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