109467b48Spatrick //===-- PredicateInfo.cpp - PredicateInfo Builder--------------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This file implements the PredicateInfo class.
1009467b48Spatrick //
1109467b48Spatrick //===----------------------------------------------------------------===//
1209467b48Spatrick
1309467b48Spatrick #include "llvm/Transforms/Utils/PredicateInfo.h"
1409467b48Spatrick #include "llvm/ADT/DenseMap.h"
1509467b48Spatrick #include "llvm/ADT/DepthFirstIterator.h"
1609467b48Spatrick #include "llvm/ADT/STLExtras.h"
1709467b48Spatrick #include "llvm/ADT/SmallPtrSet.h"
1809467b48Spatrick #include "llvm/Analysis/AssumptionCache.h"
1909467b48Spatrick #include "llvm/IR/AssemblyAnnotationWriter.h"
2009467b48Spatrick #include "llvm/IR/Dominators.h"
2109467b48Spatrick #include "llvm/IR/IRBuilder.h"
2209467b48Spatrick #include "llvm/IR/InstIterator.h"
2309467b48Spatrick #include "llvm/IR/IntrinsicInst.h"
2409467b48Spatrick #include "llvm/IR/Module.h"
2509467b48Spatrick #include "llvm/IR/PatternMatch.h"
2609467b48Spatrick #include "llvm/InitializePasses.h"
27097a140dSpatrick #include "llvm/Support/CommandLine.h"
2809467b48Spatrick #include "llvm/Support/Debug.h"
2909467b48Spatrick #include "llvm/Support/DebugCounter.h"
3009467b48Spatrick #include "llvm/Support/FormattedStream.h"
3109467b48Spatrick #include <algorithm>
3209467b48Spatrick #define DEBUG_TYPE "predicateinfo"
3309467b48Spatrick using namespace llvm;
3409467b48Spatrick using namespace PatternMatch;
3509467b48Spatrick
3609467b48Spatrick INITIALIZE_PASS_BEGIN(PredicateInfoPrinterLegacyPass, "print-predicateinfo",
3709467b48Spatrick "PredicateInfo Printer", false, false)
3809467b48Spatrick INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3909467b48Spatrick INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
4009467b48Spatrick INITIALIZE_PASS_END(PredicateInfoPrinterLegacyPass, "print-predicateinfo",
4109467b48Spatrick "PredicateInfo Printer", false, false)
4209467b48Spatrick static cl::opt<bool> VerifyPredicateInfo(
4309467b48Spatrick "verify-predicateinfo", cl::init(false), cl::Hidden,
4409467b48Spatrick cl::desc("Verify PredicateInfo in legacy printer pass."));
4509467b48Spatrick DEBUG_COUNTER(RenameCounter, "predicateinfo-rename",
4609467b48Spatrick "Controls which variables are renamed with predicateinfo");
4709467b48Spatrick
4873471bf0Spatrick // Maximum number of conditions considered for renaming for each branch/assume.
4973471bf0Spatrick // This limits renaming of deep and/or chains.
5073471bf0Spatrick static const unsigned MaxCondsPerBranch = 8;
5173471bf0Spatrick
5209467b48Spatrick namespace {
5309467b48Spatrick // Given a predicate info that is a type of branching terminator, get the
5409467b48Spatrick // branching block.
getBranchBlock(const PredicateBase * PB)5509467b48Spatrick const BasicBlock *getBranchBlock(const PredicateBase *PB) {
5609467b48Spatrick assert(isa<PredicateWithEdge>(PB) &&
5709467b48Spatrick "Only branches and switches should have PHIOnly defs that "
5809467b48Spatrick "require branch blocks.");
5909467b48Spatrick return cast<PredicateWithEdge>(PB)->From;
6009467b48Spatrick }
6109467b48Spatrick
6209467b48Spatrick // Given a predicate info that is a type of branching terminator, get the
6309467b48Spatrick // branching terminator.
getBranchTerminator(const PredicateBase * PB)6409467b48Spatrick static Instruction *getBranchTerminator(const PredicateBase *PB) {
6509467b48Spatrick assert(isa<PredicateWithEdge>(PB) &&
6609467b48Spatrick "Not a predicate info type we know how to get a terminator from.");
6709467b48Spatrick return cast<PredicateWithEdge>(PB)->From->getTerminator();
6809467b48Spatrick }
6909467b48Spatrick
7009467b48Spatrick // Given a predicate info that is a type of branching terminator, get the
7109467b48Spatrick // edge this predicate info represents
getBlockEdge(const PredicateBase * PB)7273471bf0Spatrick std::pair<BasicBlock *, BasicBlock *> getBlockEdge(const PredicateBase *PB) {
7309467b48Spatrick assert(isa<PredicateWithEdge>(PB) &&
7409467b48Spatrick "Not a predicate info type we know how to get an edge from.");
7509467b48Spatrick const auto *PEdge = cast<PredicateWithEdge>(PB);
7609467b48Spatrick return std::make_pair(PEdge->From, PEdge->To);
7709467b48Spatrick }
7809467b48Spatrick }
7909467b48Spatrick
8009467b48Spatrick namespace llvm {
8109467b48Spatrick enum LocalNum {
8209467b48Spatrick // Operations that must appear first in the block.
8309467b48Spatrick LN_First,
8409467b48Spatrick // Operations that are somewhere in the middle of the block, and are sorted on
8509467b48Spatrick // demand.
8609467b48Spatrick LN_Middle,
8709467b48Spatrick // Operations that must appear last in a block, like successor phi node uses.
8809467b48Spatrick LN_Last
8909467b48Spatrick };
9009467b48Spatrick
9109467b48Spatrick // Associate global and local DFS info with defs and uses, so we can sort them
9209467b48Spatrick // into a global domination ordering.
9309467b48Spatrick struct ValueDFS {
9409467b48Spatrick int DFSIn = 0;
9509467b48Spatrick int DFSOut = 0;
9609467b48Spatrick unsigned int LocalNum = LN_Middle;
9709467b48Spatrick // Only one of Def or Use will be set.
9809467b48Spatrick Value *Def = nullptr;
9909467b48Spatrick Use *U = nullptr;
10009467b48Spatrick // Neither PInfo nor EdgeOnly participate in the ordering
10109467b48Spatrick PredicateBase *PInfo = nullptr;
10209467b48Spatrick bool EdgeOnly = false;
10309467b48Spatrick };
10409467b48Spatrick
10509467b48Spatrick // Perform a strict weak ordering on instructions and arguments.
valueComesBefore(const Value * A,const Value * B)106097a140dSpatrick static bool valueComesBefore(const Value *A, const Value *B) {
10709467b48Spatrick auto *ArgA = dyn_cast_or_null<Argument>(A);
10809467b48Spatrick auto *ArgB = dyn_cast_or_null<Argument>(B);
10909467b48Spatrick if (ArgA && !ArgB)
11009467b48Spatrick return true;
11109467b48Spatrick if (ArgB && !ArgA)
11209467b48Spatrick return false;
11309467b48Spatrick if (ArgA && ArgB)
11409467b48Spatrick return ArgA->getArgNo() < ArgB->getArgNo();
115097a140dSpatrick return cast<Instruction>(A)->comesBefore(cast<Instruction>(B));
11609467b48Spatrick }
11709467b48Spatrick
118097a140dSpatrick // This compares ValueDFS structures. Doing so allows us to walk the minimum
119097a140dSpatrick // number of instructions necessary to compute our def/use ordering.
12009467b48Spatrick struct ValueDFS_Compare {
12109467b48Spatrick DominatorTree &DT;
ValueDFS_Comparellvm::ValueDFS_Compare122097a140dSpatrick ValueDFS_Compare(DominatorTree &DT) : DT(DT) {}
12309467b48Spatrick
operator ()llvm::ValueDFS_Compare12409467b48Spatrick bool operator()(const ValueDFS &A, const ValueDFS &B) const {
12509467b48Spatrick if (&A == &B)
12609467b48Spatrick return false;
12709467b48Spatrick // The only case we can't directly compare them is when they in the same
12809467b48Spatrick // block, and both have localnum == middle. In that case, we have to use
12909467b48Spatrick // comesbefore to see what the real ordering is, because they are in the
13009467b48Spatrick // same basic block.
13109467b48Spatrick
13209467b48Spatrick assert((A.DFSIn != B.DFSIn || A.DFSOut == B.DFSOut) &&
13309467b48Spatrick "Equal DFS-in numbers imply equal out numbers");
13409467b48Spatrick bool SameBlock = A.DFSIn == B.DFSIn;
13509467b48Spatrick
13609467b48Spatrick // We want to put the def that will get used for a given set of phi uses,
13709467b48Spatrick // before those phi uses.
13809467b48Spatrick // So we sort by edge, then by def.
13909467b48Spatrick // Note that only phi nodes uses and defs can come last.
14009467b48Spatrick if (SameBlock && A.LocalNum == LN_Last && B.LocalNum == LN_Last)
14109467b48Spatrick return comparePHIRelated(A, B);
14209467b48Spatrick
14309467b48Spatrick bool isADef = A.Def;
14409467b48Spatrick bool isBDef = B.Def;
14509467b48Spatrick if (!SameBlock || A.LocalNum != LN_Middle || B.LocalNum != LN_Middle)
14609467b48Spatrick return std::tie(A.DFSIn, A.LocalNum, isADef) <
14709467b48Spatrick std::tie(B.DFSIn, B.LocalNum, isBDef);
14809467b48Spatrick return localComesBefore(A, B);
14909467b48Spatrick }
15009467b48Spatrick
15109467b48Spatrick // For a phi use, or a non-materialized def, return the edge it represents.
getBlockEdgellvm::ValueDFS_Compare15273471bf0Spatrick std::pair<BasicBlock *, BasicBlock *> getBlockEdge(const ValueDFS &VD) const {
15309467b48Spatrick if (!VD.Def && VD.U) {
15409467b48Spatrick auto *PHI = cast<PHINode>(VD.U->getUser());
15509467b48Spatrick return std::make_pair(PHI->getIncomingBlock(*VD.U), PHI->getParent());
15609467b48Spatrick }
15709467b48Spatrick // This is really a non-materialized def.
15809467b48Spatrick return ::getBlockEdge(VD.PInfo);
15909467b48Spatrick }
16009467b48Spatrick
16109467b48Spatrick // For two phi related values, return the ordering.
comparePHIRelatedllvm::ValueDFS_Compare16209467b48Spatrick bool comparePHIRelated(const ValueDFS &A, const ValueDFS &B) const {
16309467b48Spatrick BasicBlock *ASrc, *ADest, *BSrc, *BDest;
16409467b48Spatrick std::tie(ASrc, ADest) = getBlockEdge(A);
16509467b48Spatrick std::tie(BSrc, BDest) = getBlockEdge(B);
16609467b48Spatrick
16709467b48Spatrick #ifndef NDEBUG
16809467b48Spatrick // This function should only be used for values in the same BB, check that.
16909467b48Spatrick DomTreeNode *DomASrc = DT.getNode(ASrc);
17009467b48Spatrick DomTreeNode *DomBSrc = DT.getNode(BSrc);
17109467b48Spatrick assert(DomASrc->getDFSNumIn() == (unsigned)A.DFSIn &&
17209467b48Spatrick "DFS numbers for A should match the ones of the source block");
17309467b48Spatrick assert(DomBSrc->getDFSNumIn() == (unsigned)B.DFSIn &&
17409467b48Spatrick "DFS numbers for B should match the ones of the source block");
17509467b48Spatrick assert(A.DFSIn == B.DFSIn && "Values must be in the same block");
17609467b48Spatrick #endif
17709467b48Spatrick (void)ASrc;
17809467b48Spatrick (void)BSrc;
17909467b48Spatrick
18009467b48Spatrick // Use DFS numbers to compare destination blocks, to guarantee a
18109467b48Spatrick // deterministic order.
18209467b48Spatrick DomTreeNode *DomADest = DT.getNode(ADest);
18309467b48Spatrick DomTreeNode *DomBDest = DT.getNode(BDest);
18409467b48Spatrick unsigned AIn = DomADest->getDFSNumIn();
18509467b48Spatrick unsigned BIn = DomBDest->getDFSNumIn();
18609467b48Spatrick bool isADef = A.Def;
18709467b48Spatrick bool isBDef = B.Def;
18809467b48Spatrick assert((!A.Def || !A.U) && (!B.Def || !B.U) &&
18909467b48Spatrick "Def and U cannot be set at the same time");
19009467b48Spatrick // Now sort by edge destination and then defs before uses.
19109467b48Spatrick return std::tie(AIn, isADef) < std::tie(BIn, isBDef);
19209467b48Spatrick }
19309467b48Spatrick
19409467b48Spatrick // Get the definition of an instruction that occurs in the middle of a block.
getMiddleDefllvm::ValueDFS_Compare19509467b48Spatrick Value *getMiddleDef(const ValueDFS &VD) const {
19609467b48Spatrick if (VD.Def)
19709467b48Spatrick return VD.Def;
19809467b48Spatrick // It's possible for the defs and uses to be null. For branches, the local
19909467b48Spatrick // numbering will say the placed predicaeinfos should go first (IE
20009467b48Spatrick // LN_beginning), so we won't be in this function. For assumes, we will end
20109467b48Spatrick // up here, beause we need to order the def we will place relative to the
202097a140dSpatrick // assume. So for the purpose of ordering, we pretend the def is right
203097a140dSpatrick // after the assume, because that is where we will insert the info.
20409467b48Spatrick if (!VD.U) {
20509467b48Spatrick assert(VD.PInfo &&
20609467b48Spatrick "No def, no use, and no predicateinfo should not occur");
20709467b48Spatrick assert(isa<PredicateAssume>(VD.PInfo) &&
20809467b48Spatrick "Middle of block should only occur for assumes");
209097a140dSpatrick return cast<PredicateAssume>(VD.PInfo)->AssumeInst->getNextNode();
21009467b48Spatrick }
21109467b48Spatrick return nullptr;
21209467b48Spatrick }
21309467b48Spatrick
21409467b48Spatrick // Return either the Def, if it's not null, or the user of the Use, if the def
21509467b48Spatrick // is null.
getDefOrUserllvm::ValueDFS_Compare21609467b48Spatrick const Instruction *getDefOrUser(const Value *Def, const Use *U) const {
21709467b48Spatrick if (Def)
21809467b48Spatrick return cast<Instruction>(Def);
21909467b48Spatrick return cast<Instruction>(U->getUser());
22009467b48Spatrick }
22109467b48Spatrick
22209467b48Spatrick // This performs the necessary local basic block ordering checks to tell
22309467b48Spatrick // whether A comes before B, where both are in the same basic block.
localComesBeforellvm::ValueDFS_Compare22409467b48Spatrick bool localComesBefore(const ValueDFS &A, const ValueDFS &B) const {
22509467b48Spatrick auto *ADef = getMiddleDef(A);
22609467b48Spatrick auto *BDef = getMiddleDef(B);
22709467b48Spatrick
22809467b48Spatrick // See if we have real values or uses. If we have real values, we are
22909467b48Spatrick // guaranteed they are instructions or arguments. No matter what, we are
23009467b48Spatrick // guaranteed they are in the same block if they are instructions.
23109467b48Spatrick auto *ArgA = dyn_cast_or_null<Argument>(ADef);
23209467b48Spatrick auto *ArgB = dyn_cast_or_null<Argument>(BDef);
23309467b48Spatrick
23409467b48Spatrick if (ArgA || ArgB)
235097a140dSpatrick return valueComesBefore(ArgA, ArgB);
23609467b48Spatrick
23709467b48Spatrick auto *AInst = getDefOrUser(ADef, A.U);
23809467b48Spatrick auto *BInst = getDefOrUser(BDef, B.U);
239097a140dSpatrick return valueComesBefore(AInst, BInst);
24009467b48Spatrick }
24109467b48Spatrick };
24209467b48Spatrick
243097a140dSpatrick class PredicateInfoBuilder {
244097a140dSpatrick // Used to store information about each value we might rename.
245097a140dSpatrick struct ValueInfo {
246097a140dSpatrick SmallVector<PredicateBase *, 4> Infos;
247097a140dSpatrick };
24809467b48Spatrick
249097a140dSpatrick PredicateInfo &PI;
250097a140dSpatrick Function &F;
251097a140dSpatrick DominatorTree &DT;
252097a140dSpatrick AssumptionCache &AC;
253097a140dSpatrick
254097a140dSpatrick // This stores info about each operand or comparison result we make copies
255097a140dSpatrick // of. The real ValueInfos start at index 1, index 0 is unused so that we
256097a140dSpatrick // can more easily detect invalid indexing.
257097a140dSpatrick SmallVector<ValueInfo, 32> ValueInfos;
258097a140dSpatrick
259097a140dSpatrick // This gives the index into the ValueInfos array for a given Value. Because
260097a140dSpatrick // 0 is not a valid Value Info index, you can use DenseMap::lookup and tell
261097a140dSpatrick // whether it returned a valid result.
262097a140dSpatrick DenseMap<Value *, unsigned int> ValueInfoNums;
263097a140dSpatrick
264097a140dSpatrick // The set of edges along which we can only handle phi uses, due to critical
265097a140dSpatrick // edges.
266097a140dSpatrick DenseSet<std::pair<BasicBlock *, BasicBlock *>> EdgeUsesOnly;
267097a140dSpatrick
268097a140dSpatrick ValueInfo &getOrCreateValueInfo(Value *);
269097a140dSpatrick const ValueInfo &getValueInfo(Value *) const;
270097a140dSpatrick
271097a140dSpatrick void processAssume(IntrinsicInst *, BasicBlock *,
272097a140dSpatrick SmallVectorImpl<Value *> &OpsToRename);
273097a140dSpatrick void processBranch(BranchInst *, BasicBlock *,
274097a140dSpatrick SmallVectorImpl<Value *> &OpsToRename);
275097a140dSpatrick void processSwitch(SwitchInst *, BasicBlock *,
276097a140dSpatrick SmallVectorImpl<Value *> &OpsToRename);
277097a140dSpatrick void renameUses(SmallVectorImpl<Value *> &OpsToRename);
278097a140dSpatrick void addInfoFor(SmallVectorImpl<Value *> &OpsToRename, Value *Op,
279097a140dSpatrick PredicateBase *PB);
280097a140dSpatrick
281097a140dSpatrick typedef SmallVectorImpl<ValueDFS> ValueDFSStack;
282097a140dSpatrick void convertUsesToDFSOrdered(Value *, SmallVectorImpl<ValueDFS> &);
283097a140dSpatrick Value *materializeStack(unsigned int &, ValueDFSStack &, Value *);
284097a140dSpatrick bool stackIsInScope(const ValueDFSStack &, const ValueDFS &) const;
285097a140dSpatrick void popStackUntilDFSScope(ValueDFSStack &, const ValueDFS &);
286097a140dSpatrick
287097a140dSpatrick public:
PredicateInfoBuilder(PredicateInfo & PI,Function & F,DominatorTree & DT,AssumptionCache & AC)288097a140dSpatrick PredicateInfoBuilder(PredicateInfo &PI, Function &F, DominatorTree &DT,
289097a140dSpatrick AssumptionCache &AC)
290097a140dSpatrick : PI(PI), F(F), DT(DT), AC(AC) {
291097a140dSpatrick // Push an empty operand info so that we can detect 0 as not finding one
292097a140dSpatrick ValueInfos.resize(1);
293097a140dSpatrick }
294097a140dSpatrick
295097a140dSpatrick void buildPredicateInfo();
296097a140dSpatrick };
297097a140dSpatrick
stackIsInScope(const ValueDFSStack & Stack,const ValueDFS & VDUse) const298097a140dSpatrick bool PredicateInfoBuilder::stackIsInScope(const ValueDFSStack &Stack,
29909467b48Spatrick const ValueDFS &VDUse) const {
30009467b48Spatrick if (Stack.empty())
30109467b48Spatrick return false;
30209467b48Spatrick // If it's a phi only use, make sure it's for this phi node edge, and that the
30309467b48Spatrick // use is in a phi node. If it's anything else, and the top of the stack is
30409467b48Spatrick // EdgeOnly, we need to pop the stack. We deliberately sort phi uses next to
30509467b48Spatrick // the defs they must go with so that we can know it's time to pop the stack
30609467b48Spatrick // when we hit the end of the phi uses for a given def.
30709467b48Spatrick if (Stack.back().EdgeOnly) {
30809467b48Spatrick if (!VDUse.U)
30909467b48Spatrick return false;
31009467b48Spatrick auto *PHI = dyn_cast<PHINode>(VDUse.U->getUser());
31109467b48Spatrick if (!PHI)
31209467b48Spatrick return false;
31309467b48Spatrick // Check edge
31409467b48Spatrick BasicBlock *EdgePred = PHI->getIncomingBlock(*VDUse.U);
31509467b48Spatrick if (EdgePred != getBranchBlock(Stack.back().PInfo))
31609467b48Spatrick return false;
31709467b48Spatrick
31809467b48Spatrick // Use dominates, which knows how to handle edge dominance.
31909467b48Spatrick return DT.dominates(getBlockEdge(Stack.back().PInfo), *VDUse.U);
32009467b48Spatrick }
32109467b48Spatrick
32209467b48Spatrick return (VDUse.DFSIn >= Stack.back().DFSIn &&
32309467b48Spatrick VDUse.DFSOut <= Stack.back().DFSOut);
32409467b48Spatrick }
32509467b48Spatrick
popStackUntilDFSScope(ValueDFSStack & Stack,const ValueDFS & VD)326097a140dSpatrick void PredicateInfoBuilder::popStackUntilDFSScope(ValueDFSStack &Stack,
32709467b48Spatrick const ValueDFS &VD) {
32809467b48Spatrick while (!Stack.empty() && !stackIsInScope(Stack, VD))
32909467b48Spatrick Stack.pop_back();
33009467b48Spatrick }
33109467b48Spatrick
33209467b48Spatrick // Convert the uses of Op into a vector of uses, associating global and local
33309467b48Spatrick // DFS info with each one.
convertUsesToDFSOrdered(Value * Op,SmallVectorImpl<ValueDFS> & DFSOrderedSet)334097a140dSpatrick void PredicateInfoBuilder::convertUsesToDFSOrdered(
33509467b48Spatrick Value *Op, SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
33609467b48Spatrick for (auto &U : Op->uses()) {
33709467b48Spatrick if (auto *I = dyn_cast<Instruction>(U.getUser())) {
33809467b48Spatrick ValueDFS VD;
33909467b48Spatrick // Put the phi node uses in the incoming block.
34009467b48Spatrick BasicBlock *IBlock;
34109467b48Spatrick if (auto *PN = dyn_cast<PHINode>(I)) {
34209467b48Spatrick IBlock = PN->getIncomingBlock(U);
34309467b48Spatrick // Make phi node users appear last in the incoming block
34409467b48Spatrick // they are from.
34509467b48Spatrick VD.LocalNum = LN_Last;
34609467b48Spatrick } else {
34709467b48Spatrick // If it's not a phi node use, it is somewhere in the middle of the
34809467b48Spatrick // block.
34909467b48Spatrick IBlock = I->getParent();
35009467b48Spatrick VD.LocalNum = LN_Middle;
35109467b48Spatrick }
35209467b48Spatrick DomTreeNode *DomNode = DT.getNode(IBlock);
35309467b48Spatrick // It's possible our use is in an unreachable block. Skip it if so.
35409467b48Spatrick if (!DomNode)
35509467b48Spatrick continue;
35609467b48Spatrick VD.DFSIn = DomNode->getDFSNumIn();
35709467b48Spatrick VD.DFSOut = DomNode->getDFSNumOut();
35809467b48Spatrick VD.U = &U;
35909467b48Spatrick DFSOrderedSet.push_back(VD);
36009467b48Spatrick }
36109467b48Spatrick }
36209467b48Spatrick }
36309467b48Spatrick
shouldRename(Value * V)36473471bf0Spatrick bool shouldRename(Value *V) {
36573471bf0Spatrick // Only want real values, not constants. Additionally, operands with one use
36673471bf0Spatrick // are only being used in the comparison, which means they will not be useful
36773471bf0Spatrick // for us to consider for predicateinfo.
36873471bf0Spatrick return (isa<Instruction>(V) || isa<Argument>(V)) && !V->hasOneUse();
36973471bf0Spatrick }
37073471bf0Spatrick
37109467b48Spatrick // Collect relevant operations from Comparison that we may want to insert copies
37209467b48Spatrick // for.
collectCmpOps(CmpInst * Comparison,SmallVectorImpl<Value * > & CmpOperands)37309467b48Spatrick void collectCmpOps(CmpInst *Comparison, SmallVectorImpl<Value *> &CmpOperands) {
37409467b48Spatrick auto *Op0 = Comparison->getOperand(0);
37509467b48Spatrick auto *Op1 = Comparison->getOperand(1);
37609467b48Spatrick if (Op0 == Op1)
37709467b48Spatrick return;
37873471bf0Spatrick
37909467b48Spatrick CmpOperands.push_back(Op0);
38009467b48Spatrick CmpOperands.push_back(Op1);
38109467b48Spatrick }
38209467b48Spatrick
38309467b48Spatrick // Add Op, PB to the list of value infos for Op, and mark Op to be renamed.
addInfoFor(SmallVectorImpl<Value * > & OpsToRename,Value * Op,PredicateBase * PB)384097a140dSpatrick void PredicateInfoBuilder::addInfoFor(SmallVectorImpl<Value *> &OpsToRename,
385097a140dSpatrick Value *Op, PredicateBase *PB) {
38609467b48Spatrick auto &OperandInfo = getOrCreateValueInfo(Op);
38709467b48Spatrick if (OperandInfo.Infos.empty())
38809467b48Spatrick OpsToRename.push_back(Op);
389097a140dSpatrick PI.AllInfos.push_back(PB);
39009467b48Spatrick OperandInfo.Infos.push_back(PB);
39109467b48Spatrick }
39209467b48Spatrick
39309467b48Spatrick // Process an assume instruction and place relevant operations we want to rename
39409467b48Spatrick // into OpsToRename.
processAssume(IntrinsicInst * II,BasicBlock * AssumeBB,SmallVectorImpl<Value * > & OpsToRename)395097a140dSpatrick void PredicateInfoBuilder::processAssume(
396097a140dSpatrick IntrinsicInst *II, BasicBlock *AssumeBB,
39709467b48Spatrick SmallVectorImpl<Value *> &OpsToRename) {
39873471bf0Spatrick SmallVector<Value *, 4> Worklist;
39973471bf0Spatrick SmallPtrSet<Value *, 4> Visited;
40073471bf0Spatrick Worklist.push_back(II->getOperand(0));
40173471bf0Spatrick while (!Worklist.empty()) {
40273471bf0Spatrick Value *Cond = Worklist.pop_back_val();
40373471bf0Spatrick if (!Visited.insert(Cond).second)
40473471bf0Spatrick continue;
40573471bf0Spatrick if (Visited.size() > MaxCondsPerBranch)
40673471bf0Spatrick break;
40709467b48Spatrick
40873471bf0Spatrick Value *Op0, *Op1;
40973471bf0Spatrick if (match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
41073471bf0Spatrick Worklist.push_back(Op1);
41173471bf0Spatrick Worklist.push_back(Op0);
41209467b48Spatrick }
41373471bf0Spatrick
41473471bf0Spatrick SmallVector<Value *, 4> Values;
41573471bf0Spatrick Values.push_back(Cond);
41673471bf0Spatrick if (auto *Cmp = dyn_cast<CmpInst>(Cond))
41773471bf0Spatrick collectCmpOps(Cmp, Values);
41873471bf0Spatrick
41973471bf0Spatrick for (Value *V : Values) {
42073471bf0Spatrick if (shouldRename(V)) {
42173471bf0Spatrick auto *PA = new PredicateAssume(V, II, Cond);
42273471bf0Spatrick addInfoFor(OpsToRename, V, PA);
42309467b48Spatrick }
42409467b48Spatrick }
42509467b48Spatrick }
42609467b48Spatrick }
42709467b48Spatrick
42809467b48Spatrick // Process a block terminating branch, and place relevant operations to be
42909467b48Spatrick // renamed into OpsToRename.
processBranch(BranchInst * BI,BasicBlock * BranchBB,SmallVectorImpl<Value * > & OpsToRename)430097a140dSpatrick void PredicateInfoBuilder::processBranch(
431097a140dSpatrick BranchInst *BI, BasicBlock *BranchBB,
43209467b48Spatrick SmallVectorImpl<Value *> &OpsToRename) {
43309467b48Spatrick BasicBlock *FirstBB = BI->getSuccessor(0);
43409467b48Spatrick BasicBlock *SecondBB = BI->getSuccessor(1);
43509467b48Spatrick
43673471bf0Spatrick for (BasicBlock *Succ : {FirstBB, SecondBB}) {
43773471bf0Spatrick bool TakenEdge = Succ == FirstBB;
43809467b48Spatrick // Don't try to insert on a self-edge. This is mainly because we will
43909467b48Spatrick // eliminate during renaming anyway.
44009467b48Spatrick if (Succ == BranchBB)
44109467b48Spatrick continue;
44273471bf0Spatrick
44373471bf0Spatrick SmallVector<Value *, 4> Worklist;
44473471bf0Spatrick SmallPtrSet<Value *, 4> Visited;
44573471bf0Spatrick Worklist.push_back(BI->getCondition());
44673471bf0Spatrick while (!Worklist.empty()) {
44773471bf0Spatrick Value *Cond = Worklist.pop_back_val();
44873471bf0Spatrick if (!Visited.insert(Cond).second)
44909467b48Spatrick continue;
45073471bf0Spatrick if (Visited.size() > MaxCondsPerBranch)
45173471bf0Spatrick break;
45273471bf0Spatrick
45373471bf0Spatrick Value *Op0, *Op1;
45473471bf0Spatrick if (TakenEdge ? match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))
45573471bf0Spatrick : match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
45673471bf0Spatrick Worklist.push_back(Op1);
45773471bf0Spatrick Worklist.push_back(Op0);
45873471bf0Spatrick }
45973471bf0Spatrick
46073471bf0Spatrick SmallVector<Value *, 4> Values;
46173471bf0Spatrick Values.push_back(Cond);
46273471bf0Spatrick if (auto *Cmp = dyn_cast<CmpInst>(Cond))
46373471bf0Spatrick collectCmpOps(Cmp, Values);
46473471bf0Spatrick
46573471bf0Spatrick for (Value *V : Values) {
46673471bf0Spatrick if (shouldRename(V)) {
46709467b48Spatrick PredicateBase *PB =
46873471bf0Spatrick new PredicateBranch(V, BranchBB, Succ, Cond, TakenEdge);
46973471bf0Spatrick addInfoFor(OpsToRename, V, PB);
47009467b48Spatrick if (!Succ->getSinglePredecessor())
47109467b48Spatrick EdgeUsesOnly.insert({BranchBB, Succ});
47209467b48Spatrick }
47309467b48Spatrick }
47409467b48Spatrick }
47509467b48Spatrick }
47609467b48Spatrick }
47709467b48Spatrick // Process a block terminating switch, and place relevant operations to be
47809467b48Spatrick // renamed into OpsToRename.
processSwitch(SwitchInst * SI,BasicBlock * BranchBB,SmallVectorImpl<Value * > & OpsToRename)479097a140dSpatrick void PredicateInfoBuilder::processSwitch(
480097a140dSpatrick SwitchInst *SI, BasicBlock *BranchBB,
48109467b48Spatrick SmallVectorImpl<Value *> &OpsToRename) {
48209467b48Spatrick Value *Op = SI->getCondition();
48309467b48Spatrick if ((!isa<Instruction>(Op) && !isa<Argument>(Op)) || Op->hasOneUse())
48409467b48Spatrick return;
48509467b48Spatrick
48609467b48Spatrick // Remember how many outgoing edges there are to every successor.
48709467b48Spatrick SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
48809467b48Spatrick for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
48909467b48Spatrick BasicBlock *TargetBlock = SI->getSuccessor(i);
49009467b48Spatrick ++SwitchEdges[TargetBlock];
49109467b48Spatrick }
49209467b48Spatrick
49309467b48Spatrick // Now propagate info for each case value
49409467b48Spatrick for (auto C : SI->cases()) {
49509467b48Spatrick BasicBlock *TargetBlock = C.getCaseSuccessor();
49609467b48Spatrick if (SwitchEdges.lookup(TargetBlock) == 1) {
49709467b48Spatrick PredicateSwitch *PS = new PredicateSwitch(
49809467b48Spatrick Op, SI->getParent(), TargetBlock, C.getCaseValue(), SI);
49909467b48Spatrick addInfoFor(OpsToRename, Op, PS);
50009467b48Spatrick if (!TargetBlock->getSinglePredecessor())
50109467b48Spatrick EdgeUsesOnly.insert({BranchBB, TargetBlock});
50209467b48Spatrick }
50309467b48Spatrick }
50409467b48Spatrick }
50509467b48Spatrick
50609467b48Spatrick // Build predicate info for our function
buildPredicateInfo()507097a140dSpatrick void PredicateInfoBuilder::buildPredicateInfo() {
50809467b48Spatrick DT.updateDFSNumbers();
50909467b48Spatrick // Collect operands to rename from all conditional branch terminators, as well
51009467b48Spatrick // as assume statements.
51109467b48Spatrick SmallVector<Value *, 8> OpsToRename;
512*d415bd75Srobert for (auto *DTN : depth_first(DT.getRootNode())) {
51309467b48Spatrick BasicBlock *BranchBB = DTN->getBlock();
51409467b48Spatrick if (auto *BI = dyn_cast<BranchInst>(BranchBB->getTerminator())) {
51509467b48Spatrick if (!BI->isConditional())
51609467b48Spatrick continue;
51709467b48Spatrick // Can't insert conditional information if they all go to the same place.
51809467b48Spatrick if (BI->getSuccessor(0) == BI->getSuccessor(1))
51909467b48Spatrick continue;
52009467b48Spatrick processBranch(BI, BranchBB, OpsToRename);
52109467b48Spatrick } else if (auto *SI = dyn_cast<SwitchInst>(BranchBB->getTerminator())) {
52209467b48Spatrick processSwitch(SI, BranchBB, OpsToRename);
52309467b48Spatrick }
52409467b48Spatrick }
52509467b48Spatrick for (auto &Assume : AC.assumptions()) {
52609467b48Spatrick if (auto *II = dyn_cast_or_null<IntrinsicInst>(Assume))
52709467b48Spatrick if (DT.isReachableFromEntry(II->getParent()))
52809467b48Spatrick processAssume(II, II->getParent(), OpsToRename);
52909467b48Spatrick }
53009467b48Spatrick // Now rename all our operations.
53109467b48Spatrick renameUses(OpsToRename);
53209467b48Spatrick }
53309467b48Spatrick
53409467b48Spatrick // Given the renaming stack, make all the operands currently on the stack real
53509467b48Spatrick // by inserting them into the IR. Return the last operation's value.
materializeStack(unsigned int & Counter,ValueDFSStack & RenameStack,Value * OrigOp)536097a140dSpatrick Value *PredicateInfoBuilder::materializeStack(unsigned int &Counter,
53709467b48Spatrick ValueDFSStack &RenameStack,
53809467b48Spatrick Value *OrigOp) {
53909467b48Spatrick // Find the first thing we have to materialize
54009467b48Spatrick auto RevIter = RenameStack.rbegin();
54109467b48Spatrick for (; RevIter != RenameStack.rend(); ++RevIter)
54209467b48Spatrick if (RevIter->Def)
54309467b48Spatrick break;
54409467b48Spatrick
54509467b48Spatrick size_t Start = RevIter - RenameStack.rbegin();
54609467b48Spatrick // The maximum number of things we should be trying to materialize at once
54709467b48Spatrick // right now is 4, depending on if we had an assume, a branch, and both used
54809467b48Spatrick // and of conditions.
54909467b48Spatrick for (auto RenameIter = RenameStack.end() - Start;
55009467b48Spatrick RenameIter != RenameStack.end(); ++RenameIter) {
55109467b48Spatrick auto *Op =
55209467b48Spatrick RenameIter == RenameStack.begin() ? OrigOp : (RenameIter - 1)->Def;
55309467b48Spatrick ValueDFS &Result = *RenameIter;
55409467b48Spatrick auto *ValInfo = Result.PInfo;
555097a140dSpatrick ValInfo->RenamedOp = (RenameStack.end() - Start) == RenameStack.begin()
556097a140dSpatrick ? OrigOp
557097a140dSpatrick : (RenameStack.end() - Start - 1)->Def;
55809467b48Spatrick // For edge predicates, we can just place the operand in the block before
55909467b48Spatrick // the terminator. For assume, we have to place it right before the assume
56009467b48Spatrick // to ensure we dominate all of our uses. Always insert right before the
56109467b48Spatrick // relevant instruction (terminator, assume), so that we insert in proper
56209467b48Spatrick // order in the case of multiple predicateinfo in the same block.
56373471bf0Spatrick // The number of named values is used to detect if a new declaration was
56473471bf0Spatrick // added. If so, that declaration is tracked so that it can be removed when
56573471bf0Spatrick // the analysis is done. The corner case were a new declaration results in
56673471bf0Spatrick // a name clash and the old name being renamed is not considered as that
56773471bf0Spatrick // represents an invalid module.
56809467b48Spatrick if (isa<PredicateWithEdge>(ValInfo)) {
56909467b48Spatrick IRBuilder<> B(getBranchTerminator(ValInfo));
57073471bf0Spatrick auto NumDecls = F.getParent()->getNumNamedValues();
57173471bf0Spatrick Function *IF = Intrinsic::getDeclaration(
57273471bf0Spatrick F.getParent(), Intrinsic::ssa_copy, Op->getType());
57373471bf0Spatrick if (NumDecls != F.getParent()->getNumNamedValues())
574097a140dSpatrick PI.CreatedDeclarations.insert(IF);
57509467b48Spatrick CallInst *PIC =
57609467b48Spatrick B.CreateCall(IF, Op, Op->getName() + "." + Twine(Counter++));
577097a140dSpatrick PI.PredicateMap.insert({PIC, ValInfo});
57809467b48Spatrick Result.Def = PIC;
57909467b48Spatrick } else {
58009467b48Spatrick auto *PAssume = dyn_cast<PredicateAssume>(ValInfo);
58109467b48Spatrick assert(PAssume &&
58209467b48Spatrick "Should not have gotten here without it being an assume");
583097a140dSpatrick // Insert the predicate directly after the assume. While it also holds
584097a140dSpatrick // directly before it, assume(i1 true) is not a useful fact.
585097a140dSpatrick IRBuilder<> B(PAssume->AssumeInst->getNextNode());
58673471bf0Spatrick auto NumDecls = F.getParent()->getNumNamedValues();
58773471bf0Spatrick Function *IF = Intrinsic::getDeclaration(
58873471bf0Spatrick F.getParent(), Intrinsic::ssa_copy, Op->getType());
58973471bf0Spatrick if (NumDecls != F.getParent()->getNumNamedValues())
590097a140dSpatrick PI.CreatedDeclarations.insert(IF);
59109467b48Spatrick CallInst *PIC = B.CreateCall(IF, Op);
592097a140dSpatrick PI.PredicateMap.insert({PIC, ValInfo});
59309467b48Spatrick Result.Def = PIC;
59409467b48Spatrick }
59509467b48Spatrick }
59609467b48Spatrick return RenameStack.back().Def;
59709467b48Spatrick }
59809467b48Spatrick
59909467b48Spatrick // Instead of the standard SSA renaming algorithm, which is O(Number of
60009467b48Spatrick // instructions), and walks the entire dominator tree, we walk only the defs +
60109467b48Spatrick // uses. The standard SSA renaming algorithm does not really rely on the
60209467b48Spatrick // dominator tree except to order the stack push/pops of the renaming stacks, so
60309467b48Spatrick // that defs end up getting pushed before hitting the correct uses. This does
60409467b48Spatrick // not require the dominator tree, only the *order* of the dominator tree. The
60509467b48Spatrick // complete and correct ordering of the defs and uses, in dominator tree is
60609467b48Spatrick // contained in the DFS numbering of the dominator tree. So we sort the defs and
60709467b48Spatrick // uses into the DFS ordering, and then just use the renaming stack as per
60809467b48Spatrick // normal, pushing when we hit a def (which is a predicateinfo instruction),
60909467b48Spatrick // popping when we are out of the dfs scope for that def, and replacing any uses
61009467b48Spatrick // with top of stack if it exists. In order to handle liveness without
61109467b48Spatrick // propagating liveness info, we don't actually insert the predicateinfo
61209467b48Spatrick // instruction def until we see a use that it would dominate. Once we see such
61309467b48Spatrick // a use, we materialize the predicateinfo instruction in the right place and
61409467b48Spatrick // use it.
61509467b48Spatrick //
61609467b48Spatrick // TODO: Use this algorithm to perform fast single-variable renaming in
61709467b48Spatrick // promotememtoreg and memoryssa.
renameUses(SmallVectorImpl<Value * > & OpsToRename)618097a140dSpatrick void PredicateInfoBuilder::renameUses(SmallVectorImpl<Value *> &OpsToRename) {
619097a140dSpatrick ValueDFS_Compare Compare(DT);
62009467b48Spatrick // Compute liveness, and rename in O(uses) per Op.
62109467b48Spatrick for (auto *Op : OpsToRename) {
62209467b48Spatrick LLVM_DEBUG(dbgs() << "Visiting " << *Op << "\n");
62309467b48Spatrick unsigned Counter = 0;
62409467b48Spatrick SmallVector<ValueDFS, 16> OrderedUses;
62509467b48Spatrick const auto &ValueInfo = getValueInfo(Op);
62609467b48Spatrick // Insert the possible copies into the def/use list.
62709467b48Spatrick // They will become real copies if we find a real use for them, and never
62809467b48Spatrick // created otherwise.
629*d415bd75Srobert for (const auto &PossibleCopy : ValueInfo.Infos) {
63009467b48Spatrick ValueDFS VD;
63109467b48Spatrick // Determine where we are going to place the copy by the copy type.
63209467b48Spatrick // The predicate info for branches always come first, they will get
63309467b48Spatrick // materialized in the split block at the top of the block.
63409467b48Spatrick // The predicate info for assumes will be somewhere in the middle,
63509467b48Spatrick // it will get materialized in front of the assume.
63609467b48Spatrick if (const auto *PAssume = dyn_cast<PredicateAssume>(PossibleCopy)) {
63709467b48Spatrick VD.LocalNum = LN_Middle;
63809467b48Spatrick DomTreeNode *DomNode = DT.getNode(PAssume->AssumeInst->getParent());
63909467b48Spatrick if (!DomNode)
64009467b48Spatrick continue;
64109467b48Spatrick VD.DFSIn = DomNode->getDFSNumIn();
64209467b48Spatrick VD.DFSOut = DomNode->getDFSNumOut();
64309467b48Spatrick VD.PInfo = PossibleCopy;
64409467b48Spatrick OrderedUses.push_back(VD);
64509467b48Spatrick } else if (isa<PredicateWithEdge>(PossibleCopy)) {
64609467b48Spatrick // If we can only do phi uses, we treat it like it's in the branch
64709467b48Spatrick // block, and handle it specially. We know that it goes last, and only
64809467b48Spatrick // dominate phi uses.
64909467b48Spatrick auto BlockEdge = getBlockEdge(PossibleCopy);
65009467b48Spatrick if (EdgeUsesOnly.count(BlockEdge)) {
65109467b48Spatrick VD.LocalNum = LN_Last;
65209467b48Spatrick auto *DomNode = DT.getNode(BlockEdge.first);
65309467b48Spatrick if (DomNode) {
65409467b48Spatrick VD.DFSIn = DomNode->getDFSNumIn();
65509467b48Spatrick VD.DFSOut = DomNode->getDFSNumOut();
65609467b48Spatrick VD.PInfo = PossibleCopy;
65709467b48Spatrick VD.EdgeOnly = true;
65809467b48Spatrick OrderedUses.push_back(VD);
65909467b48Spatrick }
66009467b48Spatrick } else {
66109467b48Spatrick // Otherwise, we are in the split block (even though we perform
66209467b48Spatrick // insertion in the branch block).
66309467b48Spatrick // Insert a possible copy at the split block and before the branch.
66409467b48Spatrick VD.LocalNum = LN_First;
66509467b48Spatrick auto *DomNode = DT.getNode(BlockEdge.second);
66609467b48Spatrick if (DomNode) {
66709467b48Spatrick VD.DFSIn = DomNode->getDFSNumIn();
66809467b48Spatrick VD.DFSOut = DomNode->getDFSNumOut();
66909467b48Spatrick VD.PInfo = PossibleCopy;
67009467b48Spatrick OrderedUses.push_back(VD);
67109467b48Spatrick }
67209467b48Spatrick }
67309467b48Spatrick }
67409467b48Spatrick }
67509467b48Spatrick
67609467b48Spatrick convertUsesToDFSOrdered(Op, OrderedUses);
67709467b48Spatrick // Here we require a stable sort because we do not bother to try to
67809467b48Spatrick // assign an order to the operands the uses represent. Thus, two
67909467b48Spatrick // uses in the same instruction do not have a strict sort order
68009467b48Spatrick // currently and will be considered equal. We could get rid of the
68109467b48Spatrick // stable sort by creating one if we wanted.
68209467b48Spatrick llvm::stable_sort(OrderedUses, Compare);
68309467b48Spatrick SmallVector<ValueDFS, 8> RenameStack;
68409467b48Spatrick // For each use, sorted into dfs order, push values and replaces uses with
68509467b48Spatrick // top of stack, which will represent the reaching def.
68609467b48Spatrick for (auto &VD : OrderedUses) {
68709467b48Spatrick // We currently do not materialize copy over copy, but we should decide if
68809467b48Spatrick // we want to.
68909467b48Spatrick bool PossibleCopy = VD.PInfo != nullptr;
69009467b48Spatrick if (RenameStack.empty()) {
69109467b48Spatrick LLVM_DEBUG(dbgs() << "Rename Stack is empty\n");
69209467b48Spatrick } else {
69309467b48Spatrick LLVM_DEBUG(dbgs() << "Rename Stack Top DFS numbers are ("
69409467b48Spatrick << RenameStack.back().DFSIn << ","
69509467b48Spatrick << RenameStack.back().DFSOut << ")\n");
69609467b48Spatrick }
69709467b48Spatrick
69809467b48Spatrick LLVM_DEBUG(dbgs() << "Current DFS numbers are (" << VD.DFSIn << ","
69909467b48Spatrick << VD.DFSOut << ")\n");
70009467b48Spatrick
70109467b48Spatrick bool ShouldPush = (VD.Def || PossibleCopy);
70209467b48Spatrick bool OutOfScope = !stackIsInScope(RenameStack, VD);
70309467b48Spatrick if (OutOfScope || ShouldPush) {
70409467b48Spatrick // Sync to our current scope.
70509467b48Spatrick popStackUntilDFSScope(RenameStack, VD);
70609467b48Spatrick if (ShouldPush) {
70709467b48Spatrick RenameStack.push_back(VD);
70809467b48Spatrick }
70909467b48Spatrick }
71009467b48Spatrick // If we get to this point, and the stack is empty we must have a use
71109467b48Spatrick // with no renaming needed, just skip it.
71209467b48Spatrick if (RenameStack.empty())
71309467b48Spatrick continue;
71409467b48Spatrick // Skip values, only want to rename the uses
71509467b48Spatrick if (VD.Def || PossibleCopy)
71609467b48Spatrick continue;
71709467b48Spatrick if (!DebugCounter::shouldExecute(RenameCounter)) {
71809467b48Spatrick LLVM_DEBUG(dbgs() << "Skipping execution due to debug counter\n");
71909467b48Spatrick continue;
72009467b48Spatrick }
72109467b48Spatrick ValueDFS &Result = RenameStack.back();
72209467b48Spatrick
72309467b48Spatrick // If the possible copy dominates something, materialize our stack up to
72409467b48Spatrick // this point. This ensures every comparison that affects our operation
72509467b48Spatrick // ends up with predicateinfo.
72609467b48Spatrick if (!Result.Def)
72709467b48Spatrick Result.Def = materializeStack(Counter, RenameStack, Op);
72809467b48Spatrick
72909467b48Spatrick LLVM_DEBUG(dbgs() << "Found replacement " << *Result.Def << " for "
73009467b48Spatrick << *VD.U->get() << " in " << *(VD.U->getUser())
73109467b48Spatrick << "\n");
73209467b48Spatrick assert(DT.dominates(cast<Instruction>(Result.Def), *VD.U) &&
73309467b48Spatrick "Predicateinfo def should have dominated this use");
73409467b48Spatrick VD.U->set(Result.Def);
73509467b48Spatrick }
73609467b48Spatrick }
73709467b48Spatrick }
73809467b48Spatrick
739097a140dSpatrick PredicateInfoBuilder::ValueInfo &
getOrCreateValueInfo(Value * Operand)740097a140dSpatrick PredicateInfoBuilder::getOrCreateValueInfo(Value *Operand) {
74109467b48Spatrick auto OIN = ValueInfoNums.find(Operand);
74209467b48Spatrick if (OIN == ValueInfoNums.end()) {
74309467b48Spatrick // This will grow it
74409467b48Spatrick ValueInfos.resize(ValueInfos.size() + 1);
74509467b48Spatrick // This will use the new size and give us a 0 based number of the info
74609467b48Spatrick auto InsertResult = ValueInfoNums.insert({Operand, ValueInfos.size() - 1});
74709467b48Spatrick assert(InsertResult.second && "Value info number already existed?");
74809467b48Spatrick return ValueInfos[InsertResult.first->second];
74909467b48Spatrick }
75009467b48Spatrick return ValueInfos[OIN->second];
75109467b48Spatrick }
75209467b48Spatrick
753097a140dSpatrick const PredicateInfoBuilder::ValueInfo &
getValueInfo(Value * Operand) const754097a140dSpatrick PredicateInfoBuilder::getValueInfo(Value *Operand) const {
75509467b48Spatrick auto OINI = ValueInfoNums.lookup(Operand);
75609467b48Spatrick assert(OINI != 0 && "Operand was not really in the Value Info Numbers");
75709467b48Spatrick assert(OINI < ValueInfos.size() &&
75809467b48Spatrick "Value Info Number greater than size of Value Info Table");
75909467b48Spatrick return ValueInfos[OINI];
76009467b48Spatrick }
76109467b48Spatrick
PredicateInfo(Function & F,DominatorTree & DT,AssumptionCache & AC)76209467b48Spatrick PredicateInfo::PredicateInfo(Function &F, DominatorTree &DT,
76309467b48Spatrick AssumptionCache &AC)
764097a140dSpatrick : F(F) {
765097a140dSpatrick PredicateInfoBuilder Builder(*this, F, DT, AC);
766097a140dSpatrick Builder.buildPredicateInfo();
76709467b48Spatrick }
76809467b48Spatrick
76909467b48Spatrick // Remove all declarations we created . The PredicateInfo consumers are
77009467b48Spatrick // responsible for remove the ssa_copy calls created.
~PredicateInfo()77109467b48Spatrick PredicateInfo::~PredicateInfo() {
77209467b48Spatrick // Collect function pointers in set first, as SmallSet uses a SmallVector
77309467b48Spatrick // internally and we have to remove the asserting value handles first.
77409467b48Spatrick SmallPtrSet<Function *, 20> FunctionPtrs;
775*d415bd75Srobert for (const auto &F : CreatedDeclarations)
77609467b48Spatrick FunctionPtrs.insert(&*F);
77709467b48Spatrick CreatedDeclarations.clear();
77809467b48Spatrick
77909467b48Spatrick for (Function *F : FunctionPtrs) {
78009467b48Spatrick assert(F->user_begin() == F->user_end() &&
78109467b48Spatrick "PredicateInfo consumer did not remove all SSA copies.");
78209467b48Spatrick F->eraseFromParent();
78309467b48Spatrick }
78409467b48Spatrick }
78509467b48Spatrick
getConstraint() const786*d415bd75Srobert std::optional<PredicateConstraint> PredicateBase::getConstraint() const {
78773471bf0Spatrick switch (Type) {
78873471bf0Spatrick case PT_Assume:
78973471bf0Spatrick case PT_Branch: {
79073471bf0Spatrick bool TrueEdge = true;
79173471bf0Spatrick if (auto *PBranch = dyn_cast<PredicateBranch>(this))
79273471bf0Spatrick TrueEdge = PBranch->TrueEdge;
79373471bf0Spatrick
79473471bf0Spatrick if (Condition == RenamedOp) {
79573471bf0Spatrick return {{CmpInst::ICMP_EQ,
79673471bf0Spatrick TrueEdge ? ConstantInt::getTrue(Condition->getType())
79773471bf0Spatrick : ConstantInt::getFalse(Condition->getType())}};
79873471bf0Spatrick }
79973471bf0Spatrick
80073471bf0Spatrick CmpInst *Cmp = dyn_cast<CmpInst>(Condition);
80173471bf0Spatrick if (!Cmp) {
80273471bf0Spatrick // TODO: Make this an assertion once RenamedOp is fully accurate.
803*d415bd75Srobert return std::nullopt;
80473471bf0Spatrick }
80573471bf0Spatrick
80673471bf0Spatrick CmpInst::Predicate Pred;
80773471bf0Spatrick Value *OtherOp;
80873471bf0Spatrick if (Cmp->getOperand(0) == RenamedOp) {
80973471bf0Spatrick Pred = Cmp->getPredicate();
81073471bf0Spatrick OtherOp = Cmp->getOperand(1);
81173471bf0Spatrick } else if (Cmp->getOperand(1) == RenamedOp) {
81273471bf0Spatrick Pred = Cmp->getSwappedPredicate();
81373471bf0Spatrick OtherOp = Cmp->getOperand(0);
81473471bf0Spatrick } else {
81573471bf0Spatrick // TODO: Make this an assertion once RenamedOp is fully accurate.
816*d415bd75Srobert return std::nullopt;
81773471bf0Spatrick }
81873471bf0Spatrick
81973471bf0Spatrick // Invert predicate along false edge.
82073471bf0Spatrick if (!TrueEdge)
82173471bf0Spatrick Pred = CmpInst::getInversePredicate(Pred);
82273471bf0Spatrick
82373471bf0Spatrick return {{Pred, OtherOp}};
82473471bf0Spatrick }
82573471bf0Spatrick case PT_Switch:
82673471bf0Spatrick if (Condition != RenamedOp) {
82773471bf0Spatrick // TODO: Make this an assertion once RenamedOp is fully accurate.
828*d415bd75Srobert return std::nullopt;
82973471bf0Spatrick }
83073471bf0Spatrick
83173471bf0Spatrick return {{CmpInst::ICMP_EQ, cast<PredicateSwitch>(this)->CaseValue}};
83273471bf0Spatrick }
83373471bf0Spatrick llvm_unreachable("Unknown predicate type");
83473471bf0Spatrick }
83573471bf0Spatrick
verifyPredicateInfo() const83609467b48Spatrick void PredicateInfo::verifyPredicateInfo() const {}
83709467b48Spatrick
83809467b48Spatrick char PredicateInfoPrinterLegacyPass::ID = 0;
83909467b48Spatrick
PredicateInfoPrinterLegacyPass()84009467b48Spatrick PredicateInfoPrinterLegacyPass::PredicateInfoPrinterLegacyPass()
84109467b48Spatrick : FunctionPass(ID) {
84209467b48Spatrick initializePredicateInfoPrinterLegacyPassPass(
84309467b48Spatrick *PassRegistry::getPassRegistry());
84409467b48Spatrick }
84509467b48Spatrick
getAnalysisUsage(AnalysisUsage & AU) const84609467b48Spatrick void PredicateInfoPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
84709467b48Spatrick AU.setPreservesAll();
84809467b48Spatrick AU.addRequiredTransitive<DominatorTreeWrapperPass>();
84909467b48Spatrick AU.addRequired<AssumptionCacheTracker>();
85009467b48Spatrick }
85109467b48Spatrick
85209467b48Spatrick // Replace ssa_copy calls created by PredicateInfo with their operand.
replaceCreatedSSACopys(PredicateInfo & PredInfo,Function & F)85309467b48Spatrick static void replaceCreatedSSACopys(PredicateInfo &PredInfo, Function &F) {
85473471bf0Spatrick for (Instruction &Inst : llvm::make_early_inc_range(instructions(F))) {
85573471bf0Spatrick const auto *PI = PredInfo.getPredicateInfoFor(&Inst);
85673471bf0Spatrick auto *II = dyn_cast<IntrinsicInst>(&Inst);
85709467b48Spatrick if (!PI || !II || II->getIntrinsicID() != Intrinsic::ssa_copy)
85809467b48Spatrick continue;
85909467b48Spatrick
86073471bf0Spatrick Inst.replaceAllUsesWith(II->getOperand(0));
86173471bf0Spatrick Inst.eraseFromParent();
86209467b48Spatrick }
86309467b48Spatrick }
86409467b48Spatrick
runOnFunction(Function & F)86509467b48Spatrick bool PredicateInfoPrinterLegacyPass::runOnFunction(Function &F) {
86609467b48Spatrick auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
86709467b48Spatrick auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
86809467b48Spatrick auto PredInfo = std::make_unique<PredicateInfo>(F, DT, AC);
86909467b48Spatrick PredInfo->print(dbgs());
87009467b48Spatrick if (VerifyPredicateInfo)
87109467b48Spatrick PredInfo->verifyPredicateInfo();
87209467b48Spatrick
87309467b48Spatrick replaceCreatedSSACopys(*PredInfo, F);
87409467b48Spatrick return false;
87509467b48Spatrick }
87609467b48Spatrick
run(Function & F,FunctionAnalysisManager & AM)87709467b48Spatrick PreservedAnalyses PredicateInfoPrinterPass::run(Function &F,
87809467b48Spatrick FunctionAnalysisManager &AM) {
87909467b48Spatrick auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
88009467b48Spatrick auto &AC = AM.getResult<AssumptionAnalysis>(F);
88109467b48Spatrick OS << "PredicateInfo for function: " << F.getName() << "\n";
88209467b48Spatrick auto PredInfo = std::make_unique<PredicateInfo>(F, DT, AC);
88309467b48Spatrick PredInfo->print(OS);
88409467b48Spatrick
88509467b48Spatrick replaceCreatedSSACopys(*PredInfo, F);
88609467b48Spatrick return PreservedAnalyses::all();
88709467b48Spatrick }
88809467b48Spatrick
88909467b48Spatrick /// An assembly annotator class to print PredicateInfo information in
89009467b48Spatrick /// comments.
89109467b48Spatrick class PredicateInfoAnnotatedWriter : public AssemblyAnnotationWriter {
89209467b48Spatrick friend class PredicateInfo;
89309467b48Spatrick const PredicateInfo *PredInfo;
89409467b48Spatrick
89509467b48Spatrick public:
PredicateInfoAnnotatedWriter(const PredicateInfo * M)89609467b48Spatrick PredicateInfoAnnotatedWriter(const PredicateInfo *M) : PredInfo(M) {}
89709467b48Spatrick
emitBasicBlockStartAnnot(const BasicBlock * BB,formatted_raw_ostream & OS)898097a140dSpatrick void emitBasicBlockStartAnnot(const BasicBlock *BB,
899097a140dSpatrick formatted_raw_ostream &OS) override {}
90009467b48Spatrick
emitInstructionAnnot(const Instruction * I,formatted_raw_ostream & OS)901097a140dSpatrick void emitInstructionAnnot(const Instruction *I,
902097a140dSpatrick formatted_raw_ostream &OS) override {
90309467b48Spatrick if (const auto *PI = PredInfo->getPredicateInfoFor(I)) {
90409467b48Spatrick OS << "; Has predicate info\n";
90509467b48Spatrick if (const auto *PB = dyn_cast<PredicateBranch>(PI)) {
90609467b48Spatrick OS << "; branch predicate info { TrueEdge: " << PB->TrueEdge
90709467b48Spatrick << " Comparison:" << *PB->Condition << " Edge: [";
90809467b48Spatrick PB->From->printAsOperand(OS);
90909467b48Spatrick OS << ",";
91009467b48Spatrick PB->To->printAsOperand(OS);
911097a140dSpatrick OS << "]";
91209467b48Spatrick } else if (const auto *PS = dyn_cast<PredicateSwitch>(PI)) {
91309467b48Spatrick OS << "; switch predicate info { CaseValue: " << *PS->CaseValue
91409467b48Spatrick << " Switch:" << *PS->Switch << " Edge: [";
91509467b48Spatrick PS->From->printAsOperand(OS);
91609467b48Spatrick OS << ",";
91709467b48Spatrick PS->To->printAsOperand(OS);
918097a140dSpatrick OS << "]";
91909467b48Spatrick } else if (const auto *PA = dyn_cast<PredicateAssume>(PI)) {
92009467b48Spatrick OS << "; assume predicate info {"
921097a140dSpatrick << " Comparison:" << *PA->Condition;
92209467b48Spatrick }
923097a140dSpatrick OS << ", RenamedOp: ";
924097a140dSpatrick PI->RenamedOp->printAsOperand(OS, false);
925097a140dSpatrick OS << " }\n";
92609467b48Spatrick }
92709467b48Spatrick }
92809467b48Spatrick };
92909467b48Spatrick
print(raw_ostream & OS) const93009467b48Spatrick void PredicateInfo::print(raw_ostream &OS) const {
93109467b48Spatrick PredicateInfoAnnotatedWriter Writer(this);
93209467b48Spatrick F.print(OS, &Writer);
93309467b48Spatrick }
93409467b48Spatrick
dump() const93509467b48Spatrick void PredicateInfo::dump() const {
93609467b48Spatrick PredicateInfoAnnotatedWriter Writer(this);
93709467b48Spatrick F.print(dbgs(), &Writer);
93809467b48Spatrick }
93909467b48Spatrick
run(Function & F,FunctionAnalysisManager & AM)94009467b48Spatrick PreservedAnalyses PredicateInfoVerifierPass::run(Function &F,
94109467b48Spatrick FunctionAnalysisManager &AM) {
94209467b48Spatrick auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
94309467b48Spatrick auto &AC = AM.getResult<AssumptionAnalysis>(F);
94409467b48Spatrick std::make_unique<PredicateInfo>(F, DT, AC)->verifyPredicateInfo();
94509467b48Spatrick
94609467b48Spatrick return PreservedAnalyses::all();
94709467b48Spatrick }
94809467b48Spatrick }
949