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