ValueEnumerator.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. //===- ValueEnumerator.cpp - Number values and types for bitcode writer ---===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the ValueEnumerator class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "ValueEnumerator.h"
  13. #include "llvm/ADT/DenseMap.h"
  14. #include "llvm/ADT/SmallVector.h"
  15. #include "llvm/Config/llvm-config.h"
  16. #include "llvm/IR/Argument.h"
  17. #include "llvm/IR/Attributes.h"
  18. #include "llvm/IR/BasicBlock.h"
  19. #include "llvm/IR/Constant.h"
  20. #include "llvm/IR/DebugInfoMetadata.h"
  21. #include "llvm/IR/DerivedTypes.h"
  22. #include "llvm/IR/Function.h"
  23. #include "llvm/IR/GlobalAlias.h"
  24. #include "llvm/IR/GlobalIFunc.h"
  25. #include "llvm/IR/GlobalObject.h"
  26. #include "llvm/IR/GlobalValue.h"
  27. #include "llvm/IR/GlobalVariable.h"
  28. #include "llvm/IR/Instruction.h"
  29. #include "llvm/IR/Instructions.h"
  30. #include "llvm/IR/Metadata.h"
  31. #include "llvm/IR/Module.h"
  32. #include "llvm/IR/Type.h"
  33. #include "llvm/IR/Use.h"
  34. #include "llvm/IR/UseListOrder.h"
  35. #include "llvm/IR/User.h"
  36. #include "llvm/IR/Value.h"
  37. #include "llvm/IR/ValueSymbolTable.h"
  38. #include "llvm/Support/Casting.h"
  39. #include "llvm/Support/Compiler.h"
  40. #include "llvm/Support/Debug.h"
  41. #include "llvm/Support/MathExtras.h"
  42. #include "llvm/Support/raw_ostream.h"
  43. #include <algorithm>
  44. #include <cassert>
  45. #include <cstddef>
  46. #include <iterator>
  47. #include <tuple>
  48. #include <utility>
  49. #include <vector>
  50. using namespace llvm;
  51. namespace {
  52. struct OrderMap {
  53. DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
  54. unsigned LastGlobalConstantID = 0;
  55. unsigned LastGlobalValueID = 0;
  56. OrderMap() = default;
  57. bool isGlobalConstant(unsigned ID) const {
  58. return ID <= LastGlobalConstantID;
  59. }
  60. bool isGlobalValue(unsigned ID) const {
  61. return ID <= LastGlobalValueID && !isGlobalConstant(ID);
  62. }
  63. unsigned size() const { return IDs.size(); }
  64. std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
  65. std::pair<unsigned, bool> lookup(const Value *V) const {
  66. return IDs.lookup(V);
  67. }
  68. void index(const Value *V) {
  69. // Explicitly sequence get-size and insert-value operations to avoid UB.
  70. unsigned ID = IDs.size() + 1;
  71. IDs[V].first = ID;
  72. }
  73. };
  74. } // end anonymous namespace
  75. static void orderValue(const Value *V, OrderMap &OM) {
  76. if (OM.lookup(V).first)
  77. return;
  78. if (const Constant *C = dyn_cast<Constant>(V))
  79. if (C->getNumOperands() && !isa<GlobalValue>(C))
  80. for (const Value *Op : C->operands())
  81. if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
  82. orderValue(Op, OM);
  83. // Note: we cannot cache this lookup above, since inserting into the map
  84. // changes the map's size, and thus affects the other IDs.
  85. OM.index(V);
  86. }
  87. static OrderMap orderModule(const Module &M) {
  88. // This needs to match the order used by ValueEnumerator::ValueEnumerator()
  89. // and ValueEnumerator::incorporateFunction().
  90. OrderMap OM;
  91. // In the reader, initializers of GlobalValues are set *after* all the
  92. // globals have been read. Rather than awkwardly modeling this behaviour
  93. // directly in predictValueUseListOrderImpl(), just assign IDs to
  94. // initializers of GlobalValues before GlobalValues themselves to model this
  95. // implicitly.
  96. for (const GlobalVariable &G : M.globals())
  97. if (G.hasInitializer())
  98. if (!isa<GlobalValue>(G.getInitializer()))
  99. orderValue(G.getInitializer(), OM);
  100. for (const GlobalAlias &A : M.aliases())
  101. if (!isa<GlobalValue>(A.getAliasee()))
  102. orderValue(A.getAliasee(), OM);
  103. for (const GlobalIFunc &I : M.ifuncs())
  104. if (!isa<GlobalValue>(I.getResolver()))
  105. orderValue(I.getResolver(), OM);
  106. for (const Function &F : M) {
  107. for (const Use &U : F.operands())
  108. if (!isa<GlobalValue>(U.get()))
  109. orderValue(U.get(), OM);
  110. }
  111. OM.LastGlobalConstantID = OM.size();
  112. // Initializers of GlobalValues are processed in
  113. // BitcodeReader::ResolveGlobalAndAliasInits(). Match the order there rather
  114. // than ValueEnumerator, and match the code in predictValueUseListOrderImpl()
  115. // by giving IDs in reverse order.
  116. //
  117. // Since GlobalValues never reference each other directly (just through
  118. // initializers), their relative IDs only matter for determining order of
  119. // uses in their initializers.
  120. for (const Function &F : M)
  121. orderValue(&F, OM);
  122. for (const GlobalAlias &A : M.aliases())
  123. orderValue(&A, OM);
  124. for (const GlobalIFunc &I : M.ifuncs())
  125. orderValue(&I, OM);
  126. for (const GlobalVariable &G : M.globals())
  127. orderValue(&G, OM);
  128. OM.LastGlobalValueID = OM.size();
  129. for (const Function &F : M) {
  130. if (F.isDeclaration())
  131. continue;
  132. // Here we need to match the union of ValueEnumerator::incorporateFunction()
  133. // and WriteFunction(). Basic blocks are implicitly declared before
  134. // anything else (by declaring their size).
  135. for (const BasicBlock &BB : F)
  136. orderValue(&BB, OM);
  137. for (const Argument &A : F.args())
  138. orderValue(&A, OM);
  139. for (const BasicBlock &BB : F)
  140. for (const Instruction &I : BB)
  141. for (const Value *Op : I.operands())
  142. if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
  143. isa<InlineAsm>(*Op))
  144. orderValue(Op, OM);
  145. for (const BasicBlock &BB : F)
  146. for (const Instruction &I : BB)
  147. orderValue(&I, OM);
  148. }
  149. return OM;
  150. }
  151. static void predictValueUseListOrderImpl(const Value *V, const Function *F,
  152. unsigned ID, const OrderMap &OM,
  153. UseListOrderStack &Stack) {
  154. // Predict use-list order for this one.
  155. using Entry = std::pair<const Use *, unsigned>;
  156. SmallVector<Entry, 64> List;
  157. for (const Use &U : V->uses())
  158. // Check if this user will be serialized.
  159. if (OM.lookup(U.getUser()).first)
  160. List.push_back(std::make_pair(&U, List.size()));
  161. if (List.size() < 2)
  162. // We may have lost some users.
  163. return;
  164. bool IsGlobalValue = OM.isGlobalValue(ID);
  165. llvm::sort(List, [&](const Entry &L, const Entry &R) {
  166. const Use *LU = L.first;
  167. const Use *RU = R.first;
  168. if (LU == RU)
  169. return false;
  170. auto LID = OM.lookup(LU->getUser()).first;
  171. auto RID = OM.lookup(RU->getUser()).first;
  172. // Global values are processed in reverse order.
  173. //
  174. // Moreover, initializers of GlobalValues are set *after* all the globals
  175. // have been read (despite having earlier IDs). Rather than awkwardly
  176. // modeling this behaviour here, orderModule() has assigned IDs to
  177. // initializers of GlobalValues before GlobalValues themselves.
  178. if (OM.isGlobalValue(LID) && OM.isGlobalValue(RID))
  179. return LID < RID;
  180. // If ID is 4, then expect: 7 6 5 1 2 3.
  181. if (LID < RID) {
  182. if (RID <= ID)
  183. if (!IsGlobalValue) // GlobalValue uses don't get reversed.
  184. return true;
  185. return false;
  186. }
  187. if (RID < LID) {
  188. if (LID <= ID)
  189. if (!IsGlobalValue) // GlobalValue uses don't get reversed.
  190. return false;
  191. return true;
  192. }
  193. // LID and RID are equal, so we have different operands of the same user.
  194. // Assume operands are added in order for all instructions.
  195. if (LID <= ID)
  196. if (!IsGlobalValue) // GlobalValue uses don't get reversed.
  197. return LU->getOperandNo() < RU->getOperandNo();
  198. return LU->getOperandNo() > RU->getOperandNo();
  199. });
  200. if (std::is_sorted(
  201. List.begin(), List.end(),
  202. [](const Entry &L, const Entry &R) { return L.second < R.second; }))
  203. // Order is already correct.
  204. return;
  205. // Store the shuffle.
  206. Stack.emplace_back(V, F, List.size());
  207. assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
  208. for (size_t I = 0, E = List.size(); I != E; ++I)
  209. Stack.back().Shuffle[I] = List[I].second;
  210. }
  211. static void predictValueUseListOrder(const Value *V, const Function *F,
  212. OrderMap &OM, UseListOrderStack &Stack) {
  213. auto &IDPair = OM[V];
  214. assert(IDPair.first && "Unmapped value");
  215. if (IDPair.second)
  216. // Already predicted.
  217. return;
  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. // Recursive descent into constants.
  223. if (const Constant *C = dyn_cast<Constant>(V))
  224. if (C->getNumOperands()) // Visit GlobalValues.
  225. for (const Value *Op : C->operands())
  226. if (isa<Constant>(Op)) // Visit GlobalValues.
  227. predictValueUseListOrder(Op, F, OM, Stack);
  228. }
  229. static UseListOrderStack predictUseListOrder(const Module &M) {
  230. OrderMap OM = orderModule(M);
  231. // Use-list orders need to be serialized after all the users have been added
  232. // to a value, or else the shuffles will be incomplete. Store them per
  233. // function in a stack.
  234. //
  235. // Aside from function order, the order of values doesn't matter much here.
  236. UseListOrderStack Stack;
  237. // We want to visit the functions backward now so we can list function-local
  238. // constants in the last Function they're used in. Module-level constants
  239. // have already been visited above.
  240. for (auto I = M.rbegin(), E = M.rend(); I != E; ++I) {
  241. const Function &F = *I;
  242. if (F.isDeclaration())
  243. continue;
  244. for (const BasicBlock &BB : F)
  245. predictValueUseListOrder(&BB, &F, OM, Stack);
  246. for (const Argument &A : F.args())
  247. predictValueUseListOrder(&A, &F, OM, Stack);
  248. for (const BasicBlock &BB : F)
  249. for (const Instruction &I : BB)
  250. for (const Value *Op : I.operands())
  251. if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
  252. predictValueUseListOrder(Op, &F, OM, Stack);
  253. for (const BasicBlock &BB : F)
  254. for (const Instruction &I : BB)
  255. predictValueUseListOrder(&I, &F, OM, Stack);
  256. }
  257. // Visit globals last, since the module-level use-list block will be seen
  258. // before the function bodies are processed.
  259. for (const GlobalVariable &G : M.globals())
  260. predictValueUseListOrder(&G, nullptr, OM, Stack);
  261. for (const Function &F : M)
  262. predictValueUseListOrder(&F, nullptr, OM, Stack);
  263. for (const GlobalAlias &A : M.aliases())
  264. predictValueUseListOrder(&A, nullptr, OM, Stack);
  265. for (const GlobalIFunc &I : M.ifuncs())
  266. predictValueUseListOrder(&I, nullptr, OM, Stack);
  267. for (const GlobalVariable &G : M.globals())
  268. if (G.hasInitializer())
  269. predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
  270. for (const GlobalAlias &A : M.aliases())
  271. predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
  272. for (const GlobalIFunc &I : M.ifuncs())
  273. predictValueUseListOrder(I.getResolver(), nullptr, OM, Stack);
  274. for (const Function &F : M) {
  275. for (const Use &U : F.operands())
  276. predictValueUseListOrder(U.get(), nullptr, OM, Stack);
  277. }
  278. return Stack;
  279. }
  280. static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
  281. return V.first->getType()->isIntOrIntVectorTy();
  282. }
  283. ValueEnumerator::ValueEnumerator(const Module &M,
  284. bool ShouldPreserveUseListOrder)
  285. : ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
  286. if (ShouldPreserveUseListOrder)
  287. UseListOrders = predictUseListOrder(M);
  288. // Enumerate the global variables.
  289. for (const GlobalVariable &GV : M.globals())
  290. EnumerateValue(&GV);
  291. // Enumerate the functions.
  292. for (const Function & F : M) {
  293. EnumerateValue(&F);
  294. EnumerateAttributes(F.getAttributes());
  295. }
  296. // Enumerate the aliases.
  297. for (const GlobalAlias &GA : M.aliases())
  298. EnumerateValue(&GA);
  299. // Enumerate the ifuncs.
  300. for (const GlobalIFunc &GIF : M.ifuncs())
  301. EnumerateValue(&GIF);
  302. // Remember what is the cutoff between globalvalue's and other constants.
  303. unsigned FirstConstant = Values.size();
  304. // Enumerate the global variable initializers and attributes.
  305. for (const GlobalVariable &GV : M.globals()) {
  306. if (GV.hasInitializer())
  307. EnumerateValue(GV.getInitializer());
  308. if (GV.hasAttributes())
  309. EnumerateAttributes(GV.getAttributesAsList(AttributeList::FunctionIndex));
  310. }
  311. // Enumerate the aliasees.
  312. for (const GlobalAlias &GA : M.aliases())
  313. EnumerateValue(GA.getAliasee());
  314. // Enumerate the ifunc resolvers.
  315. for (const GlobalIFunc &GIF : M.ifuncs())
  316. EnumerateValue(GIF.getResolver());
  317. // Enumerate any optional Function data.
  318. for (const Function &F : M)
  319. for (const Use &U : F.operands())
  320. EnumerateValue(U.get());
  321. // Enumerate the metadata type.
  322. //
  323. // TODO: Move this to ValueEnumerator::EnumerateOperandType() once bitcode
  324. // only encodes the metadata type when it's used as a value.
  325. EnumerateType(Type::getMetadataTy(M.getContext()));
  326. // Insert constants and metadata that are named at module level into the slot
  327. // pool so that the module symbol table can refer to them...
  328. EnumerateValueSymbolTable(M.getValueSymbolTable());
  329. EnumerateNamedMetadata(M);
  330. SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
  331. for (const GlobalVariable &GV : M.globals()) {
  332. MDs.clear();
  333. GV.getAllMetadata(MDs);
  334. for (const auto &I : MDs)
  335. // FIXME: Pass GV to EnumerateMetadata and arrange for the bitcode writer
  336. // to write metadata to the global variable's own metadata block
  337. // (PR28134).
  338. EnumerateMetadata(nullptr, I.second);
  339. }
  340. // Enumerate types used by function bodies and argument lists.
  341. for (const Function &F : M) {
  342. for (const Argument &A : F.args())
  343. EnumerateType(A.getType());
  344. // Enumerate metadata attached to this function.
  345. MDs.clear();
  346. F.getAllMetadata(MDs);
  347. for (const auto &I : MDs)
  348. EnumerateMetadata(F.isDeclaration() ? nullptr : &F, I.second);
  349. for (const BasicBlock &BB : F)
  350. for (const Instruction &I : BB) {
  351. for (const Use &Op : I.operands()) {
  352. auto *MD = dyn_cast<MetadataAsValue>(&Op);
  353. if (!MD) {
  354. EnumerateOperandType(Op);
  355. continue;
  356. }
  357. // Local metadata is enumerated during function-incorporation.
  358. if (isa<LocalAsMetadata>(MD->getMetadata()))
  359. continue;
  360. EnumerateMetadata(&F, MD->getMetadata());
  361. }
  362. EnumerateType(I.getType());
  363. if (const auto *Call = dyn_cast<CallBase>(&I))
  364. EnumerateAttributes(Call->getAttributes());
  365. // Enumerate metadata attached with this instruction.
  366. MDs.clear();
  367. I.getAllMetadataOtherThanDebugLoc(MDs);
  368. for (unsigned i = 0, e = MDs.size(); i != e; ++i)
  369. EnumerateMetadata(&F, MDs[i].second);
  370. // Don't enumerate the location directly -- it has a special record
  371. // type -- but enumerate its operands.
  372. if (DILocation *L = I.getDebugLoc())
  373. for (const Metadata *Op : L->operands())
  374. EnumerateMetadata(&F, Op);
  375. }
  376. }
  377. // Optimize constant ordering.
  378. OptimizeConstants(FirstConstant, Values.size());
  379. // Organize metadata ordering.
  380. organizeMetadata();
  381. }
  382. unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
  383. InstructionMapType::const_iterator I = InstructionMap.find(Inst);
  384. assert(I != InstructionMap.end() && "Instruction is not mapped!");
  385. return I->second;
  386. }
  387. unsigned ValueEnumerator::getComdatID(const Comdat *C) const {
  388. unsigned ComdatID = Comdats.idFor(C);
  389. assert(ComdatID && "Comdat not found!");
  390. return ComdatID;
  391. }
  392. void ValueEnumerator::setInstructionID(const Instruction *I) {
  393. InstructionMap[I] = InstructionCount++;
  394. }
  395. unsigned ValueEnumerator::getValueID(const Value *V) const {
  396. if (auto *MD = dyn_cast<MetadataAsValue>(V))
  397. return getMetadataID(MD->getMetadata());
  398. ValueMapType::const_iterator I = ValueMap.find(V);
  399. assert(I != ValueMap.end() && "Value not in slotcalculator!");
  400. return I->second-1;
  401. }
  402. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  403. LLVM_DUMP_METHOD void ValueEnumerator::dump() const {
  404. print(dbgs(), ValueMap, "Default");
  405. dbgs() << '\n';
  406. print(dbgs(), MetadataMap, "MetaData");
  407. dbgs() << '\n';
  408. }
  409. #endif
  410. void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
  411. const char *Name) const {
  412. OS << "Map Name: " << Name << "\n";
  413. OS << "Size: " << Map.size() << "\n";
  414. for (ValueMapType::const_iterator I = Map.begin(),
  415. E = Map.end(); I != E; ++I) {
  416. const Value *V = I->first;
  417. if (V->hasName())
  418. OS << "Value: " << V->getName();
  419. else
  420. OS << "Value: [null]\n";
  421. V->print(errs());
  422. errs() << '\n';
  423. OS << " Uses(" << V->getNumUses() << "):";
  424. for (const Use &U : V->uses()) {
  425. if (&U != &*V->use_begin())
  426. OS << ",";
  427. if(U->hasName())
  428. OS << " " << U->getName();
  429. else
  430. OS << " [null]";
  431. }
  432. OS << "\n\n";
  433. }
  434. }
  435. void ValueEnumerator::print(raw_ostream &OS, const MetadataMapType &Map,
  436. const char *Name) const {
  437. OS << "Map Name: " << Name << "\n";
  438. OS << "Size: " << Map.size() << "\n";
  439. for (auto I = Map.begin(), E = Map.end(); I != E; ++I) {
  440. const Metadata *MD = I->first;
  441. OS << "Metadata: slot = " << I->second.ID << "\n";
  442. OS << "Metadata: function = " << I->second.F << "\n";
  443. MD->print(OS);
  444. OS << "\n";
  445. }
  446. }
  447. /// OptimizeConstants - Reorder constant pool for denser encoding.
  448. void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
  449. if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
  450. if (ShouldPreserveUseListOrder)
  451. // Optimizing constants makes the use-list order difficult to predict.
  452. // Disable it for now when trying to preserve the order.
  453. return;
  454. std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
  455. [this](const std::pair<const Value *, unsigned> &LHS,
  456. const std::pair<const Value *, unsigned> &RHS) {
  457. // Sort by plane.
  458. if (LHS.first->getType() != RHS.first->getType())
  459. return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
  460. // Then by frequency.
  461. return LHS.second > RHS.second;
  462. });
  463. // Ensure that integer and vector of integer constants are at the start of the
  464. // constant pool. This is important so that GEP structure indices come before
  465. // gep constant exprs.
  466. std::stable_partition(Values.begin() + CstStart, Values.begin() + CstEnd,
  467. isIntOrIntVectorValue);
  468. // Rebuild the modified portion of ValueMap.
  469. for (; CstStart != CstEnd; ++CstStart)
  470. ValueMap[Values[CstStart].first] = CstStart+1;
  471. }
  472. /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
  473. /// table into the values table.
  474. void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
  475. for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
  476. VI != VE; ++VI)
  477. EnumerateValue(VI->getValue());
  478. }
  479. /// Insert all of the values referenced by named metadata in the specified
  480. /// module.
  481. void ValueEnumerator::EnumerateNamedMetadata(const Module &M) {
  482. for (const auto &I : M.named_metadata())
  483. EnumerateNamedMDNode(&I);
  484. }
  485. void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
  486. for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
  487. EnumerateMetadata(nullptr, MD->getOperand(i));
  488. }
  489. unsigned ValueEnumerator::getMetadataFunctionID(const Function *F) const {
  490. return F ? getValueID(F) + 1 : 0;
  491. }
  492. void ValueEnumerator::EnumerateMetadata(const Function *F, const Metadata *MD) {
  493. EnumerateMetadata(getMetadataFunctionID(F), MD);
  494. }
  495. void ValueEnumerator::EnumerateFunctionLocalMetadata(
  496. const Function &F, const LocalAsMetadata *Local) {
  497. EnumerateFunctionLocalMetadata(getMetadataFunctionID(&F), Local);
  498. }
  499. void ValueEnumerator::dropFunctionFromMetadata(
  500. MetadataMapType::value_type &FirstMD) {
  501. SmallVector<const MDNode *, 64> Worklist;
  502. auto push = [&Worklist](MetadataMapType::value_type &MD) {
  503. auto &Entry = MD.second;
  504. // Nothing to do if this metadata isn't tagged.
  505. if (!Entry.F)
  506. return;
  507. // Drop the function tag.
  508. Entry.F = 0;
  509. // If this is has an ID and is an MDNode, then its operands have entries as
  510. // well. We need to drop the function from them too.
  511. if (Entry.ID)
  512. if (auto *N = dyn_cast<MDNode>(MD.first))
  513. Worklist.push_back(N);
  514. };
  515. push(FirstMD);
  516. while (!Worklist.empty())
  517. for (const Metadata *Op : Worklist.pop_back_val()->operands()) {
  518. if (!Op)
  519. continue;
  520. auto MD = MetadataMap.find(Op);
  521. if (MD != MetadataMap.end())
  522. push(*MD);
  523. }
  524. }
  525. void ValueEnumerator::EnumerateMetadata(unsigned F, const Metadata *MD) {
  526. // It's vital for reader efficiency that uniqued subgraphs are done in
  527. // post-order; it's expensive when their operands have forward references.
  528. // If a distinct node is referenced from a uniqued node, it'll be delayed
  529. // until the uniqued subgraph has been completely traversed.
  530. SmallVector<const MDNode *, 32> DelayedDistinctNodes;
  531. // Start by enumerating MD, and then work through its transitive operands in
  532. // post-order. This requires a depth-first search.
  533. SmallVector<std::pair<const MDNode *, MDNode::op_iterator>, 32> Worklist;
  534. if (const MDNode *N = enumerateMetadataImpl(F, MD))
  535. Worklist.push_back(std::make_pair(N, N->op_begin()));
  536. while (!Worklist.empty()) {
  537. const MDNode *N = Worklist.back().first;
  538. // Enumerate operands until we hit a new node. We need to traverse these
  539. // nodes' operands before visiting the rest of N's operands.
  540. MDNode::op_iterator I = std::find_if(
  541. Worklist.back().second, N->op_end(),
  542. [&](const Metadata *MD) { return enumerateMetadataImpl(F, MD); });
  543. if (I != N->op_end()) {
  544. auto *Op = cast<MDNode>(*I);
  545. Worklist.back().second = ++I;
  546. // Delay traversing Op if it's a distinct node and N is uniqued.
  547. if (Op->isDistinct() && !N->isDistinct())
  548. DelayedDistinctNodes.push_back(Op);
  549. else
  550. Worklist.push_back(std::make_pair(Op, Op->op_begin()));
  551. continue;
  552. }
  553. // All the operands have been visited. Now assign an ID.
  554. Worklist.pop_back();
  555. MDs.push_back(N);
  556. MetadataMap[N].ID = MDs.size();
  557. // Flush out any delayed distinct nodes; these are all the distinct nodes
  558. // that are leaves in last uniqued subgraph.
  559. if (Worklist.empty() || Worklist.back().first->isDistinct()) {
  560. for (const MDNode *N : DelayedDistinctNodes)
  561. Worklist.push_back(std::make_pair(N, N->op_begin()));
  562. DelayedDistinctNodes.clear();
  563. }
  564. }
  565. }
  566. const MDNode *ValueEnumerator::enumerateMetadataImpl(unsigned F, const Metadata *MD) {
  567. if (!MD)
  568. return nullptr;
  569. assert(
  570. (isa<MDNode>(MD) || isa<MDString>(MD) || isa<ConstantAsMetadata>(MD)) &&
  571. "Invalid metadata kind");
  572. auto Insertion = MetadataMap.insert(std::make_pair(MD, MDIndex(F)));
  573. MDIndex &Entry = Insertion.first->second;
  574. if (!Insertion.second) {
  575. // Already mapped. If F doesn't match the function tag, drop it.
  576. if (Entry.hasDifferentFunction(F))
  577. dropFunctionFromMetadata(*Insertion.first);
  578. return nullptr;
  579. }
  580. // Don't assign IDs to metadata nodes.
  581. if (auto *N = dyn_cast<MDNode>(MD))
  582. return N;
  583. // Save the metadata.
  584. MDs.push_back(MD);
  585. Entry.ID = MDs.size();
  586. // Enumerate the constant, if any.
  587. if (auto *C = dyn_cast<ConstantAsMetadata>(MD))
  588. EnumerateValue(C->getValue());
  589. return nullptr;
  590. }
  591. /// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
  592. /// information reachable from the metadata.
  593. void ValueEnumerator::EnumerateFunctionLocalMetadata(
  594. unsigned F, const LocalAsMetadata *Local) {
  595. assert(F && "Expected a function");
  596. // Check to see if it's already in!
  597. MDIndex &Index = MetadataMap[Local];
  598. if (Index.ID) {
  599. assert(Index.F == F && "Expected the same function");
  600. return;
  601. }
  602. MDs.push_back(Local);
  603. Index.F = F;
  604. Index.ID = MDs.size();
  605. EnumerateValue(Local->getValue());
  606. }
  607. static unsigned getMetadataTypeOrder(const Metadata *MD) {
  608. // Strings are emitted in bulk and must come first.
  609. if (isa<MDString>(MD))
  610. return 0;
  611. // ConstantAsMetadata doesn't reference anything. We may as well shuffle it
  612. // to the front since we can detect it.
  613. auto *N = dyn_cast<MDNode>(MD);
  614. if (!N)
  615. return 1;
  616. // The reader is fast forward references for distinct node operands, but slow
  617. // when uniqued operands are unresolved.
  618. return N->isDistinct() ? 2 : 3;
  619. }
  620. void ValueEnumerator::organizeMetadata() {
  621. assert(MetadataMap.size() == MDs.size() &&
  622. "Metadata map and vector out of sync");
  623. if (MDs.empty())
  624. return;
  625. // Copy out the index information from MetadataMap in order to choose a new
  626. // order.
  627. SmallVector<MDIndex, 64> Order;
  628. Order.reserve(MetadataMap.size());
  629. for (const Metadata *MD : MDs)
  630. Order.push_back(MetadataMap.lookup(MD));
  631. // Partition:
  632. // - by function, then
  633. // - by isa<MDString>
  634. // and then sort by the original/current ID. Since the IDs are guaranteed to
  635. // be unique, the result of std::sort will be deterministic. There's no need
  636. // for std::stable_sort.
  637. llvm::sort(Order, [this](MDIndex LHS, MDIndex RHS) {
  638. return std::make_tuple(LHS.F, getMetadataTypeOrder(LHS.get(MDs)), LHS.ID) <
  639. std::make_tuple(RHS.F, getMetadataTypeOrder(RHS.get(MDs)), RHS.ID);
  640. });
  641. // Rebuild MDs, index the metadata ranges for each function in FunctionMDs,
  642. // and fix up MetadataMap.
  643. std::vector<const Metadata *> OldMDs;
  644. MDs.swap(OldMDs);
  645. MDs.reserve(OldMDs.size());
  646. for (unsigned I = 0, E = Order.size(); I != E && !Order[I].F; ++I) {
  647. auto *MD = Order[I].get(OldMDs);
  648. MDs.push_back(MD);
  649. MetadataMap[MD].ID = I + 1;
  650. if (isa<MDString>(MD))
  651. ++NumMDStrings;
  652. }
  653. // Return early if there's nothing for the functions.
  654. if (MDs.size() == Order.size())
  655. return;
  656. // Build the function metadata ranges.
  657. MDRange R;
  658. FunctionMDs.reserve(OldMDs.size());
  659. unsigned PrevF = 0;
  660. for (unsigned I = MDs.size(), E = Order.size(), ID = MDs.size(); I != E;
  661. ++I) {
  662. unsigned F = Order[I].F;
  663. if (!PrevF) {
  664. PrevF = F;
  665. } else if (PrevF != F) {
  666. R.Last = FunctionMDs.size();
  667. std::swap(R, FunctionMDInfo[PrevF]);
  668. R.First = FunctionMDs.size();
  669. ID = MDs.size();
  670. PrevF = F;
  671. }
  672. auto *MD = Order[I].get(OldMDs);
  673. FunctionMDs.push_back(MD);
  674. MetadataMap[MD].ID = ++ID;
  675. if (isa<MDString>(MD))
  676. ++R.NumStrings;
  677. }
  678. R.Last = FunctionMDs.size();
  679. FunctionMDInfo[PrevF] = R;
  680. }
  681. void ValueEnumerator::incorporateFunctionMetadata(const Function &F) {
  682. NumModuleMDs = MDs.size();
  683. auto R = FunctionMDInfo.lookup(getValueID(&F) + 1);
  684. NumMDStrings = R.NumStrings;
  685. MDs.insert(MDs.end(), FunctionMDs.begin() + R.First,
  686. FunctionMDs.begin() + R.Last);
  687. }
  688. void ValueEnumerator::EnumerateValue(const Value *V) {
  689. assert(!V->getType()->isVoidTy() && "Can't insert void values!");
  690. assert(!isa<MetadataAsValue>(V) && "EnumerateValue doesn't handle Metadata!");
  691. // Check to see if it's already in!
  692. unsigned &ValueID = ValueMap[V];
  693. if (ValueID) {
  694. // Increment use count.
  695. Values[ValueID-1].second++;
  696. return;
  697. }
  698. if (auto *GO = dyn_cast<GlobalObject>(V))
  699. if (const Comdat *C = GO->getComdat())
  700. Comdats.insert(C);
  701. // Enumerate the type of this value.
  702. EnumerateType(V->getType());
  703. if (const Constant *C = dyn_cast<Constant>(V)) {
  704. if (isa<GlobalValue>(C)) {
  705. // Initializers for globals are handled explicitly elsewhere.
  706. } else if (C->getNumOperands()) {
  707. // If a constant has operands, enumerate them. This makes sure that if a
  708. // constant has uses (for example an array of const ints), that they are
  709. // inserted also.
  710. // We prefer to enumerate them with values before we enumerate the user
  711. // itself. This makes it more likely that we can avoid forward references
  712. // in the reader. We know that there can be no cycles in the constants
  713. // graph that don't go through a global variable.
  714. for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
  715. I != E; ++I)
  716. if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
  717. EnumerateValue(*I);
  718. // Finally, add the value. Doing this could make the ValueID reference be
  719. // dangling, don't reuse it.
  720. Values.push_back(std::make_pair(V, 1U));
  721. ValueMap[V] = Values.size();
  722. return;
  723. }
  724. }
  725. // Add the value.
  726. Values.push_back(std::make_pair(V, 1U));
  727. ValueID = Values.size();
  728. }
  729. void ValueEnumerator::EnumerateType(Type *Ty) {
  730. unsigned *TypeID = &TypeMap[Ty];
  731. // We've already seen this type.
  732. if (*TypeID)
  733. return;
  734. // If it is a non-anonymous struct, mark the type as being visited so that we
  735. // don't recursively visit it. This is safe because we allow forward
  736. // references of these in the bitcode reader.
  737. if (StructType *STy = dyn_cast<StructType>(Ty))
  738. if (!STy->isLiteral())
  739. *TypeID = ~0U;
  740. // Enumerate all of the subtypes before we enumerate this type. This ensures
  741. // that the type will be enumerated in an order that can be directly built.
  742. for (Type *SubTy : Ty->subtypes())
  743. EnumerateType(SubTy);
  744. // Refresh the TypeID pointer in case the table rehashed.
  745. TypeID = &TypeMap[Ty];
  746. // Check to see if we got the pointer another way. This can happen when
  747. // enumerating recursive types that hit the base case deeper than they start.
  748. //
  749. // If this is actually a struct that we are treating as forward ref'able,
  750. // then emit the definition now that all of its contents are available.
  751. if (*TypeID && *TypeID != ~0U)
  752. return;
  753. // Add this type now that its contents are all happily enumerated.
  754. Types.push_back(Ty);
  755. *TypeID = Types.size();
  756. }
  757. // Enumerate the types for the specified value. If the value is a constant,
  758. // walk through it, enumerating the types of the constant.
  759. void ValueEnumerator::EnumerateOperandType(const Value *V) {
  760. EnumerateType(V->getType());
  761. assert(!isa<MetadataAsValue>(V) && "Unexpected metadata operand");
  762. const Constant *C = dyn_cast<Constant>(V);
  763. if (!C)
  764. return;
  765. // If this constant is already enumerated, ignore it, we know its type must
  766. // be enumerated.
  767. if (ValueMap.count(C))
  768. return;
  769. // This constant may have operands, make sure to enumerate the types in
  770. // them.
  771. for (const Value *Op : C->operands()) {
  772. // Don't enumerate basic blocks here, this happens as operands to
  773. // blockaddress.
  774. if (isa<BasicBlock>(Op))
  775. continue;
  776. EnumerateOperandType(Op);
  777. }
  778. }
  779. void ValueEnumerator::EnumerateAttributes(AttributeList PAL) {
  780. if (PAL.isEmpty()) return; // null is always 0.
  781. // Do a lookup.
  782. unsigned &Entry = AttributeListMap[PAL];
  783. if (Entry == 0) {
  784. // Never saw this before, add it.
  785. AttributeLists.push_back(PAL);
  786. Entry = AttributeLists.size();
  787. }
  788. // Do lookups for all attribute groups.
  789. for (unsigned i = PAL.index_begin(), e = PAL.index_end(); i != e; ++i) {
  790. AttributeSet AS = PAL.getAttributes(i);
  791. if (!AS.hasAttributes())
  792. continue;
  793. IndexAndAttrSet Pair = {i, AS};
  794. unsigned &Entry = AttributeGroupMap[Pair];
  795. if (Entry == 0) {
  796. AttributeGroups.push_back(Pair);
  797. Entry = AttributeGroups.size();
  798. }
  799. }
  800. }
  801. void ValueEnumerator::incorporateFunction(const Function &F) {
  802. InstructionCount = 0;
  803. NumModuleValues = Values.size();
  804. // Add global metadata to the function block. This doesn't include
  805. // LocalAsMetadata.
  806. incorporateFunctionMetadata(F);
  807. // Adding function arguments to the value table.
  808. for (const auto &I : F.args()) {
  809. EnumerateValue(&I);
  810. if (I.hasAttribute(Attribute::ByVal) && I.getParamByValType())
  811. EnumerateType(I.getParamByValType());
  812. }
  813. FirstFuncConstantID = Values.size();
  814. // Add all function-level constants to the value table.
  815. for (const BasicBlock &BB : F) {
  816. for (const Instruction &I : BB)
  817. for (const Use &OI : I.operands()) {
  818. if ((isa<Constant>(OI) && !isa<GlobalValue>(OI)) || isa<InlineAsm>(OI))
  819. EnumerateValue(OI);
  820. }
  821. BasicBlocks.push_back(&BB);
  822. ValueMap[&BB] = BasicBlocks.size();
  823. }
  824. // Optimize the constant layout.
  825. OptimizeConstants(FirstFuncConstantID, Values.size());
  826. // Add the function's parameter attributes so they are available for use in
  827. // the function's instruction.
  828. EnumerateAttributes(F.getAttributes());
  829. FirstInstID = Values.size();
  830. SmallVector<LocalAsMetadata *, 8> FnLocalMDVector;
  831. // Add all of the instructions.
  832. for (const BasicBlock &BB : F) {
  833. for (const Instruction &I : BB) {
  834. for (const Use &OI : I.operands()) {
  835. if (auto *MD = dyn_cast<MetadataAsValue>(&OI))
  836. if (auto *Local = dyn_cast<LocalAsMetadata>(MD->getMetadata()))
  837. // Enumerate metadata after the instructions they might refer to.
  838. FnLocalMDVector.push_back(Local);
  839. }
  840. if (!I.getType()->isVoidTy())
  841. EnumerateValue(&I);
  842. }
  843. }
  844. // Add all of the function-local metadata.
  845. for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i) {
  846. // At this point, every local values have been incorporated, we shouldn't
  847. // have a metadata operand that references a value that hasn't been seen.
  848. assert(ValueMap.count(FnLocalMDVector[i]->getValue()) &&
  849. "Missing value for metadata operand");
  850. EnumerateFunctionLocalMetadata(F, FnLocalMDVector[i]);
  851. }
  852. }
  853. void ValueEnumerator::purgeFunction() {
  854. /// Remove purged values from the ValueMap.
  855. for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
  856. ValueMap.erase(Values[i].first);
  857. for (unsigned i = NumModuleMDs, e = MDs.size(); i != e; ++i)
  858. MetadataMap.erase(MDs[i]);
  859. for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
  860. ValueMap.erase(BasicBlocks[i]);
  861. Values.resize(NumModuleValues);
  862. MDs.resize(NumModuleMDs);
  863. BasicBlocks.clear();
  864. NumMDStrings = 0;
  865. }
  866. static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
  867. DenseMap<const BasicBlock*, unsigned> &IDMap) {
  868. unsigned Counter = 0;
  869. for (const BasicBlock &BB : *F)
  870. IDMap[&BB] = ++Counter;
  871. }
  872. /// getGlobalBasicBlockID - This returns the function-specific ID for the
  873. /// specified basic block. This is relatively expensive information, so it
  874. /// should only be used by rare constructs such as address-of-label.
  875. unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
  876. unsigned &Idx = GlobalBasicBlockIDs[BB];
  877. if (Idx != 0)
  878. return Idx-1;
  879. IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
  880. return getGlobalBasicBlockID(BB);
  881. }
  882. uint64_t ValueEnumerator::computeBitsRequiredForTypeIndicies() const {
  883. return Log2_32_Ceil(getTypes().size() + 1);
  884. }