blob: f0f9f7430c531e2c6f6e93c0194c324dcc7450da [file] [log] [blame]
Chris Lattnerc1d10d62007-04-22 06:24:45 +00001//===-- ValueEnumerator.cpp - Number values and types for bitcode writer --===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerc1d10d62007-04-22 06:24:45 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ValueEnumerator class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ValueEnumerator.h"
Rafael Espindola337a1b22011-04-06 16:49:37 +000015#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/Constants.h"
18#include "llvm/IR/DerivedTypes.h"
19#include "llvm/IR/Instructions.h"
20#include "llvm/IR/Module.h"
Duncan P. N. Exon Smith15eb0ab2014-07-25 16:13:16 +000021#include "llvm/IR/UseListOrder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/ValueSymbolTable.h"
Chad Rosier78037a92011-12-07 20:44:46 +000023#include "llvm/Support/Debug.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattnera8713be2007-05-04 05:05:48 +000025#include <algorithm>
Chris Lattnerc1d10d62007-04-22 06:24:45 +000026using namespace llvm;
27
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +000028namespace {
29typedef DenseMap<const Value *, std::pair<unsigned, bool>> OrderMap;
30}
31
32static void orderValue(const Value *V, OrderMap &OM) {
33 if (OM.lookup(V).first)
34 return;
35
36 if (const Constant *C = dyn_cast<Constant>(V))
37 if (C->getNumOperands() && !isa<GlobalValue>(C))
38 for (const Value *Op : C->operands())
39 if (!isa<BasicBlock>(Op))
40 orderValue(Op, OM);
41
42 // Note: we cannot cache this lookup above, since inserting into the map
43 // changes the map's size, and thus affects the ID.
44 OM[V].first = OM.size() + 1;
45}
46
47static OrderMap orderModule(const Module *M) {
48 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
49 // and ValueEnumerator::incorporateFunction().
50 OrderMap OM;
51
52 for (const GlobalVariable &G : M->globals())
53 orderValue(&G, OM);
54 for (const Function &F : *M)
55 orderValue(&F, OM);
56 for (const GlobalAlias &A : M->aliases())
57 orderValue(&A, OM);
58 for (const GlobalVariable &G : M->globals())
59 if (G.hasInitializer())
60 orderValue(G.getInitializer(), OM);
61 for (const GlobalAlias &A : M->aliases())
62 orderValue(A.getAliasee(), OM);
63 for (const Function &F : *M)
64 if (F.hasPrefixData())
65 orderValue(F.getPrefixData(), OM);
66
67 for (const Function &F : *M) {
68 if (F.isDeclaration())
69 continue;
70 // Here we need to match the union of ValueEnumerator::incorporateFunction()
71 // and WriteFunction(). Basic blocks are implicitly declared before
72 // anything else (by declaring their size).
73 for (const BasicBlock &BB : F)
74 orderValue(&BB, OM);
75 for (const Argument &A : F.args())
76 orderValue(&A, OM);
77 for (const BasicBlock &BB : F)
78 for (const Instruction &I : BB)
79 for (const Value *Op : I.operands())
80 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
81 isa<InlineAsm>(*Op))
82 orderValue(Op, OM);
83 for (const BasicBlock &BB : F)
84 for (const Instruction &I : BB)
85 orderValue(&I, OM);
86 }
87 return OM;
88}
89
90static void predictValueUseListOrderImpl(const Value *V, const Function *F,
91 unsigned ID, const OrderMap &OM,
92 UseListOrderStack &Stack) {
93 // Predict use-list order for this one.
94 typedef std::pair<const Use *, unsigned> Entry;
95 SmallVector<Entry, 64> List;
96 for (const Use &U : V->uses())
97 // Check if this user will be serialized.
98 if (OM.lookup(U.getUser()).first)
99 List.push_back(std::make_pair(&U, List.size()));
100
101 if (List.size() < 2)
102 // We may have lost some users.
103 return;
104
105 std::sort(List.begin(), List.end(),
106 [&OM, ID](const Entry &L, const Entry &R) {
107 const Use *LU = L.first;
108 const Use *RU = R.first;
Duncan P. N. Exon Smith3f0fc7b2014-07-29 01:13:56 +0000109 if (LU == RU)
110 return false;
111
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000112 auto LID = OM.lookup(LU->getUser()).first;
113 auto RID = OM.lookup(RU->getUser()).first;
114 // If ID is 4, then expect: 7 6 5 1 2 3.
115 if (LID < RID) {
116 if (RID < ID)
117 return true;
118 return false;
119 }
120 if (RID < LID) {
121 if (LID < ID)
122 return false;
123 return true;
124 }
125 // LID and RID are equal, so we have different operands of the same user.
126 // Assume operands are added in order for all instructions.
127 if (LU->getOperandNo() < RU->getOperandNo())
128 return LID < ID;
129 return ID < LID;
130 });
131
132 if (std::is_sorted(
133 List.begin(), List.end(),
134 [](const Entry &L, const Entry &R) { return L.second < R.second; }))
135 // Order is already correct.
136 return;
137
138 // Store the shuffle.
Duncan P. N. Exon Smithf849ace2014-07-28 22:41:50 +0000139 UseListOrder O(V, F, List.size());
140 assert(List.size() == O.Shuffle.size() && "Wrong size");
141 for (size_t I = 0, E = List.size(); I != E; ++I)
142 O.Shuffle[I] = List[I].second;
143 Stack.emplace_back(std::move(O));
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000144}
145
146static void predictValueUseListOrder(const Value *V, const Function *F,
147 OrderMap &OM, UseListOrderStack &Stack) {
148 auto &IDPair = OM[V];
149 assert(IDPair.first && "Unmapped value");
150 if (IDPair.second)
151 // Already predicted.
152 return;
153
154 // Do the actual prediction.
155 IDPair.second = true;
156 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
157 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
158
159 // Recursive descent into constants.
160 if (const Constant *C = dyn_cast<Constant>(V))
161 if (C->getNumOperands() && !isa<GlobalValue>(C))
162 for (const Value *Op : C->operands())
163 if (isa<Constant>(Op) && !isa<GlobalValue>(Op))
164 predictValueUseListOrder(Op, F, OM, Stack);
165}
166
167static UseListOrderStack predictUseListOrder(const Module *M) {
168 OrderMap OM = orderModule(M);
169
170 // Use-list orders need to be serialized after all the users have been added
171 // to a value, or else the shuffles will be incomplete. Store them per
172 // function in a stack.
173 //
174 // Aside from function order, the order of values doesn't matter much here.
175 UseListOrderStack Stack;
176
177 // We want to visit the functions backward now so we can list function-local
178 // constants in the last Function they're used in. Module-level constants
179 // have already been visited above.
180 for (auto I = M->rbegin(), E = M->rend(); I != E; ++I) {
181 const Function &F = *I;
182 if (F.isDeclaration())
183 continue;
184 for (const BasicBlock &BB : F)
185 predictValueUseListOrder(&BB, &F, OM, Stack);
186 for (const Argument &A : F.args())
187 predictValueUseListOrder(&A, &F, OM, Stack);
188 for (const BasicBlock &BB : F)
189 for (const Instruction &I : BB)
190 for (const Value *Op : I.operands())
191 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
192 isa<InlineAsm>(*Op))
193 predictValueUseListOrder(Op, &F, OM, Stack);
194 for (const BasicBlock &BB : F)
195 for (const Instruction &I : BB)
196 predictValueUseListOrder(&I, &F, OM, Stack);
197 }
198
199 // Visit globals last, since the module-level use-list block will be seen
200 // before the function bodies are processed.
201 for (const GlobalVariable &G : M->globals())
202 predictValueUseListOrder(&G, nullptr, OM, Stack);
203 for (const Function &F : *M)
204 predictValueUseListOrder(&F, nullptr, OM, Stack);
205 for (const GlobalAlias &A : M->aliases())
206 predictValueUseListOrder(&A, nullptr, OM, Stack);
207 for (const GlobalVariable &G : M->globals())
208 if (G.hasInitializer())
209 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
210 for (const GlobalAlias &A : M->aliases())
211 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
212 for (const Function &F : *M)
213 if (F.hasPrefixData())
214 predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
215
216 return Stack;
217}
218
Duncan Sandse6beec62012-11-13 12:59:33 +0000219static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
220 return V.first->getType()->isIntOrIntVectorTy();
Chris Lattner430e80d2007-05-04 05:21:47 +0000221}
222
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000223/// ValueEnumerator - Enumerate module-level information.
224ValueEnumerator::ValueEnumerator(const Module *M) {
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000225 if (shouldPreserveBitcodeUseListOrder())
226 UseListOrders = predictUseListOrder(M);
227
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000228 // Enumerate the global variables.
229 for (Module::const_global_iterator I = M->global_begin(),
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +0000230
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000231 E = M->global_end(); I != E; ++I)
232 EnumerateValue(I);
233
234 // Enumerate the functions.
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000235 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000236 EnumerateValue(I);
Devang Patel4c758ea2008-09-25 21:00:45 +0000237 EnumerateAttributes(cast<Function>(I)->getAttributes());
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000238 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000239
Chris Lattner44c17072007-04-26 02:46:40 +0000240 // Enumerate the aliases.
241 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
242 I != E; ++I)
243 EnumerateValue(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000244
Chris Lattner430e80d2007-05-04 05:21:47 +0000245 // Remember what is the cutoff between globalvalue's and other constants.
246 unsigned FirstConstant = Values.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000247
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000248 // Enumerate the global variable initializers.
249 for (Module::const_global_iterator I = M->global_begin(),
250 E = M->global_end(); I != E; ++I)
251 if (I->hasInitializer())
252 EnumerateValue(I->getInitializer());
253
Chris Lattner44c17072007-04-26 02:46:40 +0000254 // Enumerate the aliasees.
255 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
256 I != E; ++I)
257 EnumerateValue(I->getAliasee());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000258
Peter Collingbourne3fa50f92013-09-16 01:08:15 +0000259 // Enumerate the prefix data constants.
260 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
261 if (I->hasPrefixData())
262 EnumerateValue(I->getPrefixData());
263
Joe Abbeybc6f4ba2013-04-01 02:28:07 +0000264 // Insert constants and metadata that are named at module level into the slot
Devang Patelfcfee0f2010-01-07 19:39:36 +0000265 // pool so that the module symbol table can refer to them...
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000266 EnumerateValueSymbolTable(M->getValueSymbolTable());
Dan Gohman2637cc12010-07-21 23:38:33 +0000267 EnumerateNamedMetadata(M);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000268
Chris Lattner8dace892009-12-31 00:51:46 +0000269 SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
270
Chris Lattner5f640b92007-04-26 03:50:57 +0000271 // Enumerate types used by function bodies and argument lists.
Rafael Espindola087d6272014-06-17 03:00:40 +0000272 for (const Function &F : *M) {
273 for (const Argument &A : F.args())
274 EnumerateType(A.getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000275
Rafael Espindola087d6272014-06-17 03:00:40 +0000276 for (const BasicBlock &BB : F)
277 for (const Instruction &I : BB) {
278 for (const Use &Op : I.operands()) {
279 if (MDNode *MD = dyn_cast<MDNode>(&Op))
Victor Hernandez1b081382010-02-06 01:21:09 +0000280 if (MD->isFunctionLocal() && MD->getFunction())
Victor Hernandez572218b2010-01-14 19:54:11 +0000281 // These will get enumerated during function-incorporation.
282 continue;
Rafael Espindola087d6272014-06-17 03:00:40 +0000283 EnumerateOperandType(Op);
Victor Hernandez572218b2010-01-14 19:54:11 +0000284 }
Rafael Espindola087d6272014-06-17 03:00:40 +0000285 EnumerateType(I.getType());
286 if (const CallInst *CI = dyn_cast<CallInst>(&I))
Devang Patel4c758ea2008-09-25 21:00:45 +0000287 EnumerateAttributes(CI->getAttributes());
Rafael Espindola087d6272014-06-17 03:00:40 +0000288 else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I))
Devang Patel4c758ea2008-09-25 21:00:45 +0000289 EnumerateAttributes(II->getAttributes());
Devang Patelaf206b82009-09-18 19:26:43 +0000290
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000291 // Enumerate metadata attached with this instruction.
Devang Patel6da5dbf2009-10-22 18:55:16 +0000292 MDs.clear();
Rafael Espindola087d6272014-06-17 03:00:40 +0000293 I.getAllMetadataOtherThanDebugLoc(MDs);
Chris Lattner2f2aa2b2009-12-28 23:41:32 +0000294 for (unsigned i = 0, e = MDs.size(); i != e; ++i)
Victor Hernandez572218b2010-01-14 19:54:11 +0000295 EnumerateMetadata(MDs[i].second);
Joe Abbey2ad8df22012-11-25 15:23:39 +0000296
Rafael Espindola087d6272014-06-17 03:00:40 +0000297 if (!I.getDebugLoc().isUnknown()) {
Chris Lattner07d09ed2010-04-03 02:17:50 +0000298 MDNode *Scope, *IA;
Rafael Espindola087d6272014-06-17 03:00:40 +0000299 I.getDebugLoc().getScopeAndInlinedAt(Scope, IA, I.getContext());
Chris Lattner07d09ed2010-04-03 02:17:50 +0000300 if (Scope) EnumerateMetadata(Scope);
301 if (IA) EnumerateMetadata(IA);
302 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000303 }
304 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000305
Chris Lattner430e80d2007-05-04 05:21:47 +0000306 // Optimize constant ordering.
307 OptimizeConstants(FirstConstant, Values.size());
Rafael Espindola337a1b22011-04-06 16:49:37 +0000308}
309
Devang Patelaf206b82009-09-18 19:26:43 +0000310unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
311 InstructionMapType::const_iterator I = InstructionMap.find(Inst);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000312 assert(I != InstructionMap.end() && "Instruction is not mapped!");
Dan Gohman1f4b0282010-08-25 17:09:50 +0000313 return I->second;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000314}
Devang Patelaf206b82009-09-18 19:26:43 +0000315
David Majnemerdad0a642014-06-27 18:19:56 +0000316unsigned ValueEnumerator::getComdatID(const Comdat *C) const {
317 unsigned ComdatID = Comdats.idFor(C);
318 assert(ComdatID && "Comdat not found!");
319 return ComdatID;
320}
321
Devang Patelaf206b82009-09-18 19:26:43 +0000322void ValueEnumerator::setInstructionID(const Instruction *I) {
323 InstructionMap[I] = InstructionCount++;
324}
325
Devang Patel05eb6172009-08-04 06:00:18 +0000326unsigned ValueEnumerator::getValueID(const Value *V) const {
Devang Patelac277eb2010-01-22 22:52:10 +0000327 if (isa<MDNode>(V) || isa<MDString>(V)) {
Devang Patel05eb6172009-08-04 06:00:18 +0000328 ValueMapType::const_iterator I = MDValueMap.find(V);
329 assert(I != MDValueMap.end() && "Value not in slotcalculator!");
330 return I->second-1;
331 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000332
Devang Patel05eb6172009-08-04 06:00:18 +0000333 ValueMapType::const_iterator I = ValueMap.find(V);
334 assert(I != ValueMap.end() && "Value not in slotcalculator!");
335 return I->second-1;
336}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000337
Chad Rosier78037a92011-12-07 20:44:46 +0000338void ValueEnumerator::dump() const {
339 print(dbgs(), ValueMap, "Default");
340 dbgs() << '\n';
341 print(dbgs(), MDValueMap, "MetaData");
342 dbgs() << '\n';
343}
344
345void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
346 const char *Name) const {
347
348 OS << "Map Name: " << Name << "\n";
349 OS << "Size: " << Map.size() << "\n";
350 for (ValueMapType::const_iterator I = Map.begin(),
351 E = Map.end(); I != E; ++I) {
352
353 const Value *V = I->first;
354 if (V->hasName())
355 OS << "Value: " << V->getName();
356 else
357 OS << "Value: [null]\n";
358 V->dump();
359
360 OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
Chandler Carruthcdf47882014-03-09 03:16:01 +0000361 for (const Use &U : V->uses()) {
362 if (&U != &*V->use_begin())
Chad Rosier78037a92011-12-07 20:44:46 +0000363 OS << ",";
Chandler Carruthcdf47882014-03-09 03:16:01 +0000364 if(U->hasName())
365 OS << " " << U->getName();
Chad Rosier78037a92011-12-07 20:44:46 +0000366 else
367 OS << " [null]";
368
369 }
370 OS << "\n\n";
371 }
372}
373
Chris Lattner430e80d2007-05-04 05:21:47 +0000374/// OptimizeConstants - Reorder constant pool for denser encoding.
375void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
376 if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000377
Duncan P. N. Exon Smith15eb0ab2014-07-25 16:13:16 +0000378 if (shouldPreserveBitcodeUseListOrder())
379 // Optimizing constants makes the use-list order difficult to predict.
380 // Disable it for now when trying to preserve the order.
381 return;
382
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000383 std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
384 [this](const std::pair<const Value *, unsigned> &LHS,
385 const std::pair<const Value *, unsigned> &RHS) {
386 // Sort by plane.
387 if (LHS.first->getType() != RHS.first->getType())
388 return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
389 // Then by frequency.
390 return LHS.second > RHS.second;
391 });
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000392
Duncan Sandse6beec62012-11-13 12:59:33 +0000393 // Ensure that integer and vector of integer constants are at the start of the
394 // constant pool. This is important so that GEP structure indices come before
395 // gep constant exprs.
Chris Lattner430e80d2007-05-04 05:21:47 +0000396 std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
Duncan Sandse6beec62012-11-13 12:59:33 +0000397 isIntOrIntVectorValue);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000398
Chris Lattner430e80d2007-05-04 05:21:47 +0000399 // Rebuild the modified portion of ValueMap.
400 for (; CstStart != CstEnd; ++CstStart)
401 ValueMap[Values[CstStart].first] = CstStart+1;
402}
403
404
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000405/// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
406/// table into the values table.
407void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000408 for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000409 VI != VE; ++VI)
410 EnumerateValue(VI->getValue());
411}
412
Dan Gohman2637cc12010-07-21 23:38:33 +0000413/// EnumerateNamedMetadata - Insert all of the values referenced by
414/// named metadata in the specified module.
415void ValueEnumerator::EnumerateNamedMetadata(const Module *M) {
416 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
417 E = M->named_metadata_end(); I != E; ++I)
418 EnumerateNamedMDNode(I);
Devang Patelfcfee0f2010-01-07 19:39:36 +0000419}
420
Devang Patel99ff5a82010-01-09 00:30:14 +0000421void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
Devang Patel99ff5a82010-01-09 00:30:14 +0000422 for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
Dan Gohmand3d2bbe2010-08-24 02:01:24 +0000423 EnumerateMetadata(MD->getOperand(i));
Devang Patel99ff5a82010-01-09 00:30:14 +0000424}
425
Dan Gohmanc828c542010-08-24 02:24:03 +0000426/// EnumerateMDNodeOperands - Enumerate all non-function-local values
427/// and types referenced by the given MDNode.
428void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) {
429 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
430 if (Value *V = N->getOperand(i)) {
431 if (isa<MDNode>(V) || isa<MDString>(V))
432 EnumerateMetadata(V);
433 else if (!isa<Instruction>(V) && !isa<Argument>(V))
434 EnumerateValue(V);
435 } else
436 EnumerateType(Type::getVoidTy(N->getContext()));
437 }
438}
439
Devang Patelac277eb2010-01-22 22:52:10 +0000440void ValueEnumerator::EnumerateMetadata(const Value *MD) {
Benjamin Kramer14bb1142010-01-23 09:54:23 +0000441 assert((isa<MDNode>(MD) || isa<MDString>(MD)) && "Invalid metadata kind");
Dan Gohmanc828c542010-08-24 02:24:03 +0000442
443 // Enumerate the type of this value.
444 EnumerateType(MD->getType());
445
446 const MDNode *N = dyn_cast<MDNode>(MD);
447
448 // In the module-level pass, skip function-local nodes themselves, but
449 // do walk their operands.
450 if (N && N->isFunctionLocal() && N->getFunction()) {
451 EnumerateMDNodeOperands(N);
452 return;
453 }
454
Devang Patel05eb6172009-08-04 06:00:18 +0000455 // Check to see if it's already in!
456 unsigned &MDValueID = MDValueMap[MD];
457 if (MDValueID) {
458 // Increment use count.
459 MDValues[MDValueID-1].second++;
460 return;
461 }
Devang Patel05eb6172009-08-04 06:00:18 +0000462 MDValues.push_back(std::make_pair(MD, 1U));
463 MDValueID = MDValues.size();
Dan Gohmanc828c542010-08-24 02:24:03 +0000464
465 // Enumerate all non-function-local operands.
466 if (N)
467 EnumerateMDNodeOperands(N);
468}
469
470/// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
471/// information reachable from the given MDNode.
472void ValueEnumerator::EnumerateFunctionLocalMetadata(const MDNode *N) {
473 assert(N->isFunctionLocal() && N->getFunction() &&
474 "EnumerateFunctionLocalMetadata called on non-function-local mdnode!");
475
476 // Enumerate the type of this value.
477 EnumerateType(N->getType());
478
479 // Check to see if it's already in!
480 unsigned &MDValueID = MDValueMap[N];
481 if (MDValueID) {
482 // Increment use count.
483 MDValues[MDValueID-1].second++;
484 return;
485 }
486 MDValues.push_back(std::make_pair(N, 1U));
487 MDValueID = MDValues.size();
488
489 // To incoroporate function-local information visit all function-local
490 // MDNodes and all function-local values they reference.
491 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
492 if (Value *V = N->getOperand(i)) {
Dan Gohman10215a12010-08-24 02:40:27 +0000493 if (MDNode *O = dyn_cast<MDNode>(V)) {
Dan Gohmanc828c542010-08-24 02:24:03 +0000494 if (O->isFunctionLocal() && O->getFunction())
495 EnumerateFunctionLocalMetadata(O);
Dan Gohman10215a12010-08-24 02:40:27 +0000496 } else if (isa<Instruction>(V) || isa<Argument>(V))
Dan Gohmanc828c542010-08-24 02:24:03 +0000497 EnumerateValue(V);
498 }
499
500 // Also, collect all function-local MDNodes for easy access.
501 FunctionLocalMDs.push_back(N);
Devang Patel05eb6172009-08-04 06:00:18 +0000502}
503
Victor Hernandez572218b2010-01-14 19:54:11 +0000504void ValueEnumerator::EnumerateValue(const Value *V) {
Chris Lattner8dace892009-12-31 00:51:46 +0000505 assert(!V->getType()->isVoidTy() && "Can't insert void values!");
Dan Gohmanc828c542010-08-24 02:24:03 +0000506 assert(!isa<MDNode>(V) && !isa<MDString>(V) &&
507 "EnumerateValue doesn't handle Metadata!");
Devang Patel05eb6172009-08-04 06:00:18 +0000508
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000509 // Check to see if it's already in!
510 unsigned &ValueID = ValueMap[V];
511 if (ValueID) {
512 // Increment use count.
513 Values[ValueID-1].second++;
514 return;
515 }
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000516
David Majnemerdad0a642014-06-27 18:19:56 +0000517 if (auto *GO = dyn_cast<GlobalObject>(V))
518 if (const Comdat *C = GO->getComdat())
519 Comdats.insert(C);
520
Chris Lattner9ee48362007-05-06 01:00:28 +0000521 // Enumerate the type of this value.
522 EnumerateType(V->getType());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000523
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000524 if (const Constant *C = dyn_cast<Constant>(V)) {
525 if (isa<GlobalValue>(C)) {
526 // Initializers for globals are handled explicitly elsewhere.
Chris Lattner9ee48362007-05-06 01:00:28 +0000527 } else if (C->getNumOperands()) {
528 // If a constant has operands, enumerate them. This makes sure that if a
529 // constant has uses (for example an array of const ints), that they are
530 // inserted also.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000531
Chris Lattner9ee48362007-05-06 01:00:28 +0000532 // We prefer to enumerate them with values before we enumerate the user
533 // itself. This makes it more likely that we can avoid forward references
534 // in the reader. We know that there can be no cycles in the constants
535 // graph that don't go through a global variable.
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000536 for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
537 I != E; ++I)
Chris Lattneraa99c942009-11-01 01:27:45 +0000538 if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
Victor Hernandez572218b2010-01-14 19:54:11 +0000539 EnumerateValue(*I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000540
Chris Lattner9ee48362007-05-06 01:00:28 +0000541 // Finally, add the value. Doing this could make the ValueID reference be
542 // dangling, don't reuse it.
543 Values.push_back(std::make_pair(V, 1U));
544 ValueMap[V] = Values.size();
545 return;
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000546 }
547 }
Devang Patele059ba6e2009-07-23 01:07:34 +0000548
Chris Lattner9ee48362007-05-06 01:00:28 +0000549 // Add the value.
550 Values.push_back(std::make_pair(V, 1U));
551 ValueID = Values.size();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000552}
553
554
Chris Lattner229907c2011-07-18 04:54:35 +0000555void ValueEnumerator::EnumerateType(Type *Ty) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000556 unsigned *TypeID = &TypeMap[Ty];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000557
Rafael Espindola337a1b22011-04-06 16:49:37 +0000558 // We've already seen this type.
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000559 if (*TypeID)
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000560 return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000561
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000562 // If it is a non-anonymous struct, mark the type as being visited so that we
563 // don't recursively visit it. This is safe because we allow forward
564 // references of these in the bitcode reader.
Chris Lattner229907c2011-07-18 04:54:35 +0000565 if (StructType *STy = dyn_cast<StructType>(Ty))
Chris Lattner335d3992011-08-12 18:06:37 +0000566 if (!STy->isLiteral())
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000567 *TypeID = ~0U;
Joe Abbey2ad8df22012-11-25 15:23:39 +0000568
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000569 // Enumerate all of the subtypes before we enumerate this type. This ensures
570 // that the type will be enumerated in an order that can be directly built.
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000571 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
572 I != E; ++I)
573 EnumerateType(*I);
Joe Abbey2ad8df22012-11-25 15:23:39 +0000574
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000575 // Refresh the TypeID pointer in case the table rehashed.
576 TypeID = &TypeMap[Ty];
Joe Abbey2ad8df22012-11-25 15:23:39 +0000577
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000578 // Check to see if we got the pointer another way. This can happen when
579 // enumerating recursive types that hit the base case deeper than they start.
580 //
581 // If this is actually a struct that we are treating as forward ref'able,
582 // then emit the definition now that all of its contents are available.
583 if (*TypeID && *TypeID != ~0U)
584 return;
Joe Abbey2ad8df22012-11-25 15:23:39 +0000585
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000586 // Add this type now that its contents are all happily enumerated.
587 Types.push_back(Ty);
Joe Abbey2ad8df22012-11-25 15:23:39 +0000588
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000589 *TypeID = Types.size();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000590}
591
Chris Lattner76fd90f2007-05-06 08:35:19 +0000592// Enumerate the types for the specified value. If the value is a constant,
593// walk through it, enumerating the types of the constant.
Victor Hernandez572218b2010-01-14 19:54:11 +0000594void ValueEnumerator::EnumerateOperandType(const Value *V) {
Chris Lattner76fd90f2007-05-06 08:35:19 +0000595 EnumerateType(V->getType());
Joe Abbey2ad8df22012-11-25 15:23:39 +0000596
Chris Lattner76fd90f2007-05-06 08:35:19 +0000597 if (const Constant *C = dyn_cast<Constant>(V)) {
598 // If this constant is already enumerated, ignore it, we know its type must
599 // be enumerated.
600 if (ValueMap.count(V)) return;
601
602 // This constant may have operands, make sure to enumerate the types in
603 // them.
Chris Lattnerf540d742009-10-28 05:24:40 +0000604 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
Jay Foad0159a1e2011-04-11 09:48:55 +0000605 const Value *Op = C->getOperand(i);
Joe Abbey2ad8df22012-11-25 15:23:39 +0000606
Chris Lattnerf540d742009-10-28 05:24:40 +0000607 // Don't enumerate basic blocks here, this happens as operands to
608 // blockaddress.
609 if (isa<BasicBlock>(Op)) continue;
Joe Abbey2ad8df22012-11-25 15:23:39 +0000610
Dan Gohman9cfe5322010-08-25 17:09:03 +0000611 EnumerateOperandType(Op);
Chris Lattnerf540d742009-10-28 05:24:40 +0000612 }
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000613
614 if (const MDNode *N = dyn_cast<MDNode>(V)) {
Chris Lattner9b493022009-12-31 01:22:29 +0000615 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
616 if (Value *Elem = N->getOperand(i))
Victor Hernandez572218b2010-01-14 19:54:11 +0000617 EnumerateOperandType(Elem);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000618 }
Devang Patele059ba6e2009-07-23 01:07:34 +0000619 } else if (isa<MDString>(V) || isa<MDNode>(V))
Dan Gohmanab09a122010-08-24 02:10:52 +0000620 EnumerateMetadata(V);
Chris Lattner76fd90f2007-05-06 08:35:19 +0000621}
622
Bill Wendling7b5f4f32013-02-12 08:01:22 +0000623void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) {
Chris Lattner8a923e72008-03-12 17:45:29 +0000624 if (PAL.isEmpty()) return; // null is always 0.
Bill Wendling7b5f4f32013-02-12 08:01:22 +0000625
Chris Lattnere4bbad62007-05-03 22:46:43 +0000626 // Do a lookup.
Bill Wendling7b5f4f32013-02-12 08:01:22 +0000627 unsigned &Entry = AttributeMap[PAL];
Chris Lattnere4bbad62007-05-03 22:46:43 +0000628 if (Entry == 0) {
629 // Never saw this before, add it.
Bill Wendling3d7b0b82012-12-19 07:18:57 +0000630 Attribute.push_back(PAL);
631 Entry = Attribute.size();
Chris Lattnere4bbad62007-05-03 22:46:43 +0000632 }
Bill Wendling51f612e2013-02-10 23:06:02 +0000633
634 // Do lookups for all attribute groups.
635 for (unsigned i = 0, e = PAL.getNumSlots(); i != e; ++i) {
636 AttributeSet AS = PAL.getSlotAttributes(i);
Bill Wendling92ed7002013-02-11 22:33:26 +0000637 unsigned &Entry = AttributeGroupMap[AS];
Bill Wendling51f612e2013-02-10 23:06:02 +0000638 if (Entry == 0) {
Bill Wendling92ed7002013-02-11 22:33:26 +0000639 AttributeGroups.push_back(AS);
640 Entry = AttributeGroups.size();
Bill Wendling51f612e2013-02-10 23:06:02 +0000641 }
642 }
Chris Lattnere4bbad62007-05-03 22:46:43 +0000643}
644
Chad Rosier6a11b642011-06-03 17:02:19 +0000645void ValueEnumerator::incorporateFunction(const Function &F) {
Nick Lewyckya72e1af2010-02-25 08:30:17 +0000646 InstructionCount = 0;
Chris Lattnere6e364c2007-04-26 05:53:54 +0000647 NumModuleValues = Values.size();
Dan Gohmanc828c542010-08-24 02:24:03 +0000648 NumModuleMDValues = MDValues.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000649
Chris Lattner5f640b92007-04-26 03:50:57 +0000650 // Adding function arguments to the value table.
Dan Gohman9a54c172010-07-16 22:58:39 +0000651 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
652 I != E; ++I)
Chris Lattner5f640b92007-04-26 03:50:57 +0000653 EnumerateValue(I);
654
Chris Lattnere6e364c2007-04-26 05:53:54 +0000655 FirstFuncConstantID = Values.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000656
Chris Lattner5f640b92007-04-26 03:50:57 +0000657 // Add all function-level constants to the value table.
658 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
659 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000660 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
Chris Lattner5f640b92007-04-26 03:50:57 +0000661 OI != E; ++OI) {
662 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
663 isa<InlineAsm>(*OI))
664 EnumerateValue(*OI);
665 }
Chris Lattner7c37b012007-04-26 04:42:16 +0000666 BasicBlocks.push_back(BB);
Chris Lattner6be58c62007-05-03 22:18:21 +0000667 ValueMap[BB] = BasicBlocks.size();
Chris Lattner5f640b92007-04-26 03:50:57 +0000668 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000669
Chris Lattner430e80d2007-05-04 05:21:47 +0000670 // Optimize the constant layout.
671 OptimizeConstants(FirstFuncConstantID, Values.size());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000672
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000673 // Add the function's parameter attributes so they are available for use in
674 // the function's instruction.
Devang Patel4c758ea2008-09-25 21:00:45 +0000675 EnumerateAttributes(F.getAttributes());
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000676
Chris Lattnere6e364c2007-04-26 05:53:54 +0000677 FirstInstID = Values.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000678
Devang Pateldf84e8b2010-06-02 23:05:04 +0000679 SmallVector<MDNode *, 8> FnLocalMDVector;
Chris Lattner5f640b92007-04-26 03:50:57 +0000680 // Add all of the instructions.
681 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000682 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
Victor Hernandezcad73282010-01-13 19:36:16 +0000683 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
684 OI != E; ++OI) {
Victor Hernandez572218b2010-01-14 19:54:11 +0000685 if (MDNode *MD = dyn_cast<MDNode>(*OI))
Victor Hernandez1b081382010-02-06 01:21:09 +0000686 if (MD->isFunctionLocal() && MD->getFunction())
Victor Hernandezd44ee352010-02-04 01:13:08 +0000687 // Enumerate metadata after the instructions they might refer to.
Devang Pateldf84e8b2010-06-02 23:05:04 +0000688 FnLocalMDVector.push_back(MD);
Victor Hernandezcad73282010-01-13 19:36:16 +0000689 }
Dan Gohmanc828c542010-08-24 02:24:03 +0000690
691 SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
692 I->getAllMetadataOtherThanDebugLoc(MDs);
693 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
694 MDNode *N = MDs[i].second;
695 if (N->isFunctionLocal() && N->getFunction())
696 FnLocalMDVector.push_back(N);
697 }
Joe Abbey2ad8df22012-11-25 15:23:39 +0000698
Benjamin Kramerccce8ba2010-01-05 13:12:22 +0000699 if (!I->getType()->isVoidTy())
Chris Lattner5f640b92007-04-26 03:50:57 +0000700 EnumerateValue(I);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000701 }
702 }
Victor Hernandezd44ee352010-02-04 01:13:08 +0000703
704 // Add all of the function-local metadata.
Devang Pateldf84e8b2010-06-02 23:05:04 +0000705 for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
Dan Gohmanc828c542010-08-24 02:24:03 +0000706 EnumerateFunctionLocalMetadata(FnLocalMDVector[i]);
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000707}
708
Chad Rosier6a11b642011-06-03 17:02:19 +0000709void ValueEnumerator::purgeFunction() {
Chris Lattner5f640b92007-04-26 03:50:57 +0000710 /// Remove purged values from the ValueMap.
Chris Lattnere6e364c2007-04-26 05:53:54 +0000711 for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
Chris Lattner5f640b92007-04-26 03:50:57 +0000712 ValueMap.erase(Values[i].first);
Dan Gohmanc828c542010-08-24 02:24:03 +0000713 for (unsigned i = NumModuleMDValues, e = MDValues.size(); i != e; ++i)
714 MDValueMap.erase(MDValues[i].first);
Chris Lattner7c37b012007-04-26 04:42:16 +0000715 for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
716 ValueMap.erase(BasicBlocks[i]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000717
Chris Lattnere6e364c2007-04-26 05:53:54 +0000718 Values.resize(NumModuleValues);
Dan Gohmanc828c542010-08-24 02:24:03 +0000719 MDValues.resize(NumModuleMDValues);
Chris Lattner7c37b012007-04-26 04:42:16 +0000720 BasicBlocks.clear();
Dan Gohman22161da2010-08-25 17:11:16 +0000721 FunctionLocalMDs.clear();
Chris Lattnerc1d10d62007-04-22 06:24:45 +0000722}
Chris Lattnerf540d742009-10-28 05:24:40 +0000723
724static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
725 DenseMap<const BasicBlock*, unsigned> &IDMap) {
726 unsigned Counter = 0;
727 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
728 IDMap[BB] = ++Counter;
729}
730
731/// getGlobalBasicBlockID - This returns the function-specific ID for the
732/// specified basic block. This is relatively expensive information, so it
733/// should only be used by rare constructs such as address-of-label.
734unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
735 unsigned &Idx = GlobalBasicBlockIDs[BB];
736 if (Idx != 0)
Chris Lattneraa99c942009-11-01 01:27:45 +0000737 return Idx-1;
Chris Lattnerf540d742009-10-28 05:24:40 +0000738
739 IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
740 return getGlobalBasicBlockID(BB);
741}
742