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