PredicateInfo.cpp 34 KB

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