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