PredicateInfo.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. //===-- PredicateInfo.cpp - PredicateInfo Builder--------------------===//
  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 PredicateInfo class.
  10. //
  11. //===----------------------------------------------------------------===//
  12. #include "llvm/Transforms/Utils/PredicateInfo.h"
  13. #include "llvm/ADT/DenseMap.h"
  14. #include "llvm/ADT/DepthFirstIterator.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SmallPtrSet.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/Analysis/AssumptionCache.h"
  20. #include "llvm/Analysis/CFG.h"
  21. #include "llvm/IR/AssemblyAnnotationWriter.h"
  22. #include "llvm/IR/DataLayout.h"
  23. #include "llvm/IR/Dominators.h"
  24. #include "llvm/IR/GlobalVariable.h"
  25. #include "llvm/IR/IRBuilder.h"
  26. #include "llvm/IR/InstIterator.h"
  27. #include "llvm/IR/IntrinsicInst.h"
  28. #include "llvm/IR/LLVMContext.h"
  29. #include "llvm/IR/Metadata.h"
  30. #include "llvm/IR/Module.h"
  31. #include "llvm/IR/PatternMatch.h"
  32. #include "llvm/InitializePasses.h"
  33. #include "llvm/Support/CommandLine.h"
  34. #include "llvm/Support/Debug.h"
  35. #include "llvm/Support/DebugCounter.h"
  36. #include "llvm/Support/FormattedStream.h"
  37. #include "llvm/Transforms/Utils.h"
  38. #include <algorithm>
  39. #define DEBUG_TYPE "predicateinfo"
  40. using namespace llvm;
  41. using namespace PatternMatch;
  42. INITIALIZE_PASS_BEGIN(PredicateInfoPrinterLegacyPass, "print-predicateinfo",
  43. "PredicateInfo Printer", false, false)
  44. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  45. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  46. INITIALIZE_PASS_END(PredicateInfoPrinterLegacyPass, "print-predicateinfo",
  47. "PredicateInfo Printer", false, false)
  48. static cl::opt<bool> VerifyPredicateInfo(
  49. "verify-predicateinfo", cl::init(false), cl::Hidden,
  50. cl::desc("Verify PredicateInfo in legacy printer pass."));
  51. DEBUG_COUNTER(RenameCounter, "predicateinfo-rename",
  52. "Controls which variables are renamed with predicateinfo");
  53. // Maximum number of conditions considered for renaming for each branch/assume.
  54. // This limits renaming of deep and/or chains.
  55. static const unsigned MaxCondsPerBranch = 8;
  56. namespace {
  57. // Given a predicate info that is a type of branching terminator, get the
  58. // branching block.
  59. const BasicBlock *getBranchBlock(const PredicateBase *PB) {
  60. assert(isa<PredicateWithEdge>(PB) &&
  61. "Only branches and switches should have PHIOnly defs that "
  62. "require branch blocks.");
  63. return cast<PredicateWithEdge>(PB)->From;
  64. }
  65. // Given a predicate info that is a type of branching terminator, get the
  66. // branching terminator.
  67. static Instruction *getBranchTerminator(const PredicateBase *PB) {
  68. assert(isa<PredicateWithEdge>(PB) &&
  69. "Not a predicate info type we know how to get a terminator from.");
  70. return cast<PredicateWithEdge>(PB)->From->getTerminator();
  71. }
  72. // Given a predicate info that is a type of branching terminator, get the
  73. // edge this predicate info represents
  74. const std::pair<BasicBlock *, BasicBlock *>
  75. getBlockEdge(const PredicateBase *PB) {
  76. assert(isa<PredicateWithEdge>(PB) &&
  77. "Not a predicate info type we know how to get an edge from.");
  78. const auto *PEdge = cast<PredicateWithEdge>(PB);
  79. return std::make_pair(PEdge->From, PEdge->To);
  80. }
  81. }
  82. namespace llvm {
  83. enum LocalNum {
  84. // Operations that must appear first in the block.
  85. LN_First,
  86. // Operations that are somewhere in the middle of the block, and are sorted on
  87. // demand.
  88. LN_Middle,
  89. // Operations that must appear last in a block, like successor phi node uses.
  90. LN_Last
  91. };
  92. // Associate global and local DFS info with defs and uses, so we can sort them
  93. // into a global domination ordering.
  94. struct ValueDFS {
  95. int DFSIn = 0;
  96. int DFSOut = 0;
  97. unsigned int LocalNum = LN_Middle;
  98. // Only one of Def or Use will be set.
  99. Value *Def = nullptr;
  100. Use *U = nullptr;
  101. // Neither PInfo nor EdgeOnly participate in the ordering
  102. PredicateBase *PInfo = nullptr;
  103. bool EdgeOnly = false;
  104. };
  105. // Perform a strict weak ordering on instructions and arguments.
  106. static bool valueComesBefore(const Value *A, const Value *B) {
  107. auto *ArgA = dyn_cast_or_null<Argument>(A);
  108. auto *ArgB = dyn_cast_or_null<Argument>(B);
  109. if (ArgA && !ArgB)
  110. return true;
  111. if (ArgB && !ArgA)
  112. return false;
  113. if (ArgA && ArgB)
  114. return ArgA->getArgNo() < ArgB->getArgNo();
  115. return cast<Instruction>(A)->comesBefore(cast<Instruction>(B));
  116. }
  117. // This compares ValueDFS structures. Doing so allows us to walk the minimum
  118. // number of instructions necessary to compute our def/use ordering.
  119. struct ValueDFS_Compare {
  120. DominatorTree &DT;
  121. ValueDFS_Compare(DominatorTree &DT) : DT(DT) {}
  122. bool operator()(const ValueDFS &A, const ValueDFS &B) const {
  123. if (&A == &B)
  124. return false;
  125. // The only case we can't directly compare them is when they in the same
  126. // block, and both have localnum == middle. In that case, we have to use
  127. // comesbefore to see what the real ordering is, because they are in the
  128. // same basic block.
  129. assert((A.DFSIn != B.DFSIn || A.DFSOut == B.DFSOut) &&
  130. "Equal DFS-in numbers imply equal out numbers");
  131. bool SameBlock = A.DFSIn == B.DFSIn;
  132. // We want to put the def that will get used for a given set of phi uses,
  133. // before those phi uses.
  134. // So we sort by edge, then by def.
  135. // Note that only phi nodes uses and defs can come last.
  136. if (SameBlock && A.LocalNum == LN_Last && B.LocalNum == LN_Last)
  137. return comparePHIRelated(A, B);
  138. bool isADef = A.Def;
  139. bool isBDef = B.Def;
  140. if (!SameBlock || A.LocalNum != LN_Middle || B.LocalNum != LN_Middle)
  141. return std::tie(A.DFSIn, A.LocalNum, isADef) <
  142. std::tie(B.DFSIn, B.LocalNum, isBDef);
  143. return localComesBefore(A, B);
  144. }
  145. // For a phi use, or a non-materialized def, return the edge it represents.
  146. const std::pair<BasicBlock *, BasicBlock *>
  147. getBlockEdge(const ValueDFS &VD) const {
  148. if (!VD.Def && VD.U) {
  149. auto *PHI = cast<PHINode>(VD.U->getUser());
  150. return std::make_pair(PHI->getIncomingBlock(*VD.U), PHI->getParent());
  151. }
  152. // This is really a non-materialized def.
  153. return ::getBlockEdge(VD.PInfo);
  154. }
  155. // For two phi related values, return the ordering.
  156. bool comparePHIRelated(const ValueDFS &A, const ValueDFS &B) const {
  157. BasicBlock *ASrc, *ADest, *BSrc, *BDest;
  158. std::tie(ASrc, ADest) = getBlockEdge(A);
  159. std::tie(BSrc, BDest) = getBlockEdge(B);
  160. #ifndef NDEBUG
  161. // This function should only be used for values in the same BB, check that.
  162. DomTreeNode *DomASrc = DT.getNode(ASrc);
  163. DomTreeNode *DomBSrc = DT.getNode(BSrc);
  164. assert(DomASrc->getDFSNumIn() == (unsigned)A.DFSIn &&
  165. "DFS numbers for A should match the ones of the source block");
  166. assert(DomBSrc->getDFSNumIn() == (unsigned)B.DFSIn &&
  167. "DFS numbers for B should match the ones of the source block");
  168. assert(A.DFSIn == B.DFSIn && "Values must be in the same block");
  169. #endif
  170. (void)ASrc;
  171. (void)BSrc;
  172. // Use DFS numbers to compare destination blocks, to guarantee a
  173. // deterministic order.
  174. DomTreeNode *DomADest = DT.getNode(ADest);
  175. DomTreeNode *DomBDest = DT.getNode(BDest);
  176. unsigned AIn = DomADest->getDFSNumIn();
  177. unsigned BIn = DomBDest->getDFSNumIn();
  178. bool isADef = A.Def;
  179. bool isBDef = B.Def;
  180. assert((!A.Def || !A.U) && (!B.Def || !B.U) &&
  181. "Def and U cannot be set at the same time");
  182. // Now sort by edge destination and then defs before uses.
  183. return std::tie(AIn, isADef) < std::tie(BIn, isBDef);
  184. }
  185. // Get the definition of an instruction that occurs in the middle of a block.
  186. Value *getMiddleDef(const ValueDFS &VD) const {
  187. if (VD.Def)
  188. return VD.Def;
  189. // It's possible for the defs and uses to be null. For branches, the local
  190. // numbering will say the placed predicaeinfos should go first (IE
  191. // LN_beginning), so we won't be in this function. For assumes, we will end
  192. // up here, beause we need to order the def we will place relative to the
  193. // assume. So for the purpose of ordering, we pretend the def is right
  194. // after the assume, because that is where we will insert the info.
  195. if (!VD.U) {
  196. assert(VD.PInfo &&
  197. "No def, no use, and no predicateinfo should not occur");
  198. assert(isa<PredicateAssume>(VD.PInfo) &&
  199. "Middle of block should only occur for assumes");
  200. return cast<PredicateAssume>(VD.PInfo)->AssumeInst->getNextNode();
  201. }
  202. return nullptr;
  203. }
  204. // Return either the Def, if it's not null, or the user of the Use, if the def
  205. // is null.
  206. const Instruction *getDefOrUser(const Value *Def, const Use *U) const {
  207. if (Def)
  208. return cast<Instruction>(Def);
  209. return cast<Instruction>(U->getUser());
  210. }
  211. // This performs the necessary local basic block ordering checks to tell
  212. // whether A comes before B, where both are in the same basic block.
  213. bool localComesBefore(const ValueDFS &A, const ValueDFS &B) const {
  214. auto *ADef = getMiddleDef(A);
  215. auto *BDef = getMiddleDef(B);
  216. // See if we have real values or uses. If we have real values, we are
  217. // guaranteed they are instructions or arguments. No matter what, we are
  218. // guaranteed they are in the same block if they are instructions.
  219. auto *ArgA = dyn_cast_or_null<Argument>(ADef);
  220. auto *ArgB = dyn_cast_or_null<Argument>(BDef);
  221. if (ArgA || ArgB)
  222. return valueComesBefore(ArgA, ArgB);
  223. auto *AInst = getDefOrUser(ADef, A.U);
  224. auto *BInst = getDefOrUser(BDef, B.U);
  225. return valueComesBefore(AInst, BInst);
  226. }
  227. };
  228. class PredicateInfoBuilder {
  229. // Used to store information about each value we might rename.
  230. struct ValueInfo {
  231. SmallVector<PredicateBase *, 4> Infos;
  232. };
  233. PredicateInfo &PI;
  234. Function &F;
  235. DominatorTree &DT;
  236. AssumptionCache &AC;
  237. // This stores info about each operand or comparison result we make copies
  238. // of. The real ValueInfos start at index 1, index 0 is unused so that we
  239. // can more easily detect invalid indexing.
  240. SmallVector<ValueInfo, 32> ValueInfos;
  241. // This gives the index into the ValueInfos array for a given Value. Because
  242. // 0 is not a valid Value Info index, you can use DenseMap::lookup and tell
  243. // whether it returned a valid result.
  244. DenseMap<Value *, unsigned int> ValueInfoNums;
  245. // The set of edges along which we can only handle phi uses, due to critical
  246. // edges.
  247. DenseSet<std::pair<BasicBlock *, BasicBlock *>> EdgeUsesOnly;
  248. ValueInfo &getOrCreateValueInfo(Value *);
  249. const ValueInfo &getValueInfo(Value *) const;
  250. void processAssume(IntrinsicInst *, BasicBlock *,
  251. SmallVectorImpl<Value *> &OpsToRename);
  252. void processBranch(BranchInst *, BasicBlock *,
  253. SmallVectorImpl<Value *> &OpsToRename);
  254. void processSwitch(SwitchInst *, BasicBlock *,
  255. SmallVectorImpl<Value *> &OpsToRename);
  256. void renameUses(SmallVectorImpl<Value *> &OpsToRename);
  257. void addInfoFor(SmallVectorImpl<Value *> &OpsToRename, Value *Op,
  258. PredicateBase *PB);
  259. typedef SmallVectorImpl<ValueDFS> ValueDFSStack;
  260. void convertUsesToDFSOrdered(Value *, SmallVectorImpl<ValueDFS> &);
  261. Value *materializeStack(unsigned int &, ValueDFSStack &, Value *);
  262. bool stackIsInScope(const ValueDFSStack &, const ValueDFS &) const;
  263. void popStackUntilDFSScope(ValueDFSStack &, const ValueDFS &);
  264. public:
  265. PredicateInfoBuilder(PredicateInfo &PI, Function &F, DominatorTree &DT,
  266. AssumptionCache &AC)
  267. : PI(PI), F(F), DT(DT), AC(AC) {
  268. // Push an empty operand info so that we can detect 0 as not finding one
  269. ValueInfos.resize(1);
  270. }
  271. void buildPredicateInfo();
  272. };
  273. bool PredicateInfoBuilder::stackIsInScope(const ValueDFSStack &Stack,
  274. const ValueDFS &VDUse) const {
  275. if (Stack.empty())
  276. return false;
  277. // If it's a phi only use, make sure it's for this phi node edge, and that the
  278. // use is in a phi node. If it's anything else, and the top of the stack is
  279. // EdgeOnly, we need to pop the stack. We deliberately sort phi uses next to
  280. // the defs they must go with so that we can know it's time to pop the stack
  281. // when we hit the end of the phi uses for a given def.
  282. if (Stack.back().EdgeOnly) {
  283. if (!VDUse.U)
  284. return false;
  285. auto *PHI = dyn_cast<PHINode>(VDUse.U->getUser());
  286. if (!PHI)
  287. return false;
  288. // Check edge
  289. BasicBlock *EdgePred = PHI->getIncomingBlock(*VDUse.U);
  290. if (EdgePred != getBranchBlock(Stack.back().PInfo))
  291. return false;
  292. // Use dominates, which knows how to handle edge dominance.
  293. return DT.dominates(getBlockEdge(Stack.back().PInfo), *VDUse.U);
  294. }
  295. return (VDUse.DFSIn >= Stack.back().DFSIn &&
  296. VDUse.DFSOut <= Stack.back().DFSOut);
  297. }
  298. void PredicateInfoBuilder::popStackUntilDFSScope(ValueDFSStack &Stack,
  299. const ValueDFS &VD) {
  300. while (!Stack.empty() && !stackIsInScope(Stack, VD))
  301. Stack.pop_back();
  302. }
  303. // Convert the uses of Op into a vector of uses, associating global and local
  304. // DFS info with each one.
  305. void PredicateInfoBuilder::convertUsesToDFSOrdered(
  306. Value *Op, SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
  307. for (auto &U : Op->uses()) {
  308. if (auto *I = dyn_cast<Instruction>(U.getUser())) {
  309. ValueDFS VD;
  310. // Put the phi node uses in the incoming block.
  311. BasicBlock *IBlock;
  312. if (auto *PN = dyn_cast<PHINode>(I)) {
  313. IBlock = PN->getIncomingBlock(U);
  314. // Make phi node users appear last in the incoming block
  315. // they are from.
  316. VD.LocalNum = LN_Last;
  317. } else {
  318. // If it's not a phi node use, it is somewhere in the middle of the
  319. // block.
  320. IBlock = I->getParent();
  321. VD.LocalNum = LN_Middle;
  322. }
  323. DomTreeNode *DomNode = DT.getNode(IBlock);
  324. // It's possible our use is in an unreachable block. Skip it if so.
  325. if (!DomNode)
  326. continue;
  327. VD.DFSIn = DomNode->getDFSNumIn();
  328. VD.DFSOut = DomNode->getDFSNumOut();
  329. VD.U = &U;
  330. DFSOrderedSet.push_back(VD);
  331. }
  332. }
  333. }
  334. bool shouldRename(Value *V) {
  335. // Only want real values, not constants. Additionally, operands with one use
  336. // are only being used in the comparison, which means they will not be useful
  337. // for us to consider for predicateinfo.
  338. return (isa<Instruction>(V) || isa<Argument>(V)) && !V->hasOneUse();
  339. }
  340. // Collect relevant operations from Comparison that we may want to insert copies
  341. // for.
  342. void collectCmpOps(CmpInst *Comparison, SmallVectorImpl<Value *> &CmpOperands) {
  343. auto *Op0 = Comparison->getOperand(0);
  344. auto *Op1 = Comparison->getOperand(1);
  345. if (Op0 == Op1)
  346. return;
  347. CmpOperands.push_back(Op0);
  348. CmpOperands.push_back(Op1);
  349. }
  350. // Add Op, PB to the list of value infos for Op, and mark Op to be renamed.
  351. void PredicateInfoBuilder::addInfoFor(SmallVectorImpl<Value *> &OpsToRename,
  352. Value *Op, PredicateBase *PB) {
  353. auto &OperandInfo = getOrCreateValueInfo(Op);
  354. if (OperandInfo.Infos.empty())
  355. OpsToRename.push_back(Op);
  356. PI.AllInfos.push_back(PB);
  357. OperandInfo.Infos.push_back(PB);
  358. }
  359. // Process an assume instruction and place relevant operations we want to rename
  360. // into OpsToRename.
  361. void PredicateInfoBuilder::processAssume(
  362. IntrinsicInst *II, BasicBlock *AssumeBB,
  363. SmallVectorImpl<Value *> &OpsToRename) {
  364. SmallVector<Value *, 4> Worklist;
  365. SmallPtrSet<Value *, 4> Visited;
  366. Worklist.push_back(II->getOperand(0));
  367. while (!Worklist.empty()) {
  368. Value *Cond = Worklist.pop_back_val();
  369. if (!Visited.insert(Cond).second)
  370. continue;
  371. if (Visited.size() > MaxCondsPerBranch)
  372. break;
  373. Value *Op0, *Op1;
  374. if (match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
  375. Worklist.push_back(Op1);
  376. Worklist.push_back(Op0);
  377. }
  378. SmallVector<Value *, 4> Values;
  379. Values.push_back(Cond);
  380. if (auto *Cmp = dyn_cast<CmpInst>(Cond))
  381. collectCmpOps(Cmp, Values);
  382. for (Value *V : Values) {
  383. if (shouldRename(V)) {
  384. auto *PA = new PredicateAssume(V, II, Cond);
  385. addInfoFor(OpsToRename, V, PA);
  386. }
  387. }
  388. }
  389. }
  390. // Process a block terminating branch, and place relevant operations to be
  391. // renamed into OpsToRename.
  392. void PredicateInfoBuilder::processBranch(
  393. BranchInst *BI, BasicBlock *BranchBB,
  394. SmallVectorImpl<Value *> &OpsToRename) {
  395. BasicBlock *FirstBB = BI->getSuccessor(0);
  396. BasicBlock *SecondBB = BI->getSuccessor(1);
  397. for (BasicBlock *Succ : {FirstBB, SecondBB}) {
  398. bool TakenEdge = Succ == FirstBB;
  399. // Don't try to insert on a self-edge. This is mainly because we will
  400. // eliminate during renaming anyway.
  401. if (Succ == BranchBB)
  402. continue;
  403. SmallVector<Value *, 4> Worklist;
  404. SmallPtrSet<Value *, 4> Visited;
  405. Worklist.push_back(BI->getCondition());
  406. while (!Worklist.empty()) {
  407. Value *Cond = Worklist.pop_back_val();
  408. if (!Visited.insert(Cond).second)
  409. continue;
  410. if (Visited.size() > MaxCondsPerBranch)
  411. break;
  412. Value *Op0, *Op1;
  413. if (TakenEdge ? match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))
  414. : match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
  415. Worklist.push_back(Op1);
  416. Worklist.push_back(Op0);
  417. }
  418. SmallVector<Value *, 4> Values;
  419. Values.push_back(Cond);
  420. if (auto *Cmp = dyn_cast<CmpInst>(Cond))
  421. collectCmpOps(Cmp, Values);
  422. for (Value *V : Values) {
  423. if (shouldRename(V)) {
  424. PredicateBase *PB =
  425. new PredicateBranch(V, BranchBB, Succ, Cond, TakenEdge);
  426. addInfoFor(OpsToRename, V, PB);
  427. if (!Succ->getSinglePredecessor())
  428. EdgeUsesOnly.insert({BranchBB, Succ});
  429. }
  430. }
  431. }
  432. }
  433. }
  434. // Process a block terminating switch, and place relevant operations to be
  435. // renamed into OpsToRename.
  436. void PredicateInfoBuilder::processSwitch(
  437. SwitchInst *SI, BasicBlock *BranchBB,
  438. SmallVectorImpl<Value *> &OpsToRename) {
  439. Value *Op = SI->getCondition();
  440. if ((!isa<Instruction>(Op) && !isa<Argument>(Op)) || Op->hasOneUse())
  441. return;
  442. // Remember how many outgoing edges there are to every successor.
  443. SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
  444. for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
  445. BasicBlock *TargetBlock = SI->getSuccessor(i);
  446. ++SwitchEdges[TargetBlock];
  447. }
  448. // Now propagate info for each case value
  449. for (auto C : SI->cases()) {
  450. BasicBlock *TargetBlock = C.getCaseSuccessor();
  451. if (SwitchEdges.lookup(TargetBlock) == 1) {
  452. PredicateSwitch *PS = new PredicateSwitch(
  453. Op, SI->getParent(), TargetBlock, C.getCaseValue(), SI);
  454. addInfoFor(OpsToRename, Op, PS);
  455. if (!TargetBlock->getSinglePredecessor())
  456. EdgeUsesOnly.insert({BranchBB, TargetBlock});
  457. }
  458. }
  459. }
  460. // Build predicate info for our function
  461. void PredicateInfoBuilder::buildPredicateInfo() {
  462. DT.updateDFSNumbers();
  463. // Collect operands to rename from all conditional branch terminators, as well
  464. // as assume statements.
  465. SmallVector<Value *, 8> OpsToRename;
  466. for (auto DTN : depth_first(DT.getRootNode())) {
  467. BasicBlock *BranchBB = DTN->getBlock();
  468. if (auto *BI = dyn_cast<BranchInst>(BranchBB->getTerminator())) {
  469. if (!BI->isConditional())
  470. continue;
  471. // Can't insert conditional information if they all go to the same place.
  472. if (BI->getSuccessor(0) == BI->getSuccessor(1))
  473. continue;
  474. processBranch(BI, BranchBB, OpsToRename);
  475. } else if (auto *SI = dyn_cast<SwitchInst>(BranchBB->getTerminator())) {
  476. processSwitch(SI, BranchBB, OpsToRename);
  477. }
  478. }
  479. for (auto &Assume : AC.assumptions()) {
  480. if (auto *II = dyn_cast_or_null<IntrinsicInst>(Assume))
  481. if (DT.isReachableFromEntry(II->getParent()))
  482. processAssume(II, II->getParent(), OpsToRename);
  483. }
  484. // Now rename all our operations.
  485. renameUses(OpsToRename);
  486. }
  487. // Create a ssa_copy declaration with custom mangling, because
  488. // Intrinsic::getDeclaration does not handle overloaded unnamed types properly:
  489. // all unnamed types get mangled to the same string. We use the pointer
  490. // to the type as name here, as it guarantees unique names for different
  491. // types and we remove the declarations when destroying PredicateInfo.
  492. // It is a workaround for PR38117, because solving it in a fully general way is
  493. // tricky (FIXME).
  494. static Function *getCopyDeclaration(Module *M, Type *Ty) {
  495. std::string Name = "llvm.ssa.copy." + utostr((uintptr_t) Ty);
  496. return cast<Function>(
  497. M->getOrInsertFunction(Name,
  498. getType(M->getContext(), Intrinsic::ssa_copy, Ty))
  499. .getCallee());
  500. }
  501. // Given the renaming stack, make all the operands currently on the stack real
  502. // by inserting them into the IR. Return the last operation's value.
  503. Value *PredicateInfoBuilder::materializeStack(unsigned int &Counter,
  504. ValueDFSStack &RenameStack,
  505. Value *OrigOp) {
  506. // Find the first thing we have to materialize
  507. auto RevIter = RenameStack.rbegin();
  508. for (; RevIter != RenameStack.rend(); ++RevIter)
  509. if (RevIter->Def)
  510. break;
  511. size_t Start = RevIter - RenameStack.rbegin();
  512. // The maximum number of things we should be trying to materialize at once
  513. // right now is 4, depending on if we had an assume, a branch, and both used
  514. // and of conditions.
  515. for (auto RenameIter = RenameStack.end() - Start;
  516. RenameIter != RenameStack.end(); ++RenameIter) {
  517. auto *Op =
  518. RenameIter == RenameStack.begin() ? OrigOp : (RenameIter - 1)->Def;
  519. ValueDFS &Result = *RenameIter;
  520. auto *ValInfo = Result.PInfo;
  521. ValInfo->RenamedOp = (RenameStack.end() - Start) == RenameStack.begin()
  522. ? OrigOp
  523. : (RenameStack.end() - Start - 1)->Def;
  524. // For edge predicates, we can just place the operand in the block before
  525. // the terminator. For assume, we have to place it right before the assume
  526. // to ensure we dominate all of our uses. Always insert right before the
  527. // relevant instruction (terminator, assume), so that we insert in proper
  528. // order in the case of multiple predicateinfo in the same block.
  529. if (isa<PredicateWithEdge>(ValInfo)) {
  530. IRBuilder<> B(getBranchTerminator(ValInfo));
  531. Function *IF = getCopyDeclaration(F.getParent(), Op->getType());
  532. if (IF->users().empty())
  533. PI.CreatedDeclarations.insert(IF);
  534. CallInst *PIC =
  535. B.CreateCall(IF, Op, Op->getName() + "." + Twine(Counter++));
  536. PI.PredicateMap.insert({PIC, ValInfo});
  537. Result.Def = PIC;
  538. } else {
  539. auto *PAssume = dyn_cast<PredicateAssume>(ValInfo);
  540. assert(PAssume &&
  541. "Should not have gotten here without it being an assume");
  542. // Insert the predicate directly after the assume. While it also holds
  543. // directly before it, assume(i1 true) is not a useful fact.
  544. IRBuilder<> B(PAssume->AssumeInst->getNextNode());
  545. Function *IF = getCopyDeclaration(F.getParent(), Op->getType());
  546. if (IF->users().empty())
  547. PI.CreatedDeclarations.insert(IF);
  548. CallInst *PIC = B.CreateCall(IF, Op);
  549. PI.PredicateMap.insert({PIC, ValInfo});
  550. Result.Def = PIC;
  551. }
  552. }
  553. return RenameStack.back().Def;
  554. }
  555. // Instead of the standard SSA renaming algorithm, which is O(Number of
  556. // instructions), and walks the entire dominator tree, we walk only the defs +
  557. // uses. The standard SSA renaming algorithm does not really rely on the
  558. // dominator tree except to order the stack push/pops of the renaming stacks, so
  559. // that defs end up getting pushed before hitting the correct uses. This does
  560. // not require the dominator tree, only the *order* of the dominator tree. The
  561. // complete and correct ordering of the defs and uses, in dominator tree is
  562. // contained in the DFS numbering of the dominator tree. So we sort the defs and
  563. // uses into the DFS ordering, and then just use the renaming stack as per
  564. // normal, pushing when we hit a def (which is a predicateinfo instruction),
  565. // popping when we are out of the dfs scope for that def, and replacing any uses
  566. // with top of stack if it exists. In order to handle liveness without
  567. // propagating liveness info, we don't actually insert the predicateinfo
  568. // instruction def until we see a use that it would dominate. Once we see such
  569. // a use, we materialize the predicateinfo instruction in the right place and
  570. // use it.
  571. //
  572. // TODO: Use this algorithm to perform fast single-variable renaming in
  573. // promotememtoreg and memoryssa.
  574. void PredicateInfoBuilder::renameUses(SmallVectorImpl<Value *> &OpsToRename) {
  575. ValueDFS_Compare Compare(DT);
  576. // Compute liveness, and rename in O(uses) per Op.
  577. for (auto *Op : OpsToRename) {
  578. LLVM_DEBUG(dbgs() << "Visiting " << *Op << "\n");
  579. unsigned Counter = 0;
  580. SmallVector<ValueDFS, 16> OrderedUses;
  581. const auto &ValueInfo = getValueInfo(Op);
  582. // Insert the possible copies into the def/use list.
  583. // They will become real copies if we find a real use for them, and never
  584. // created otherwise.
  585. for (auto &PossibleCopy : ValueInfo.Infos) {
  586. ValueDFS VD;
  587. // Determine where we are going to place the copy by the copy type.
  588. // The predicate info for branches always come first, they will get
  589. // materialized in the split block at the top of the block.
  590. // The predicate info for assumes will be somewhere in the middle,
  591. // it will get materialized in front of the assume.
  592. if (const auto *PAssume = dyn_cast<PredicateAssume>(PossibleCopy)) {
  593. VD.LocalNum = LN_Middle;
  594. DomTreeNode *DomNode = DT.getNode(PAssume->AssumeInst->getParent());
  595. if (!DomNode)
  596. continue;
  597. VD.DFSIn = DomNode->getDFSNumIn();
  598. VD.DFSOut = DomNode->getDFSNumOut();
  599. VD.PInfo = PossibleCopy;
  600. OrderedUses.push_back(VD);
  601. } else if (isa<PredicateWithEdge>(PossibleCopy)) {
  602. // If we can only do phi uses, we treat it like it's in the branch
  603. // block, and handle it specially. We know that it goes last, and only
  604. // dominate phi uses.
  605. auto BlockEdge = getBlockEdge(PossibleCopy);
  606. if (EdgeUsesOnly.count(BlockEdge)) {
  607. VD.LocalNum = LN_Last;
  608. auto *DomNode = DT.getNode(BlockEdge.first);
  609. if (DomNode) {
  610. VD.DFSIn = DomNode->getDFSNumIn();
  611. VD.DFSOut = DomNode->getDFSNumOut();
  612. VD.PInfo = PossibleCopy;
  613. VD.EdgeOnly = true;
  614. OrderedUses.push_back(VD);
  615. }
  616. } else {
  617. // Otherwise, we are in the split block (even though we perform
  618. // insertion in the branch block).
  619. // Insert a possible copy at the split block and before the branch.
  620. VD.LocalNum = LN_First;
  621. auto *DomNode = DT.getNode(BlockEdge.second);
  622. if (DomNode) {
  623. VD.DFSIn = DomNode->getDFSNumIn();
  624. VD.DFSOut = DomNode->getDFSNumOut();
  625. VD.PInfo = PossibleCopy;
  626. OrderedUses.push_back(VD);
  627. }
  628. }
  629. }
  630. }
  631. convertUsesToDFSOrdered(Op, OrderedUses);
  632. // Here we require a stable sort because we do not bother to try to
  633. // assign an order to the operands the uses represent. Thus, two
  634. // uses in the same instruction do not have a strict sort order
  635. // currently and will be considered equal. We could get rid of the
  636. // stable sort by creating one if we wanted.
  637. llvm::stable_sort(OrderedUses, Compare);
  638. SmallVector<ValueDFS, 8> RenameStack;
  639. // For each use, sorted into dfs order, push values and replaces uses with
  640. // top of stack, which will represent the reaching def.
  641. for (auto &VD : OrderedUses) {
  642. // We currently do not materialize copy over copy, but we should decide if
  643. // we want to.
  644. bool PossibleCopy = VD.PInfo != nullptr;
  645. if (RenameStack.empty()) {
  646. LLVM_DEBUG(dbgs() << "Rename Stack is empty\n");
  647. } else {
  648. LLVM_DEBUG(dbgs() << "Rename Stack Top DFS numbers are ("
  649. << RenameStack.back().DFSIn << ","
  650. << RenameStack.back().DFSOut << ")\n");
  651. }
  652. LLVM_DEBUG(dbgs() << "Current DFS numbers are (" << VD.DFSIn << ","
  653. << VD.DFSOut << ")\n");
  654. bool ShouldPush = (VD.Def || PossibleCopy);
  655. bool OutOfScope = !stackIsInScope(RenameStack, VD);
  656. if (OutOfScope || ShouldPush) {
  657. // Sync to our current scope.
  658. popStackUntilDFSScope(RenameStack, VD);
  659. if (ShouldPush) {
  660. RenameStack.push_back(VD);
  661. }
  662. }
  663. // If we get to this point, and the stack is empty we must have a use
  664. // with no renaming needed, just skip it.
  665. if (RenameStack.empty())
  666. continue;
  667. // Skip values, only want to rename the uses
  668. if (VD.Def || PossibleCopy)
  669. continue;
  670. if (!DebugCounter::shouldExecute(RenameCounter)) {
  671. LLVM_DEBUG(dbgs() << "Skipping execution due to debug counter\n");
  672. continue;
  673. }
  674. ValueDFS &Result = RenameStack.back();
  675. // If the possible copy dominates something, materialize our stack up to
  676. // this point. This ensures every comparison that affects our operation
  677. // ends up with predicateinfo.
  678. if (!Result.Def)
  679. Result.Def = materializeStack(Counter, RenameStack, Op);
  680. LLVM_DEBUG(dbgs() << "Found replacement " << *Result.Def << " for "
  681. << *VD.U->get() << " in " << *(VD.U->getUser())
  682. << "\n");
  683. assert(DT.dominates(cast<Instruction>(Result.Def), *VD.U) &&
  684. "Predicateinfo def should have dominated this use");
  685. VD.U->set(Result.Def);
  686. }
  687. }
  688. }
  689. PredicateInfoBuilder::ValueInfo &
  690. PredicateInfoBuilder::getOrCreateValueInfo(Value *Operand) {
  691. auto OIN = ValueInfoNums.find(Operand);
  692. if (OIN == ValueInfoNums.end()) {
  693. // This will grow it
  694. ValueInfos.resize(ValueInfos.size() + 1);
  695. // This will use the new size and give us a 0 based number of the info
  696. auto InsertResult = ValueInfoNums.insert({Operand, ValueInfos.size() - 1});
  697. assert(InsertResult.second && "Value info number already existed?");
  698. return ValueInfos[InsertResult.first->second];
  699. }
  700. return ValueInfos[OIN->second];
  701. }
  702. const PredicateInfoBuilder::ValueInfo &
  703. PredicateInfoBuilder::getValueInfo(Value *Operand) const {
  704. auto OINI = ValueInfoNums.lookup(Operand);
  705. assert(OINI != 0 && "Operand was not really in the Value Info Numbers");
  706. assert(OINI < ValueInfos.size() &&
  707. "Value Info Number greater than size of Value Info Table");
  708. return ValueInfos[OINI];
  709. }
  710. PredicateInfo::PredicateInfo(Function &F, DominatorTree &DT,
  711. AssumptionCache &AC)
  712. : F(F) {
  713. PredicateInfoBuilder Builder(*this, F, DT, AC);
  714. Builder.buildPredicateInfo();
  715. }
  716. // Remove all declarations we created . The PredicateInfo consumers are
  717. // responsible for remove the ssa_copy calls created.
  718. PredicateInfo::~PredicateInfo() {
  719. // Collect function pointers in set first, as SmallSet uses a SmallVector
  720. // internally and we have to remove the asserting value handles first.
  721. SmallPtrSet<Function *, 20> FunctionPtrs;
  722. for (auto &F : CreatedDeclarations)
  723. FunctionPtrs.insert(&*F);
  724. CreatedDeclarations.clear();
  725. for (Function *F : FunctionPtrs) {
  726. assert(F->user_begin() == F->user_end() &&
  727. "PredicateInfo consumer did not remove all SSA copies.");
  728. F->eraseFromParent();
  729. }
  730. }
  731. Optional<PredicateConstraint> PredicateBase::getConstraint() const {
  732. switch (Type) {
  733. case PT_Assume:
  734. case PT_Branch: {
  735. bool TrueEdge = true;
  736. if (auto *PBranch = dyn_cast<PredicateBranch>(this))
  737. TrueEdge = PBranch->TrueEdge;
  738. if (Condition == RenamedOp) {
  739. return {{CmpInst::ICMP_EQ,
  740. TrueEdge ? ConstantInt::getTrue(Condition->getType())
  741. : ConstantInt::getFalse(Condition->getType())}};
  742. }
  743. CmpInst *Cmp = dyn_cast<CmpInst>(Condition);
  744. if (!Cmp) {
  745. // TODO: Make this an assertion once RenamedOp is fully accurate.
  746. return None;
  747. }
  748. CmpInst::Predicate Pred;
  749. Value *OtherOp;
  750. if (Cmp->getOperand(0) == RenamedOp) {
  751. Pred = Cmp->getPredicate();
  752. OtherOp = Cmp->getOperand(1);
  753. } else if (Cmp->getOperand(1) == RenamedOp) {
  754. Pred = Cmp->getSwappedPredicate();
  755. OtherOp = Cmp->getOperand(0);
  756. } else {
  757. // TODO: Make this an assertion once RenamedOp is fully accurate.
  758. return None;
  759. }
  760. // Invert predicate along false edge.
  761. if (!TrueEdge)
  762. Pred = CmpInst::getInversePredicate(Pred);
  763. return {{Pred, OtherOp}};
  764. }
  765. case PT_Switch:
  766. if (Condition != RenamedOp) {
  767. // TODO: Make this an assertion once RenamedOp is fully accurate.
  768. return None;
  769. }
  770. return {{CmpInst::ICMP_EQ, cast<PredicateSwitch>(this)->CaseValue}};
  771. }
  772. llvm_unreachable("Unknown predicate type");
  773. }
  774. void PredicateInfo::verifyPredicateInfo() const {}
  775. char PredicateInfoPrinterLegacyPass::ID = 0;
  776. PredicateInfoPrinterLegacyPass::PredicateInfoPrinterLegacyPass()
  777. : FunctionPass(ID) {
  778. initializePredicateInfoPrinterLegacyPassPass(
  779. *PassRegistry::getPassRegistry());
  780. }
  781. void PredicateInfoPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
  782. AU.setPreservesAll();
  783. AU.addRequiredTransitive<DominatorTreeWrapperPass>();
  784. AU.addRequired<AssumptionCacheTracker>();
  785. }
  786. // Replace ssa_copy calls created by PredicateInfo with their operand.
  787. static void replaceCreatedSSACopys(PredicateInfo &PredInfo, Function &F) {
  788. for (auto I = inst_begin(F), E = inst_end(F); I != E;) {
  789. Instruction *Inst = &*I++;
  790. const auto *PI = PredInfo.getPredicateInfoFor(Inst);
  791. auto *II = dyn_cast<IntrinsicInst>(Inst);
  792. if (!PI || !II || II->getIntrinsicID() != Intrinsic::ssa_copy)
  793. continue;
  794. Inst->replaceAllUsesWith(II->getOperand(0));
  795. Inst->eraseFromParent();
  796. }
  797. }
  798. bool PredicateInfoPrinterLegacyPass::runOnFunction(Function &F) {
  799. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  800. auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  801. auto PredInfo = std::make_unique<PredicateInfo>(F, DT, AC);
  802. PredInfo->print(dbgs());
  803. if (VerifyPredicateInfo)
  804. PredInfo->verifyPredicateInfo();
  805. replaceCreatedSSACopys(*PredInfo, F);
  806. return false;
  807. }
  808. PreservedAnalyses PredicateInfoPrinterPass::run(Function &F,
  809. FunctionAnalysisManager &AM) {
  810. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  811. auto &AC = AM.getResult<AssumptionAnalysis>(F);
  812. OS << "PredicateInfo for function: " << F.getName() << "\n";
  813. auto PredInfo = std::make_unique<PredicateInfo>(F, DT, AC);
  814. PredInfo->print(OS);
  815. replaceCreatedSSACopys(*PredInfo, F);
  816. return PreservedAnalyses::all();
  817. }
  818. /// An assembly annotator class to print PredicateInfo information in
  819. /// comments.
  820. class PredicateInfoAnnotatedWriter : public AssemblyAnnotationWriter {
  821. friend class PredicateInfo;
  822. const PredicateInfo *PredInfo;
  823. public:
  824. PredicateInfoAnnotatedWriter(const PredicateInfo *M) : PredInfo(M) {}
  825. void emitBasicBlockStartAnnot(const BasicBlock *BB,
  826. formatted_raw_ostream &OS) override {}
  827. void emitInstructionAnnot(const Instruction *I,
  828. formatted_raw_ostream &OS) override {
  829. if (const auto *PI = PredInfo->getPredicateInfoFor(I)) {
  830. OS << "; Has predicate info\n";
  831. if (const auto *PB = dyn_cast<PredicateBranch>(PI)) {
  832. OS << "; branch predicate info { TrueEdge: " << PB->TrueEdge
  833. << " Comparison:" << *PB->Condition << " Edge: [";
  834. PB->From->printAsOperand(OS);
  835. OS << ",";
  836. PB->To->printAsOperand(OS);
  837. OS << "]";
  838. } else if (const auto *PS = dyn_cast<PredicateSwitch>(PI)) {
  839. OS << "; switch predicate info { CaseValue: " << *PS->CaseValue
  840. << " Switch:" << *PS->Switch << " Edge: [";
  841. PS->From->printAsOperand(OS);
  842. OS << ",";
  843. PS->To->printAsOperand(OS);
  844. OS << "]";
  845. } else if (const auto *PA = dyn_cast<PredicateAssume>(PI)) {
  846. OS << "; assume predicate info {"
  847. << " Comparison:" << *PA->Condition;
  848. }
  849. OS << ", RenamedOp: ";
  850. PI->RenamedOp->printAsOperand(OS, false);
  851. OS << " }\n";
  852. }
  853. }
  854. };
  855. void PredicateInfo::print(raw_ostream &OS) const {
  856. PredicateInfoAnnotatedWriter Writer(this);
  857. F.print(OS, &Writer);
  858. }
  859. void PredicateInfo::dump() const {
  860. PredicateInfoAnnotatedWriter Writer(this);
  861. F.print(dbgs(), &Writer);
  862. }
  863. PreservedAnalyses PredicateInfoVerifierPass::run(Function &F,
  864. FunctionAnalysisManager &AM) {
  865. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  866. auto &AC = AM.getResult<AssumptionAnalysis>(F);
  867. std::make_unique<PredicateInfo>(F, DT, AC)->verifyPredicateInfo();
  868. return PreservedAnalyses::all();
  869. }
  870. }