PredicateInfo.cpp 36 KB

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