LLVM  3.7.0
ValueEnumerator.cpp
Go to the documentation of this file.
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"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/Instructions.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/UseListOrder.h"
24 #include "llvm/Support/Debug.h"
26 #include <algorithm>
27 using namespace llvm;
28 
29 namespace {
30 struct OrderMap {
32  unsigned LastGlobalConstantID;
33  unsigned LastGlobalValueID;
34 
35  OrderMap() : LastGlobalConstantID(0), LastGlobalValueID(0) {}
36 
37  bool isGlobalConstant(unsigned ID) const {
38  return ID <= LastGlobalConstantID;
39  }
40  bool isGlobalValue(unsigned ID) const {
41  return ID <= LastGlobalValueID && !isGlobalConstant(ID);
42  }
43 
44  unsigned size() const { return IDs.size(); }
45  std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
46  std::pair<unsigned, bool> lookup(const Value *V) const {
47  return IDs.lookup(V);
48  }
49  void index(const Value *V) {
50  // Explicitly sequence get-size and insert-value operations to avoid UB.
51  unsigned ID = IDs.size() + 1;
52  IDs[V].first = ID;
53  }
54 };
55 }
56 
57 static void orderValue(const Value *V, OrderMap &OM) {
58  if (OM.lookup(V).first)
59  return;
60 
61  if (const Constant *C = dyn_cast<Constant>(V))
62  if (C->getNumOperands() && !isa<GlobalValue>(C))
63  for (const Value *Op : C->operands())
64  if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
65  orderValue(Op, OM);
66 
67  // Note: we cannot cache this lookup above, since inserting into the map
68  // changes the map's size, and thus affects the other IDs.
69  OM.index(V);
70 }
71 
72 static OrderMap orderModule(const Module &M) {
73  // This needs to match the order used by ValueEnumerator::ValueEnumerator()
74  // and ValueEnumerator::incorporateFunction().
75  OrderMap OM;
76 
77  // In the reader, initializers of GlobalValues are set *after* all the
78  // globals have been read. Rather than awkwardly modeling this behaviour
79  // directly in predictValueUseListOrderImpl(), just assign IDs to
80  // initializers of GlobalValues before GlobalValues themselves to model this
81  // implicitly.
82  for (const GlobalVariable &G : M.globals())
83  if (G.hasInitializer())
84  if (!isa<GlobalValue>(G.getInitializer()))
85  orderValue(G.getInitializer(), OM);
86  for (const GlobalAlias &A : M.aliases())
87  if (!isa<GlobalValue>(A.getAliasee()))
88  orderValue(A.getAliasee(), OM);
89  for (const Function &F : M) {
90  if (F.hasPrefixData())
91  if (!isa<GlobalValue>(F.getPrefixData()))
92  orderValue(F.getPrefixData(), OM);
93  if (F.hasPrologueData())
94  if (!isa<GlobalValue>(F.getPrologueData()))
95  orderValue(F.getPrologueData(), OM);
96  if (F.hasPersonalityFn())
97  if (!isa<GlobalValue>(F.getPersonalityFn()))
98  orderValue(F.getPersonalityFn(), OM);
99  }
100  OM.LastGlobalConstantID = OM.size();
101 
102  // Initializers of GlobalValues are processed in
103  // BitcodeReader::ResolveGlobalAndAliasInits(). Match the order there rather
104  // than ValueEnumerator, and match the code in predictValueUseListOrderImpl()
105  // by giving IDs in reverse order.
106  //
107  // Since GlobalValues never reference each other directly (just through
108  // initializers), their relative IDs only matter for determining order of
109  // uses in their initializers.
110  for (const Function &F : M)
111  orderValue(&F, OM);
112  for (const GlobalAlias &A : M.aliases())
113  orderValue(&A, OM);
114  for (const GlobalVariable &G : M.globals())
115  orderValue(&G, OM);
116  OM.LastGlobalValueID = OM.size();
117 
118  for (const Function &F : M) {
119  if (F.isDeclaration())
120  continue;
121  // Here we need to match the union of ValueEnumerator::incorporateFunction()
122  // and WriteFunction(). Basic blocks are implicitly declared before
123  // anything else (by declaring their size).
124  for (const BasicBlock &BB : F)
125  orderValue(&BB, OM);
126  for (const Argument &A : F.args())
127  orderValue(&A, OM);
128  for (const BasicBlock &BB : F)
129  for (const Instruction &I : BB)
130  for (const Value *Op : I.operands())
131  if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
132  isa<InlineAsm>(*Op))
133  orderValue(Op, OM);
134  for (const BasicBlock &BB : F)
135  for (const Instruction &I : BB)
136  orderValue(&I, OM);
137  }
138  return OM;
139 }
140 
141 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
142  unsigned ID, const OrderMap &OM,
143  UseListOrderStack &Stack) {
144  // Predict use-list order for this one.
145  typedef std::pair<const Use *, unsigned> Entry;
147  for (const Use &U : V->uses())
148  // Check if this user will be serialized.
149  if (OM.lookup(U.getUser()).first)
150  List.push_back(std::make_pair(&U, List.size()));
151 
152  if (List.size() < 2)
153  // We may have lost some users.
154  return;
155 
156  bool IsGlobalValue = OM.isGlobalValue(ID);
157  std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
158  const Use *LU = L.first;
159  const Use *RU = R.first;
160  if (LU == RU)
161  return false;
162 
163  auto LID = OM.lookup(LU->getUser()).first;
164  auto RID = OM.lookup(RU->getUser()).first;
165 
166  // Global values are processed in reverse order.
167  //
168  // Moreover, initializers of GlobalValues are set *after* all the globals
169  // have been read (despite having earlier IDs). Rather than awkwardly
170  // modeling this behaviour here, orderModule() has assigned IDs to
171  // initializers of GlobalValues before GlobalValues themselves.
172  if (OM.isGlobalValue(LID) && OM.isGlobalValue(RID))
173  return LID < RID;
174 
175  // If ID is 4, then expect: 7 6 5 1 2 3.
176  if (LID < RID) {
177  if (RID <= ID)
178  if (!IsGlobalValue) // GlobalValue uses don't get reversed.
179  return true;
180  return false;
181  }
182  if (RID < LID) {
183  if (LID <= ID)
184  if (!IsGlobalValue) // GlobalValue uses don't get reversed.
185  return false;
186  return true;
187  }
188 
189  // LID and RID are equal, so we have different operands of the same user.
190  // Assume operands are added in order for all instructions.
191  if (LID <= ID)
192  if (!IsGlobalValue) // GlobalValue uses don't get reversed.
193  return LU->getOperandNo() < RU->getOperandNo();
194  return LU->getOperandNo() > RU->getOperandNo();
195  });
196 
197  if (std::is_sorted(
198  List.begin(), List.end(),
199  [](const Entry &L, const Entry &R) { return L.second < R.second; }))
200  // Order is already correct.
201  return;
202 
203  // Store the shuffle.
204  Stack.emplace_back(V, F, List.size());
205  assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
206  for (size_t I = 0, E = List.size(); I != E; ++I)
207  Stack.back().Shuffle[I] = List[I].second;
208 }
209 
210 static void predictValueUseListOrder(const Value *V, const Function *F,
211  OrderMap &OM, UseListOrderStack &Stack) {
212  auto &IDPair = OM[V];
213  assert(IDPair.first && "Unmapped value");
214  if (IDPair.second)
215  // Already predicted.
216  return;
217 
218  // Do the actual prediction.
219  IDPair.second = true;
220  if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
221  predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
222 
223  // Recursive descent into constants.
224  if (const Constant *C = dyn_cast<Constant>(V))
225  if (C->getNumOperands()) // Visit GlobalValues.
226  for (const Value *Op : C->operands())
227  if (isa<Constant>(Op)) // Visit GlobalValues.
228  predictValueUseListOrder(Op, F, OM, Stack);
229 }
230 
232  OrderMap OM = orderModule(M);
233 
234  // Use-list orders need to be serialized after all the users have been added
235  // to a value, or else the shuffles will be incomplete. Store them per
236  // function in a stack.
237  //
238  // Aside from function order, the order of values doesn't matter much here.
240 
241  // We want to visit the functions backward now so we can list function-local
242  // constants in the last Function they're used in. Module-level constants
243  // have already been visited above.
244  for (auto I = M.rbegin(), E = M.rend(); I != E; ++I) {
245  const Function &F = *I;
246  if (F.isDeclaration())
247  continue;
248  for (const BasicBlock &BB : F)
249  predictValueUseListOrder(&BB, &F, OM, Stack);
250  for (const Argument &A : F.args())
251  predictValueUseListOrder(&A, &F, OM, Stack);
252  for (const BasicBlock &BB : F)
253  for (const Instruction &I : BB)
254  for (const Value *Op : I.operands())
255  if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
256  predictValueUseListOrder(Op, &F, OM, Stack);
257  for (const BasicBlock &BB : F)
258  for (const Instruction &I : BB)
259  predictValueUseListOrder(&I, &F, OM, Stack);
260  }
261 
262  // Visit globals last, since the module-level use-list block will be seen
263  // before the function bodies are processed.
264  for (const GlobalVariable &G : M.globals())
265  predictValueUseListOrder(&G, nullptr, OM, Stack);
266  for (const Function &F : M)
267  predictValueUseListOrder(&F, nullptr, OM, Stack);
268  for (const GlobalAlias &A : M.aliases())
269  predictValueUseListOrder(&A, nullptr, OM, Stack);
270  for (const GlobalVariable &G : M.globals())
271  if (G.hasInitializer())
272  predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
273  for (const GlobalAlias &A : M.aliases())
274  predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
275  for (const Function &F : M) {
276  if (F.hasPrefixData())
277  predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
278  if (F.hasPrologueData())
279  predictValueUseListOrder(F.getPrologueData(), nullptr, OM, Stack);
280  if (F.hasPersonalityFn())
281  predictValueUseListOrder(F.getPersonalityFn(), nullptr, OM, Stack);
282  }
283 
284  return Stack;
285 }
286 
287 static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
288  return V.first->getType()->isIntOrIntVectorTy();
289 }
290 
291 ValueEnumerator::ValueEnumerator(const Module &M,
292  bool ShouldPreserveUseListOrder)
293  : HasMDString(false), HasDILocation(false), HasGenericDINode(false),
294  ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
295  if (ShouldPreserveUseListOrder)
297 
298  // Enumerate the global variables.
299  for (const GlobalVariable &GV : M.globals())
300  EnumerateValue(&GV);
301 
302  // Enumerate the functions.
303  for (const Function & F : M) {
304  EnumerateValue(&F);
305  EnumerateAttributes(F.getAttributes());
306  }
307 
308  // Enumerate the aliases.
309  for (const GlobalAlias &GA : M.aliases())
310  EnumerateValue(&GA);
311 
312  // Remember what is the cutoff between globalvalue's and other constants.
313  unsigned FirstConstant = Values.size();
314 
315  // Enumerate the global variable initializers.
316  for (const GlobalVariable &GV : M.globals())
317  if (GV.hasInitializer())
318  EnumerateValue(GV.getInitializer());
319 
320  // Enumerate the aliasees.
321  for (const GlobalAlias &GA : M.aliases())
322  EnumerateValue(GA.getAliasee());
323 
324  // Enumerate the prefix data constants.
325  for (const Function &F : M)
326  if (F.hasPrefixData())
327  EnumerateValue(F.getPrefixData());
328 
329  // Enumerate the prologue data constants.
330  for (const Function &F : M)
331  if (F.hasPrologueData())
332  EnumerateValue(F.getPrologueData());
333 
334  // Enumerate the personality functions.
335  for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
336  if (I->hasPersonalityFn())
337  EnumerateValue(I->getPersonalityFn());
338 
339  // Enumerate the metadata type.
340  //
341  // TODO: Move this to ValueEnumerator::EnumerateOperandType() once bitcode
342  // only encodes the metadata type when it's used as a value.
343  EnumerateType(Type::getMetadataTy(M.getContext()));
344 
345  // Insert constants and metadata that are named at module level into the slot
346  // pool so that the module symbol table can refer to them...
347  EnumerateValueSymbolTable(M.getValueSymbolTable());
348  EnumerateNamedMetadata(M);
349 
351 
352  // Enumerate types used by function bodies and argument lists.
353  for (const Function &F : M) {
354  for (const Argument &A : F.args())
355  EnumerateType(A.getType());
356 
357  // Enumerate metadata attached to this function.
358  F.getAllMetadata(MDs);
359  for (const auto &I : MDs)
360  EnumerateMetadata(I.second);
361 
362  for (const BasicBlock &BB : F)
363  for (const Instruction &I : BB) {
364  for (const Use &Op : I.operands()) {
365  auto *MD = dyn_cast<MetadataAsValue>(&Op);
366  if (!MD) {
367  EnumerateOperandType(Op);
368  continue;
369  }
370 
371  // Local metadata is enumerated during function-incorporation.
372  if (isa<LocalAsMetadata>(MD->getMetadata()))
373  continue;
374 
375  EnumerateMetadata(MD->getMetadata());
376  }
377  EnumerateType(I.getType());
378  if (const CallInst *CI = dyn_cast<CallInst>(&I))
379  EnumerateAttributes(CI->getAttributes());
380  else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I))
381  EnumerateAttributes(II->getAttributes());
382 
383  // Enumerate metadata attached with this instruction.
384  MDs.clear();
385  I.getAllMetadataOtherThanDebugLoc(MDs);
386  for (unsigned i = 0, e = MDs.size(); i != e; ++i)
387  EnumerateMetadata(MDs[i].second);
388 
389  // Don't enumerate the location directly -- it has a special record
390  // type -- but enumerate its operands.
391  if (DILocation *L = I.getDebugLoc())
392  EnumerateMDNodeOperands(L);
393  }
394  }
395 
396  // Optimize constant ordering.
397  OptimizeConstants(FirstConstant, Values.size());
398 }
399 
400 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
401  InstructionMapType::const_iterator I = InstructionMap.find(Inst);
402  assert(I != InstructionMap.end() && "Instruction is not mapped!");
403  return I->second;
404 }
405 
406 unsigned ValueEnumerator::getComdatID(const Comdat *C) const {
407  unsigned ComdatID = Comdats.idFor(C);
408  assert(ComdatID && "Comdat not found!");
409  return ComdatID;
410 }
411 
413  InstructionMap[I] = InstructionCount++;
414 }
415 
416 unsigned ValueEnumerator::getValueID(const Value *V) const {
417  if (auto *MD = dyn_cast<MetadataAsValue>(V))
418  return getMetadataID(MD->getMetadata());
419 
421  assert(I != ValueMap.end() && "Value not in slotcalculator!");
422  return I->second-1;
423 }
424 
425 void ValueEnumerator::dump() const {
426  print(dbgs(), ValueMap, "Default");
427  dbgs() << '\n';
428  print(dbgs(), MDValueMap, "MetaData");
429  dbgs() << '\n';
430 }
431 
433  const char *Name) const {
434 
435  OS << "Map Name: " << Name << "\n";
436  OS << "Size: " << Map.size() << "\n";
437  for (ValueMapType::const_iterator I = Map.begin(),
438  E = Map.end(); I != E; ++I) {
439 
440  const Value *V = I->first;
441  if (V->hasName())
442  OS << "Value: " << V->getName();
443  else
444  OS << "Value: [null]\n";
445  V->dump();
446 
447  OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
448  for (const Use &U : V->uses()) {
449  if (&U != &*V->use_begin())
450  OS << ",";
451  if(U->hasName())
452  OS << " " << U->getName();
453  else
454  OS << " [null]";
455 
456  }
457  OS << "\n\n";
458  }
459 }
460 
462  const char *Name) const {
463 
464  OS << "Map Name: " << Name << "\n";
465  OS << "Size: " << Map.size() << "\n";
466  for (auto I = Map.begin(), E = Map.end(); I != E; ++I) {
467  const Metadata *MD = I->first;
468  OS << "Metadata: slot = " << I->second << "\n";
469  MD->print(OS);
470  }
471 }
472 
473 /// OptimizeConstants - Reorder constant pool for denser encoding.
474 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
475  if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
476 
477  if (ShouldPreserveUseListOrder)
478  // Optimizing constants makes the use-list order difficult to predict.
479  // Disable it for now when trying to preserve the order.
480  return;
481 
482  std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
483  [this](const std::pair<const Value *, unsigned> &LHS,
484  const std::pair<const Value *, unsigned> &RHS) {
485  // Sort by plane.
486  if (LHS.first->getType() != RHS.first->getType())
487  return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
488  // Then by frequency.
489  return LHS.second > RHS.second;
490  });
491 
492  // Ensure that integer and vector of integer constants are at the start of the
493  // constant pool. This is important so that GEP structure indices come before
494  // gep constant exprs.
495  std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
497 
498  // Rebuild the modified portion of ValueMap.
499  for (; CstStart != CstEnd; ++CstStart)
500  ValueMap[Values[CstStart].first] = CstStart+1;
501 }
502 
503 
504 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
505 /// table into the values table.
506 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
507  for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
508  VI != VE; ++VI)
509  EnumerateValue(VI->getValue());
510 }
511 
512 /// Insert all of the values referenced by named metadata in the specified
513 /// module.
514 void ValueEnumerator::EnumerateNamedMetadata(const Module &M) {
516  E = M.named_metadata_end();
517  I != E; ++I)
518  EnumerateNamedMDNode(I);
519 }
520 
521 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
522  for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
523  EnumerateMetadata(MD->getOperand(i));
524 }
525 
526 /// EnumerateMDNodeOperands - Enumerate all non-function-local values
527 /// and types referenced by the given MDNode.
528 void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) {
529  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
530  Metadata *MD = N->getOperand(i);
531  if (!MD)
532  continue;
533  assert(!isa<LocalAsMetadata>(MD) && "MDNodes cannot be function-local");
534  EnumerateMetadata(MD);
535  }
536 }
537 
538 void ValueEnumerator::EnumerateMetadata(const Metadata *MD) {
539  assert(
540  (isa<MDNode>(MD) || isa<MDString>(MD) || isa<ConstantAsMetadata>(MD)) &&
541  "Invalid metadata kind");
542 
543  // Insert a dummy ID to block the co-recursive call to
544  // EnumerateMDNodeOperands() from re-visiting MD in a cyclic graph.
545  //
546  // Return early if there's already an ID.
547  if (!MDValueMap.insert(std::make_pair(MD, 0)).second)
548  return;
549 
550  // Visit operands first to minimize RAUW.
551  if (auto *N = dyn_cast<MDNode>(MD))
552  EnumerateMDNodeOperands(N);
553  else if (auto *C = dyn_cast<ConstantAsMetadata>(MD))
554  EnumerateValue(C->getValue());
555 
556  HasMDString |= isa<MDString>(MD);
557  HasDILocation |= isa<DILocation>(MD);
558  HasGenericDINode |= isa<GenericDINode>(MD);
559 
560  // Replace the dummy ID inserted above with the correct one. MDValueMap may
561  // have changed by inserting operands, so we need a fresh lookup here.
562  MDs.push_back(MD);
563  MDValueMap[MD] = MDs.size();
564 }
565 
566 /// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
567 /// information reachable from the metadata.
568 void ValueEnumerator::EnumerateFunctionLocalMetadata(
569  const LocalAsMetadata *Local) {
570  // Check to see if it's already in!
571  unsigned &MDValueID = MDValueMap[Local];
572  if (MDValueID)
573  return;
574 
575  MDs.push_back(Local);
576  MDValueID = MDs.size();
577 
578  EnumerateValue(Local->getValue());
579 
580  // Also, collect all function-local metadata for easy access.
581  FunctionLocalMDs.push_back(Local);
582 }
583 
584 void ValueEnumerator::EnumerateValue(const Value *V) {
585  assert(!V->getType()->isVoidTy() && "Can't insert void values!");
586  assert(!isa<MetadataAsValue>(V) && "EnumerateValue doesn't handle Metadata!");
587 
588  // Check to see if it's already in!
589  unsigned &ValueID = ValueMap[V];
590  if (ValueID) {
591  // Increment use count.
592  Values[ValueID-1].second++;
593  return;
594  }
595 
596  if (auto *GO = dyn_cast<GlobalObject>(V))
597  if (const Comdat *C = GO->getComdat())
598  Comdats.insert(C);
599 
600  // Enumerate the type of this value.
601  EnumerateType(V->getType());
602 
603  if (const Constant *C = dyn_cast<Constant>(V)) {
604  if (isa<GlobalValue>(C)) {
605  // Initializers for globals are handled explicitly elsewhere.
606  } else if (C->getNumOperands()) {
607  // If a constant has operands, enumerate them. This makes sure that if a
608  // constant has uses (for example an array of const ints), that they are
609  // inserted also.
610 
611  // We prefer to enumerate them with values before we enumerate the user
612  // itself. This makes it more likely that we can avoid forward references
613  // in the reader. We know that there can be no cycles in the constants
614  // graph that don't go through a global variable.
615  for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
616  I != E; ++I)
617  if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
618  EnumerateValue(*I);
619 
620  // Finally, add the value. Doing this could make the ValueID reference be
621  // dangling, don't reuse it.
622  Values.push_back(std::make_pair(V, 1U));
623  ValueMap[V] = Values.size();
624  return;
625  }
626  }
627 
628  // Add the value.
629  Values.push_back(std::make_pair(V, 1U));
630  ValueID = Values.size();
631 }
632 
633 
634 void ValueEnumerator::EnumerateType(Type *Ty) {
635  unsigned *TypeID = &TypeMap[Ty];
636 
637  // We've already seen this type.
638  if (*TypeID)
639  return;
640 
641  // If it is a non-anonymous struct, mark the type as being visited so that we
642  // don't recursively visit it. This is safe because we allow forward
643  // references of these in the bitcode reader.
644  if (StructType *STy = dyn_cast<StructType>(Ty))
645  if (!STy->isLiteral())
646  *TypeID = ~0U;
647 
648  // Enumerate all of the subtypes before we enumerate this type. This ensures
649  // that the type will be enumerated in an order that can be directly built.
650  for (Type *SubTy : Ty->subtypes())
651  EnumerateType(SubTy);
652 
653  // Refresh the TypeID pointer in case the table rehashed.
654  TypeID = &TypeMap[Ty];
655 
656  // Check to see if we got the pointer another way. This can happen when
657  // enumerating recursive types that hit the base case deeper than they start.
658  //
659  // If this is actually a struct that we are treating as forward ref'able,
660  // then emit the definition now that all of its contents are available.
661  if (*TypeID && *TypeID != ~0U)
662  return;
663 
664  // Add this type now that its contents are all happily enumerated.
665  Types.push_back(Ty);
666 
667  *TypeID = Types.size();
668 }
669 
670 // Enumerate the types for the specified value. If the value is a constant,
671 // walk through it, enumerating the types of the constant.
672 void ValueEnumerator::EnumerateOperandType(const Value *V) {
673  EnumerateType(V->getType());
674 
675  if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
676  assert(!isa<LocalAsMetadata>(MD->getMetadata()) &&
677  "Function-local metadata should be left for later");
678 
679  EnumerateMetadata(MD->getMetadata());
680  return;
681  }
682 
683  const Constant *C = dyn_cast<Constant>(V);
684  if (!C)
685  return;
686 
687  // If this constant is already enumerated, ignore it, we know its type must
688  // be enumerated.
689  if (ValueMap.count(C))
690  return;
691 
692  // This constant may have operands, make sure to enumerate the types in
693  // them.
694  for (const Value *Op : C->operands()) {
695  // Don't enumerate basic blocks here, this happens as operands to
696  // blockaddress.
697  if (isa<BasicBlock>(Op))
698  continue;
699 
700  EnumerateOperandType(Op);
701  }
702 }
703 
704 void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) {
705  if (PAL.isEmpty()) return; // null is always 0.
706 
707  // Do a lookup.
708  unsigned &Entry = AttributeMap[PAL];
709  if (Entry == 0) {
710  // Never saw this before, add it.
711  Attribute.push_back(PAL);
712  Entry = Attribute.size();
713  }
714 
715  // Do lookups for all attribute groups.
716  for (unsigned i = 0, e = PAL.getNumSlots(); i != e; ++i) {
717  AttributeSet AS = PAL.getSlotAttributes(i);
718  unsigned &Entry = AttributeGroupMap[AS];
719  if (Entry == 0) {
720  AttributeGroups.push_back(AS);
721  Entry = AttributeGroups.size();
722  }
723  }
724 }
725 
727  InstructionCount = 0;
728  NumModuleValues = Values.size();
729  NumModuleMDs = MDs.size();
730 
731  // Adding function arguments to the value table.
732  for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
733  I != E; ++I)
734  EnumerateValue(I);
735 
736  FirstFuncConstantID = Values.size();
737 
738  // Add all function-level constants to the value table.
739  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
740  for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
741  for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
742  OI != E; ++OI) {
743  if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
744  isa<InlineAsm>(*OI))
745  EnumerateValue(*OI);
746  }
747  BasicBlocks.push_back(BB);
748  ValueMap[BB] = BasicBlocks.size();
749  }
750 
751  // Optimize the constant layout.
752  OptimizeConstants(FirstFuncConstantID, Values.size());
753 
754  // Add the function's parameter attributes so they are available for use in
755  // the function's instruction.
756  EnumerateAttributes(F.getAttributes());
757 
758  FirstInstID = Values.size();
759 
760  SmallVector<LocalAsMetadata *, 8> FnLocalMDVector;
761  // Add all of the instructions.
762  for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
763  for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
764  for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
765  OI != E; ++OI) {
766  if (auto *MD = dyn_cast<MetadataAsValue>(&*OI))
767  if (auto *Local = dyn_cast<LocalAsMetadata>(MD->getMetadata()))
768  // Enumerate metadata after the instructions they might refer to.
769  FnLocalMDVector.push_back(Local);
770  }
771 
772  if (!I->getType()->isVoidTy())
773  EnumerateValue(I);
774  }
775  }
776 
777  // Add all of the function-local metadata.
778  for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
779  EnumerateFunctionLocalMetadata(FnLocalMDVector[i]);
780 }
781 
783  /// Remove purged values from the ValueMap.
784  for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
785  ValueMap.erase(Values[i].first);
786  for (unsigned i = NumModuleMDs, e = MDs.size(); i != e; ++i)
787  MDValueMap.erase(MDs[i]);
788  for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
789  ValueMap.erase(BasicBlocks[i]);
790 
791  Values.resize(NumModuleValues);
792  MDs.resize(NumModuleMDs);
793  BasicBlocks.clear();
794  FunctionLocalMDs.clear();
795 }
796 
799  unsigned Counter = 0;
800  for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
801  IDMap[BB] = ++Counter;
802 }
803 
804 /// getGlobalBasicBlockID - This returns the function-specific ID for the
805 /// specified basic block. This is relatively expensive information, so it
806 /// should only be used by rare constructs such as address-of-label.
808  unsigned &Idx = GlobalBasicBlockIDs[BB];
809  if (Idx != 0)
810  return Idx-1;
811 
812  IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
813  return getGlobalBasicBlockID(BB);
814 }
815 
817  return Log2_32_Ceil(getTypes().size() + 1);
818 }
use_iterator use_end()
Definition: Value.h:281
unsigned Log2_32_Ceil(uint32_t Value)
Log2_32_Ceil - This function returns the ceil log base 2 of the specified value, 32 if the value is z...
Definition: MathExtras.h:481
This class provides a symbol table of name/value pairs.
iterator_range< use_iterator > uses()
Definition: Value.h:283
LLVM Argument representation.
Definition: Argument.h:35
iterator begin()
Get an iterator that from the beginning of the symbol table.
bool hasName() const
Definition: Value.h:228
static void predictValueUseListOrder(const Value *V, const Function *F, OrderMap &OM, UseListOrderStack &Stack)
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:114
iterator end()
Definition: Function.h:459
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:942
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: ValueMap.h:128
CallInst - This class represents a function call, abstracting a target machine's calling convention...
named_metadata_iterator named_metadata_end()
Definition: Module.h:614
void setInstructionID(const Instruction *I)
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:111
arg_iterator arg_end()
Definition: Function.h:480
Metadata node.
Definition: Metadata.h:740
F(f)
static Type * getMetadataTy(LLVMContext &C)
Definition: Type.cpp:230
static void predictValueUseListOrderImpl(const Value *V, const Function *F, unsigned ID, const OrderMap &OM, UseListOrderStack &Stack)
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:188
void incorporateFunction(const Function &F)
incorporateFunction/purgeFunction - If you'd like to deal with a function, use these two methods to g...
static bool isIntOrIntVectorValue(const std::pair< const Value *, unsigned > &V)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:169
A tuple of MDNodes.
Definition: Metadata.h:1127
unsigned getComdatID(const Comdat *C) const
StructType - Class to represent struct types.
Definition: DerivedTypes.h:191
A Use represents the edge between a Value definition and its users.
Definition: Use.h:69
std::vector< UseListOrder > UseListOrderStack
Definition: UseListOrder.h:52
TypeID
Definitions of all of the base types for the Type system.
Definition: Type.h:54
#define false
Definition: ConvertUTF.c:65
uint64_t computeBitsRequiredForTypeIndicies() const
#define G(x, y, z)
Definition: MD5.cpp:52
unsigned idFor(const T &Entry) const
idFor - return the ID for an existing entry.
Definition: UniqueVector.h:58
reverse_iterator rend()
Definition: Module.h:575
const TypeList & getTypes() const
unsigned getInstructionID(const Instruction *I) const
unsigned getValueID(const Value *V) const
iterator find(const KeyT &Val)
Definition: ValueMap.h:132
iterator end()
Get an iterator to the end of the symbol table.
Debug location.
iterator begin()
Definition: Function.h:457
unsigned getNumSlots() const
Return the number of slots used in this attribute list.
bool erase(const KeyT &Val)
Definition: DenseMap.h:206
unsigned getTypeID(Type *T) const
LLVM Basic Block Representation.
Definition: BasicBlock.h:65
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
AttributeSet getSlotAttributes(unsigned Slot) const
Return the attributes at the given slot.
This is an important base class in LLVM.
Definition: Constant.h:41
This file contains the declarations for the subclasses of Constant, which represent the different fla...
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:965
static OrderMap orderModule(const Module &M)
op_range operands()
Definition: User.h:191
arg_iterator arg_begin()
Definition: Function.h:472
static UseListOrderStack predictUseListOrder(const Module &M)
Metadata wrapper in the Value hierarchy.
Definition: Metadata.h:172
void print(raw_ostream &OS, const Module *M=nullptr) const
Print.
Definition: AsmWriter.cpp:3341
void dump() const
Support for debugging, callable in GDB: V->dump()
Definition: AsmWriter.cpp:3353
reverse_iterator rbegin()
Definition: Module.h:573
iterator end()
Definition: ValueMap.h:112
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:936
See the file comment.
Definition: ValueMap.h:80
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:222
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:123
AttributeSet getAttributes() const
Return the attribute list for this Function.
Definition: Function.h:181
unsigned getMetadataID(const Metadata *MD) const
UseListOrderStack UseListOrders
LLVM_ATTRIBUTE_UNUSED_RESULT std::enable_if< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:285
use_iterator use_begin()
Definition: Value.h:279
static const uint16_t * lookup(unsigned opcode, unsigned domain)
static void orderValue(const Value *V, OrderMap &OM)
unsigned size() const
Definition: DenseMap.h:82
void print(raw_ostream &OS, const ValueMapType &Map, const char *Name) const
unsigned insert(const T &Entry)
insert - Append entry to the vector if it doesn't already exist.
Definition: UniqueVector.h:41
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:128
iterator begin()
Definition: DenseMap.h:64
Value * getValue() const
Definition: Metadata.h:287
#define I(x, y, z)
Definition: MD5.cpp:54
#define N
iterator end()
Definition: DenseMap.h:68
iterator find(const KeyT &Val)
Definition: DenseMap.h:124
void size_t size
static void IncorporateFunctionInfoGlobalBBIDs(const Function *F, DenseMap< const BasicBlock *, unsigned > &IDMap)
bool use_empty() const
Definition: Value.h:275
unsigned getGlobalBasicBlockID(const BasicBlock *BB) const
getGlobalBasicBlockID - This returns the function-specific ID for the specified basic block...
LLVM Value Representation.
Definition: Value.h:69
unsigned getNumOperands() const
Definition: Metadata.cpp:961
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:38
InvokeInst - Invoke instruction.
iterator_range< global_iterator > globals()
Definition: Module.h:558
Root of the metadata hierarchy.
Definition: Metadata.h:45
bool isEmpty() const
Return true if there are no attributes.
Definition: Attributes.h:390
named_metadata_iterator named_metadata_begin()
Definition: Module.h:609
bool erase(const KeyT &Val)
Definition: ValueMap.h:168
ArrayRef< Type * > subtypes() const
Definition: Type.h:316
bool isVoidTy() const
isVoidTy - Return true if this is 'void'.
Definition: Type.h:137
iterator_range< alias_iterator > aliases()
Definition: Module.h:598