1//===-- ValueEnumerator.cpp - Number values and types for bitcode writer --===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ValueEnumerator class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ValueEnumerator.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/IR/Constants.h"
18#include "llvm/IR/DerivedTypes.h"
19#include "llvm/IR/Instructions.h"
20#include "llvm/IR/Module.h"
21#include "llvm/IR/ValueSymbolTable.h"
22#include "llvm/Support/Debug.h"
23#include "llvm/Support/raw_ostream.h"
24#include <algorithm>
25using namespace llvm;
26
27namespace llvm_3_2 {
28
29static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
30  return V.first->getType()->isIntOrIntVectorTy();
31}
32
33/// ValueEnumerator - Enumerate module-level information.
34ValueEnumerator::ValueEnumerator(const Module *M) {
35  // Enumerate the global variables.
36  for (Module::const_global_iterator I = M->global_begin(),
37         E = M->global_end(); I != E; ++I)
38    EnumerateValue(I);
39
40  // Enumerate the functions.
41  for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
42    EnumerateValue(I);
43    EnumerateAttributes(cast<Function>(I)->getAttributes());
44  }
45
46  // Enumerate the aliases.
47  for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
48       I != E; ++I)
49    EnumerateValue(I);
50
51  // Remember what is the cutoff between globalvalue's and other constants.
52  unsigned FirstConstant = Values.size();
53
54  // Enumerate the global variable initializers.
55  for (Module::const_global_iterator I = M->global_begin(),
56         E = M->global_end(); I != E; ++I)
57    if (I->hasInitializer())
58      EnumerateValue(I->getInitializer());
59
60  // Enumerate the aliasees.
61  for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
62       I != E; ++I)
63    EnumerateValue(I->getAliasee());
64
65  // Insert constants and metadata that are named at module level into the slot
66  // pool so that the module symbol table can refer to them...
67  EnumerateValueSymbolTable(M->getValueSymbolTable());
68  EnumerateNamedMetadata(M);
69
70  SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
71
72  // Enumerate types used by function bodies and argument lists.
73  for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
74
75    for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
76         I != E; ++I)
77      EnumerateType(I->getType());
78
79    for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
80      for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){
81        for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
82             OI != E; ++OI) {
83          if (MDNode *MD = dyn_cast<MDNode>(*OI))
84            if (MD->isFunctionLocal() && MD->getFunction())
85              // These will get enumerated during function-incorporation.
86              continue;
87          EnumerateOperandType(*OI);
88        }
89        EnumerateType(I->getType());
90        if (const CallInst *CI = dyn_cast<CallInst>(I))
91          EnumerateAttributes(CI->getAttributes());
92        else if (const InvokeInst *II = dyn_cast<InvokeInst>(I))
93          EnumerateAttributes(II->getAttributes());
94
95        // Enumerate metadata attached with this instruction.
96        MDs.clear();
97        I->getAllMetadataOtherThanDebugLoc(MDs);
98        for (unsigned i = 0, e = MDs.size(); i != e; ++i)
99          EnumerateMetadata(MDs[i].second);
100
101        if (!I->getDebugLoc().isUnknown()) {
102          MDNode *Scope, *IA;
103          I->getDebugLoc().getScopeAndInlinedAt(Scope, IA, I->getContext());
104          if (Scope) EnumerateMetadata(Scope);
105          if (IA) EnumerateMetadata(IA);
106        }
107      }
108  }
109
110  // Optimize constant ordering.
111  OptimizeConstants(FirstConstant, Values.size());
112}
113
114unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
115  InstructionMapType::const_iterator I = InstructionMap.find(Inst);
116  assert(I != InstructionMap.end() && "Instruction is not mapped!");
117  return I->second;
118}
119
120void ValueEnumerator::setInstructionID(const Instruction *I) {
121  InstructionMap[I] = InstructionCount++;
122}
123
124unsigned ValueEnumerator::getValueID(const Value *V) const {
125  if (isa<MDNode>(V) || isa<MDString>(V)) {
126    ValueMapType::const_iterator I = MDValueMap.find(V);
127    assert(I != MDValueMap.end() && "Value not in slotcalculator!");
128    return I->second-1;
129  }
130
131  ValueMapType::const_iterator I = ValueMap.find(V);
132  assert(I != ValueMap.end() && "Value not in slotcalculator!");
133  return I->second-1;
134}
135
136void ValueEnumerator::dump() const {
137  print(dbgs(), ValueMap, "Default");
138  dbgs() << '\n';
139  print(dbgs(), MDValueMap, "MetaData");
140  dbgs() << '\n';
141}
142
143void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
144                            const char *Name) const {
145
146  OS << "Map Name: " << Name << "\n";
147  OS << "Size: " << Map.size() << "\n";
148  for (ValueMapType::const_iterator I = Map.begin(),
149         E = Map.end(); I != E; ++I) {
150
151    const Value *V = I->first;
152    if (V->hasName())
153      OS << "Value: " << V->getName();
154    else
155      OS << "Value: [null]\n";
156    V->dump();
157
158    OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
159    for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
160         UI != UE; ++UI) {
161      if (UI != V->use_begin())
162        OS << ",";
163      if((*UI)->hasName())
164        OS << " " << (*UI)->getName();
165      else
166        OS << " [null]";
167
168    }
169    OS <<  "\n\n";
170  }
171}
172
173// Optimize constant ordering.
174namespace {
175  struct CstSortPredicate {
176    ValueEnumerator &VE;
177    explicit CstSortPredicate(ValueEnumerator &ve) : VE(ve) {}
178    bool operator()(const std::pair<const Value*, unsigned> &LHS,
179                    const std::pair<const Value*, unsigned> &RHS) {
180      // Sort by plane.
181      if (LHS.first->getType() != RHS.first->getType())
182        return VE.getTypeID(LHS.first->getType()) <
183               VE.getTypeID(RHS.first->getType());
184      // Then by frequency.
185      return LHS.second > RHS.second;
186    }
187  };
188}
189
190/// OptimizeConstants - Reorder constant pool for denser encoding.
191void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
192  if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
193
194  CstSortPredicate P(*this);
195  std::stable_sort(Values.begin()+CstStart, Values.begin()+CstEnd, P);
196
197  // Ensure that integer and vector of integer constants are at the start of the
198  // constant pool.  This is important so that GEP structure indices come before
199  // gep constant exprs.
200  std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
201                 isIntOrIntVectorValue);
202
203  // Rebuild the modified portion of ValueMap.
204  for (; CstStart != CstEnd; ++CstStart)
205    ValueMap[Values[CstStart].first] = CstStart+1;
206}
207
208
209/// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
210/// table into the values table.
211void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
212  for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
213       VI != VE; ++VI)
214    EnumerateValue(VI->getValue());
215}
216
217/// EnumerateNamedMetadata - Insert all of the values referenced by
218/// named metadata in the specified module.
219void ValueEnumerator::EnumerateNamedMetadata(const Module *M) {
220  for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
221       E = M->named_metadata_end(); I != E; ++I)
222    EnumerateNamedMDNode(I);
223}
224
225void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
226  for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
227    EnumerateMetadata(MD->getOperand(i));
228}
229
230/// EnumerateMDNodeOperands - Enumerate all non-function-local values
231/// and types referenced by the given MDNode.
232void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) {
233  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
234    if (Value *V = N->getOperand(i)) {
235      if (isa<MDNode>(V) || isa<MDString>(V))
236        EnumerateMetadata(V);
237      else if (!isa<Instruction>(V) && !isa<Argument>(V))
238        EnumerateValue(V);
239    } else
240      EnumerateType(Type::getVoidTy(N->getContext()));
241  }
242}
243
244void ValueEnumerator::EnumerateMetadata(const Value *MD) {
245  assert((isa<MDNode>(MD) || isa<MDString>(MD)) && "Invalid metadata kind");
246
247  // Enumerate the type of this value.
248  EnumerateType(MD->getType());
249
250  const MDNode *N = dyn_cast<MDNode>(MD);
251
252  // In the module-level pass, skip function-local nodes themselves, but
253  // do walk their operands.
254  if (N && N->isFunctionLocal() && N->getFunction()) {
255    EnumerateMDNodeOperands(N);
256    return;
257  }
258
259  // Check to see if it's already in!
260  unsigned &MDValueID = MDValueMap[MD];
261  if (MDValueID) {
262    // Increment use count.
263    MDValues[MDValueID-1].second++;
264    return;
265  }
266  MDValues.push_back(std::make_pair(MD, 1U));
267  MDValueID = MDValues.size();
268
269  // Enumerate all non-function-local operands.
270  if (N)
271    EnumerateMDNodeOperands(N);
272}
273
274/// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
275/// information reachable from the given MDNode.
276void ValueEnumerator::EnumerateFunctionLocalMetadata(const MDNode *N) {
277  assert(N->isFunctionLocal() && N->getFunction() &&
278         "EnumerateFunctionLocalMetadata called on non-function-local mdnode!");
279
280  // Enumerate the type of this value.
281  EnumerateType(N->getType());
282
283  // Check to see if it's already in!
284  unsigned &MDValueID = MDValueMap[N];
285  if (MDValueID) {
286    // Increment use count.
287    MDValues[MDValueID-1].second++;
288    return;
289  }
290  MDValues.push_back(std::make_pair(N, 1U));
291  MDValueID = MDValues.size();
292
293  // To incoroporate function-local information visit all function-local
294  // MDNodes and all function-local values they reference.
295  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
296    if (Value *V = N->getOperand(i)) {
297      if (MDNode *O = dyn_cast<MDNode>(V)) {
298        if (O->isFunctionLocal() && O->getFunction())
299          EnumerateFunctionLocalMetadata(O);
300      } else if (isa<Instruction>(V) || isa<Argument>(V))
301        EnumerateValue(V);
302    }
303
304  // Also, collect all function-local MDNodes for easy access.
305  FunctionLocalMDs.push_back(N);
306}
307
308void ValueEnumerator::EnumerateValue(const Value *V) {
309  assert(!V->getType()->isVoidTy() && "Can't insert void values!");
310  assert(!isa<MDNode>(V) && !isa<MDString>(V) &&
311         "EnumerateValue doesn't handle Metadata!");
312
313  // Check to see if it's already in!
314  unsigned &ValueID = ValueMap[V];
315  if (ValueID) {
316    // Increment use count.
317    Values[ValueID-1].second++;
318    return;
319  }
320
321  // Enumerate the type of this value.
322  EnumerateType(V->getType());
323
324  if (const Constant *C = dyn_cast<Constant>(V)) {
325    if (isa<GlobalValue>(C)) {
326      // Initializers for globals are handled explicitly elsewhere.
327    } else if (C->getNumOperands()) {
328      // If a constant has operands, enumerate them.  This makes sure that if a
329      // constant has uses (for example an array of const ints), that they are
330      // inserted also.
331
332      // We prefer to enumerate them with values before we enumerate the user
333      // itself.  This makes it more likely that we can avoid forward references
334      // in the reader.  We know that there can be no cycles in the constants
335      // graph that don't go through a global variable.
336      for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
337           I != E; ++I)
338        if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
339          EnumerateValue(*I);
340
341      // Finally, add the value.  Doing this could make the ValueID reference be
342      // dangling, don't reuse it.
343      Values.push_back(std::make_pair(V, 1U));
344      ValueMap[V] = Values.size();
345      return;
346    } else if (const ConstantDataSequential *CDS =
347               dyn_cast<ConstantDataSequential>(C)) {
348      // For our legacy handling of the new ConstantDataSequential type, we
349      // need to enumerate the individual elements, as well as mark the
350      // outer constant as used.
351      for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
352        EnumerateValue(CDS->getElementAsConstant(i));
353      Values.push_back(std::make_pair(V, 1U));
354      ValueMap[V] = Values.size();
355      return;
356    }
357  }
358
359  // Add the value.
360  Values.push_back(std::make_pair(V, 1U));
361  ValueID = Values.size();
362}
363
364
365void ValueEnumerator::EnumerateType(Type *Ty) {
366  unsigned *TypeID = &TypeMap[Ty];
367
368  // We've already seen this type.
369  if (*TypeID)
370    return;
371
372  // If it is a non-anonymous struct, mark the type as being visited so that we
373  // don't recursively visit it.  This is safe because we allow forward
374  // references of these in the bitcode reader.
375  if (StructType *STy = dyn_cast<StructType>(Ty))
376    if (!STy->isLiteral())
377      *TypeID = ~0U;
378
379  // Enumerate all of the subtypes before we enumerate this type.  This ensures
380  // that the type will be enumerated in an order that can be directly built.
381  for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
382       I != E; ++I)
383    EnumerateType(*I);
384
385  // Refresh the TypeID pointer in case the table rehashed.
386  TypeID = &TypeMap[Ty];
387
388  // Check to see if we got the pointer another way.  This can happen when
389  // enumerating recursive types that hit the base case deeper than they start.
390  //
391  // If this is actually a struct that we are treating as forward ref'able,
392  // then emit the definition now that all of its contents are available.
393  if (*TypeID && *TypeID != ~0U)
394    return;
395
396  // Add this type now that its contents are all happily enumerated.
397  Types.push_back(Ty);
398
399  *TypeID = Types.size();
400}
401
402// Enumerate the types for the specified value.  If the value is a constant,
403// walk through it, enumerating the types of the constant.
404void ValueEnumerator::EnumerateOperandType(const Value *V) {
405  EnumerateType(V->getType());
406
407  if (const Constant *C = dyn_cast<Constant>(V)) {
408    // If this constant is already enumerated, ignore it, we know its type must
409    // be enumerated.
410    if (ValueMap.count(V)) return;
411
412    // This constant may have operands, make sure to enumerate the types in
413    // them.
414    for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
415      const Value *Op = C->getOperand(i);
416
417      // Don't enumerate basic blocks here, this happens as operands to
418      // blockaddress.
419      if (isa<BasicBlock>(Op)) continue;
420
421      EnumerateOperandType(Op);
422    }
423
424    if (const MDNode *N = dyn_cast<MDNode>(V)) {
425      for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
426        if (Value *Elem = N->getOperand(i))
427          EnumerateOperandType(Elem);
428    }
429  } else if (isa<MDString>(V) || isa<MDNode>(V))
430    EnumerateMetadata(V);
431}
432
433void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) {
434  if (PAL.isEmpty()) return;  // null is always 0.
435
436  // Do a lookup.
437  unsigned &Entry = AttributeMap[PAL];
438  if (Entry == 0) {
439    // Never saw this before, add it.
440    Attribute.push_back(PAL);
441    Entry = Attribute.size();
442  }
443
444  // Do lookups for all attribute groups.
445  for (unsigned i = 0, e = PAL.getNumSlots(); i != e; ++i) {
446    AttributeSet AS = PAL.getSlotAttributes(i);
447    unsigned &Entry = AttributeGroupMap[AS];
448    if (Entry == 0) {
449      AttributeGroups.push_back(AS);
450      Entry = AttributeGroups.size();
451    }
452  }
453}
454
455void ValueEnumerator::incorporateFunction(const Function &F) {
456  InstructionCount = 0;
457  NumModuleValues = Values.size();
458  NumModuleMDValues = MDValues.size();
459
460  // Adding function arguments to the value table.
461  for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
462       I != E; ++I)
463    EnumerateValue(I);
464
465  FirstFuncConstantID = Values.size();
466
467  // Add all function-level constants to the value table.
468  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
469    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
470      for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
471           OI != E; ++OI) {
472        if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
473            isa<InlineAsm>(*OI))
474          EnumerateValue(*OI);
475      }
476    BasicBlocks.push_back(BB);
477    ValueMap[BB] = BasicBlocks.size();
478  }
479
480  // Optimize the constant layout.
481  OptimizeConstants(FirstFuncConstantID, Values.size());
482
483  // Add the function's parameter attributes so they are available for use in
484  // the function's instruction.
485  EnumerateAttributes(F.getAttributes());
486
487  FirstInstID = Values.size();
488
489  SmallVector<MDNode *, 8> FnLocalMDVector;
490  // Add all of the instructions.
491  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
492    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
493      for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
494           OI != E; ++OI) {
495        if (MDNode *MD = dyn_cast<MDNode>(*OI))
496          if (MD->isFunctionLocal() && MD->getFunction())
497            // Enumerate metadata after the instructions they might refer to.
498            FnLocalMDVector.push_back(MD);
499      }
500
501      SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
502      I->getAllMetadataOtherThanDebugLoc(MDs);
503      for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
504        MDNode *N = MDs[i].second;
505        if (N->isFunctionLocal() && N->getFunction())
506          FnLocalMDVector.push_back(N);
507      }
508
509      if (!I->getType()->isVoidTy())
510        EnumerateValue(I);
511    }
512  }
513
514  // Add all of the function-local metadata.
515  for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
516    EnumerateFunctionLocalMetadata(FnLocalMDVector[i]);
517}
518
519void ValueEnumerator::purgeFunction() {
520  /// Remove purged values from the ValueMap.
521  for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
522    ValueMap.erase(Values[i].first);
523  for (unsigned i = NumModuleMDValues, e = MDValues.size(); i != e; ++i)
524    MDValueMap.erase(MDValues[i].first);
525  for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
526    ValueMap.erase(BasicBlocks[i]);
527
528  Values.resize(NumModuleValues);
529  MDValues.resize(NumModuleMDValues);
530  BasicBlocks.clear();
531  FunctionLocalMDs.clear();
532}
533
534static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
535                                 DenseMap<const BasicBlock*, unsigned> &IDMap) {
536  unsigned Counter = 0;
537  for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
538    IDMap[BB] = ++Counter;
539}
540
541/// getGlobalBasicBlockID - This returns the function-specific ID for the
542/// specified basic block.  This is relatively expensive information, so it
543/// should only be used by rare constructs such as address-of-label.
544unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
545  unsigned &Idx = GlobalBasicBlockIDs[BB];
546  if (Idx != 0)
547    return Idx-1;
548
549  IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
550  return getGlobalBasicBlockID(BB);
551}
552
553}  // end llvm_3_2 namespace
554