38 #define DEBUG_TYPE "predicateinfo"
40 using namespace PatternMatch;
41 using namespace llvm::PredicateInfoClasses;
44 "PredicateInfo Printer",
false,
false)
54 "Controls which variables are renamed with predicateinfo")
58 assert(isa<PredicateWithEdge>(PB) &&
59 "Only branches and switches should have PHIOnly defs that "
60 "require branch blocks.");
61 return cast<PredicateWithEdge>(PB)->From;
67 assert(isa<PredicateWithEdge>(PB) &&
68 "Not a predicate info type we know how to get a terminator from.");
69 return cast<PredicateWithEdge>(PB)->From->getTerminator();
74 const std::pair<BasicBlock *, BasicBlock *>
76 assert(isa<PredicateWithEdge>(PB) &&
77 "Not a predicate info type we know how to get an edge from.");
78 const auto *PEdge = cast<PredicateWithEdge>(PB);
79 return std::make_pair(PEdge->From, PEdge->To);
84 namespace PredicateInfoClasses {
106 bool EdgeOnly =
false;
112 auto *ArgA = dyn_cast_or_null<Argument>(
A);
113 auto *ArgB = dyn_cast_or_null<Argument>(
B);
119 return ArgA->getArgNo() < ArgB->getArgNo();
120 return OI.
dominates(cast<Instruction>(A), cast<Instruction>(B));
145 return comparePHIRelated(A, B);
150 return localComesBefore(A, B);
154 const std::pair<BasicBlock *, BasicBlock *>
156 if (!VD.
Def && VD.
U) {
157 auto *PHI = cast<PHINode>(VD.
U->getUser());
158 return std::make_pair(PHI->getIncomingBlock(*VD.
U), PHI->getParent());
161 return ::getBlockEdge(VD.
PInfo);
166 auto &ABlockEdge = getBlockEdge(A);
167 auto &BBlockEdge = getBlockEdge(B);
169 return std::tie(ABlockEdge, A.
Def, A.
U) < std::tie(BBlockEdge, B.
Def, B.
U);
184 "No def, no use, and no predicateinfo should not occur");
186 "Middle of block should only occur for assumes");
187 return cast<PredicateAssume>(VD.
PInfo)->AssumeInst;
196 return cast<Instruction>(
Def);
197 return cast<Instruction>(U->getUser());
203 auto *ADef = getMiddleDef(A);
204 auto *BDef = getMiddleDef(B);
209 auto *ArgA = dyn_cast_or_null<Argument>(ADef);
210 auto *ArgB = dyn_cast_or_null<Argument>(BDef);
215 auto *AInst = getDefOrUser(ADef, A.
U);
216 auto *BInst = getDefOrUser(BDef, B.
U);
223 bool PredicateInfo::stackIsInScope(
const ValueDFSStack &Stack,
232 if (Stack.back().EdgeOnly) {
239 BasicBlock *EdgePred = PHI->getIncomingBlock(*VDUse.
U);
240 if (EdgePred != getBranchBlock(Stack.back().PInfo))
244 return DT.dominates(getBlockEdge(Stack.back().PInfo), *VDUse.
U);
247 return (VDUse.
DFSIn >= Stack.back().DFSIn &&
248 VDUse.
DFSOut <= Stack.back().DFSOut);
251 void PredicateInfo::popStackUntilDFSScope(ValueDFSStack &Stack,
253 while (!Stack.empty() && !stackIsInScope(Stack, VD))
259 void PredicateInfo::convertUsesToDFSOrdered(
261 for (
auto &U : Op->
uses()) {
262 if (
auto *
I = dyn_cast<Instruction>(U.getUser())) {
266 if (
auto *PN = dyn_cast<PHINode>(
I)) {
267 IBlock = PN->getIncomingBlock(U);
274 IBlock =
I->getParent();
301 if ((isa<Instruction>(Op0) || isa<Argument>(Op0)) && !Op0->hasOneUse())
303 if ((isa<Instruction>(Op1) || isa<Argument>(Op1)) && !Op1->hasOneUse())
311 auto &OperandInfo = getOrCreateValueInfo(Op);
312 AllInfos.push_back(PB);
313 OperandInfo.Infos.push_back(PB);
328 ConditionsToProcess.
push_back(cast<BinaryOperator>(Operand)->getOperand(0));
329 ConditionsToProcess.
push_back(cast<BinaryOperator>(Operand)->getOperand(1));
331 }
else if (isa<CmpInst>(Operand)) {
335 for (
auto Cond : ConditionsToProcess) {
336 if (
auto *Cmp = dyn_cast<CmpInst>(Cond)) {
339 for (
auto *Op : CmpOperands) {
341 addInfoFor(OpsToRename, Op, PA);
344 }
else if (
auto *BinOp = dyn_cast<BinaryOperator>(Cond)) {
346 assert(BinOp->getOpcode() == Instruction::And &&
347 "Should have been an AND");
349 addInfoFor(OpsToRename, BinOp, PA);
367 auto InsertHelper = [&](
Value *
Op,
bool isAnd,
bool isOr,
Value *Cond) {
368 for (
auto *Succ : SuccsToProcess) {
371 if (Succ == BranchBB)
373 bool TakenEdge = (Succ == FirstBB);
376 if ((isAnd && !TakenEdge) || (isOr && TakenEdge))
380 addInfoFor(OpsToRename, Op, PB);
381 if (!Succ->getSinglePredecessor())
382 EdgeUsesOnly.insert({BranchBB, Succ});
396 if (BinOp->getOpcode() == Instruction::And)
398 else if (BinOp->getOpcode() == Instruction::Or)
400 ConditionsToProcess.
push_back(BinOp->getOperand(0));
401 ConditionsToProcess.
push_back(BinOp->getOperand(1));
406 for (
auto Cond : ConditionsToProcess) {
407 if (
auto *Cmp = dyn_cast<CmpInst>(Cond)) {
410 for (
auto *Op : CmpOperands)
411 InsertHelper(Op, isAnd, isOr, Cmp);
412 }
else if (
auto *BinOp = dyn_cast<BinaryOperator>(Cond)) {
414 assert((BinOp->getOpcode() == Instruction::And ||
415 BinOp->getOpcode() == Instruction::Or) &&
416 "Should have been an AND or an OR");
419 InsertHelper(BinOp,
false,
false, BinOp);
431 if ((!isa<Instruction>(Op) && !isa<Argument>(Op)) || Op->
hasOneUse())
438 ++SwitchEdges[TargetBlock];
442 for (
auto C : SI->
cases()) {
444 if (SwitchEdges.
lookup(TargetBlock) == 1) {
446 Op, SI->
getParent(), TargetBlock,
C.getCaseValue(), SI);
447 addInfoFor(OpsToRename, Op, PS);
449 EdgeUsesOnly.insert({BranchBB, TargetBlock});
455 void PredicateInfo::buildPredicateInfo() {
456 DT.updateDFSNumbers();
462 if (
auto *BI = dyn_cast<BranchInst>(BranchBB->
getTerminator())) {
468 processBranch(BI, BranchBB, OpsToRename);
469 }
else if (
auto *SI = dyn_cast<SwitchInst>(BranchBB->
getTerminator())) {
473 for (
auto &Assume : AC.assumptions()) {
474 if (
auto *II = dyn_cast_or_null<IntrinsicInst>(Assume))
475 processAssume(II, II->
getParent(), OpsToRename);
478 renameUses(OpsToRename);
483 Value *PredicateInfo::materializeStack(
unsigned int &
Counter,
484 ValueDFSStack &RenameStack,
487 auto RevIter = RenameStack.rbegin();
488 for (; RevIter != RenameStack.rend(); ++RevIter)
492 size_t Start = RevIter - RenameStack.rbegin();
496 for (
auto RenameIter = RenameStack.end() - Start;
497 RenameIter != RenameStack.end(); ++RenameIter) {
499 RenameIter == RenameStack.begin() ? OrigOp : (RenameIter - 1)->
Def;
501 auto *ValInfo = Result.
PInfo;
507 if (isa<PredicateWithEdge>(ValInfo)) {
510 F.getParent(), Intrinsic::ssa_copy, Op->
getType());
512 B.CreateCall(IF, Op, Op->
getName() +
"." +
Twine(Counter++));
513 PredicateMap.insert({PIC, ValInfo});
518 "Should not have gotten here without it being an assume");
521 F.getParent(), Intrinsic::ssa_copy, Op->
getType());
523 PredicateMap.insert({PIC, ValInfo});
527 return RenameStack.back().Def;
558 for (
auto *Op : OpsToRename) {
559 unsigned Counter = 0;
561 const auto &
ValueInfo = getValueInfo(Op);
565 for (
auto &PossibleCopy :
ValueInfo.Infos) {
572 if (
const auto *PAssume = dyn_cast<PredicateAssume>(PossibleCopy)) {
574 DomTreeNode *DomNode = DT.getNode(PAssume->AssumeInst->getParent());
579 VD.
PInfo = PossibleCopy;
581 }
else if (isa<PredicateWithEdge>(PossibleCopy)) {
585 auto BlockEdge = getBlockEdge(PossibleCopy);
586 if (EdgeUsesOnly.count(BlockEdge)) {
588 auto *DomNode = DT.getNode(BlockEdge.first);
592 VD.
PInfo = PossibleCopy;
601 auto *DomNode = DT.getNode(BlockEdge.second);
605 VD.
PInfo = PossibleCopy;
612 convertUsesToDFSOrdered(Op, OrderedUses);
617 for (
auto &VD : OrderedUses) {
620 bool PossibleCopy = VD.
PInfo !=
nullptr;
621 if (RenameStack.empty()) {
622 DEBUG(
dbgs() <<
"Rename Stack is empty\n");
624 DEBUG(
dbgs() <<
"Rename Stack Top DFS numbers are ("
625 << RenameStack.back().DFSIn <<
","
626 << RenameStack.back().DFSOut <<
")\n");
632 bool ShouldPush = (VD.
Def || PossibleCopy);
633 bool OutOfScope = !stackIsInScope(RenameStack, VD);
634 if (OutOfScope || ShouldPush) {
636 popStackUntilDFSScope(RenameStack, VD);
638 RenameStack.push_back(VD);
643 if (RenameStack.empty())
646 if (VD.
Def || PossibleCopy)
649 DEBUG(
dbgs() <<
"Skipping execution due to debug counter\n");
652 ValueDFS &Result = RenameStack.back();
658 Result.
Def = materializeStack(Counter, RenameStack, Op);
660 DEBUG(
dbgs() <<
"Found replacement " << *Result.
Def <<
" for "
661 << *VD.
U->get() <<
" in " << *(VD.
U->getUser()) <<
"\n");
662 assert(DT.dominates(cast<Instruction>(Result.
Def), *VD.
U) &&
663 "Predicateinfo def should have dominated this use");
664 VD.
U->set(Result.
Def);
669 PredicateInfo::ValueInfo &PredicateInfo::getOrCreateValueInfo(
Value *Operand) {
670 auto OIN = ValueInfoNums.find(Operand);
671 if (OIN == ValueInfoNums.end()) {
673 ValueInfos.resize(ValueInfos.size() + 1);
675 auto InsertResult = ValueInfoNums.insert({Operand, ValueInfos.size() - 1});
676 assert(InsertResult.second &&
"Value info number already existed?");
677 return ValueInfos[InsertResult.first->second];
679 return ValueInfos[OIN->second];
682 const PredicateInfo::ValueInfo &
683 PredicateInfo::getValueInfo(
Value *Operand)
const {
684 auto OINI = ValueInfoNums.lookup(Operand);
685 assert(OINI != 0 &&
"Operand was not really in the Value Info Numbers");
686 assert(OINI < ValueInfos.size() &&
687 "Value Info Number greater than size of Value Info Table");
688 return ValueInfos[OINI];
693 : F(F), DT(DT), AC(AC), OI(&DT) {
696 buildPredicateInfo();
718 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
719 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
720 auto PredInfo = make_unique<PredicateInfo>(
F, DT, AC);
721 PredInfo->print(
dbgs());
723 PredInfo->verifyPredicateInfo();
731 OS <<
"PredicateInfo for function: " << F.
getName() <<
"\n";
732 make_unique<PredicateInfo>(
F, DT, AC)->print(OS);
752 OS <<
"; Has predicate info\n";
753 if (
const auto *PB = dyn_cast<PredicateBranch>(PI)) {
754 OS <<
"; branch predicate info { TrueEdge: " << PB->TrueEdge
755 <<
" Comparison:" << *PB->Condition <<
" Edge: [";
756 PB->From->printAsOperand(OS);
758 PB->To->printAsOperand(OS);
760 }
else if (
const auto *
PS = dyn_cast<PredicateSwitch>(PI)) {
761 OS <<
"; switch predicate info { CaseValue: " << *
PS->CaseValue
762 <<
" Switch:" << *
PS->Switch <<
" Edge: [";
763 PS->From->printAsOperand(OS);
765 PS->To->printAsOperand(OS);
767 }
else if (
const auto *PA = dyn_cast<PredicateAssume>(PI)) {
768 OS <<
"; assume predicate info {"
769 <<
" Comparison:" << *PA->Condition <<
" }\n";
777 F.print(OS, &Writer);
782 F.print(
dbgs(), &Writer);
789 make_unique<PredicateInfo>(
F, DT, AC)->verifyPredicateInfo();
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
void push_back(const T &Elt)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Safe Stack instrumentation pass
This class is the base class for the comparison instructions.
iterator_range< use_iterator > uses()
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
PredicateInfo(Function &, DominatorTree &, AssumptionCache &)
This class represents a function call, abstracting a target machine's calling convention.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of .assume calls within a function.
PredicateInfoPrinterLegacyPass()
Analysis pass which computes a DominatorTree.
virtual void emitBasicBlockStartAnnot(const BasicBlock *BB, formatted_raw_ostream &OS)
emitBasicBlockStartAnnot - This may be implemented to emit a string right after the basic block label...
INITIALIZE_PASS_BEGIN(PredicateInfoPrinterLegacyPass,"print-predicateinfo","PredicateInfo Printer", false, false) INITIALIZE_PASS_END(PredicateInfoPrinterLegacyPass
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static bool valueComesBefore(OrderedInstructions &OI, const Value *A, const Value *B)
StringRef getName() const
Return a constant reference to the value's name.
bool match(Val *V, const Pattern &P)
const Instruction * getDefOrUser(const Value *Def, const Use *U) const
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
A Use represents the edge between a Value definition and its users.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Value * getMiddleDef(const ValueDFS &VD) const
This file provides an implementation of debug counters.
PredicateInfoAnnotatedWriter(const PredicateInfo *M)
void initializePredicateInfoPrinterLegacyPassPass(PassRegistry &)
ppc ctr loops PowerPC CTR Loops Verify
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
print PredicateInfo static false cl::opt< bool > VerifyPredicateInfo("verify-predicateinfo", cl::init(false), cl::Hidden, cl::desc("Verify PredicateInfo in legacy printer pass."))
BasicBlock * getSuccessor(unsigned i) const
Base class for the actual dominator tree node.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
bool comparePHIRelated(const ValueDFS &A, const ValueDFS &B) const
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
bool dominates(const Instruction *, const Instruction *) const
Return true if first instruction dominates the second.
bool localComesBefore(const ValueDFS &A, const ValueDFS &B) const
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
bool verify(const TargetRegisterInfo &TRI) const
Check that information hold by this instance make sense for the given TRI.
initializer< Ty > init(const Ty &Val)
void collectCmpOps(CmpInst *Comparison, SmallVectorImpl< Value * > &CmpOperands)
A set of analyses that are preserved following a run of a transformation pass.
LLVM Basic Block Representation.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
Conditional or Unconditional Branch instruction.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
void verifyPredicateInfo() const
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
DEBUG_COUNTER(VNCounter,"newgvn-vn","Controls which instructions are value numbered") DEBUG_COUNTER(PHIOfOpsCounter
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
unsigned getDFSNumIn() const
getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes in the dominator tree...
Represent the analysis usage information of a pass.
void print(raw_ostream &) const
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
FunctionPass class - This class is used to implement most global optimizations.
Value * getOperand(unsigned i) const
static bool shouldExecute(unsigned CounterName)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
This file implements the PredicateInfo analysis, which creates an Extended SSA form for operations us...
Struct that holds a reference to a particular GUID in a global value summary.
bool isConditional() const
A function analysis which provides an AssumptionCache.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
unsigned getNumSuccessors() const
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Encapsulates PredicateInfo, including all data associated with memory accesses.
void setPreservesAll()
Set by analyses that do not transform their input at all.
Value * getCondition() const
llvm_unreachable("Unknown RegBank!")
unsigned getDFSNumOut() const
const PredicateBase * getPredicateInfoFor(const Value *V) const
BasicBlock * getSuccessor(unsigned idx) const
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Value * getCondition() const
print PredicateInfo Printer
ValueDFS_Compare(OrderedInstructions &OI)
const std::pair< BasicBlock *, BasicBlock * > getBlockEdge(const ValueDFS &VD) const
bool hasOneUse() const
Return true if there is exactly one user of this value.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
An assembly annotator class to print PredicateInfo information in comments.
AnalysisUsage & addRequiredTransitive()
print PredicateInfo false
iterator_range< df_iterator< T > > depth_first(const T &G)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
This class implements an extremely fast bulk output stream that can only output to a stream...
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
bool runOnFunction(Function &) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
const BasicBlock * getParent() const
bool operator()(const ValueDFS &A, const ValueDFS &B) const
A wrapper class for inspecting calls to intrinsic functions.
virtual void emitInstructionAnnot(const Instruction *I, formatted_raw_ostream &OS)
emitInstructionAnnot - This may be implemented to emit a string right before an instruction is emitte...