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