39 #define DEBUG_TYPE "predicateinfo" 45 "PredicateInfo Printer",
false,
false)
51 "
verify-predicateinfo", cl::
init(false), cl::Hidden,
54 "Controls which variables are renamed with predicateinfo");
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;
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();
76 const std::pair<BasicBlock *, BasicBlock *>
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);
86 namespace PredicateInfoClasses {
108 bool EdgeOnly =
false;
114 auto *ArgA = dyn_cast_or_null<Argument>(A);
115 auto *ArgB = dyn_cast_or_null<Argument>(
B);
121 return ArgA->getArgNo() < ArgB->getArgNo();
122 return OI.
dfsBefore(cast<Instruction>(A), cast<Instruction>(B));
143 "Equal DFS-in numbers imply equal out numbers");
151 return comparePHIRelated(A, B);
158 return localComesBefore(A, B);
162 const std::pair<BasicBlock *, BasicBlock *>
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());
169 return ::getBlockEdge(VD.
PInfo);
175 std::tie(ASrc, ADest) = getBlockEdge(A);
176 std::tie(BSrc, BDest) = getBlockEdge(B);
183 "DFS numbers for A should match the ones of the source block");
185 "DFS numbers for B should match the ones of the source block");
200 "Def and U cannot be set at the same time");
202 return std::tie(AIn, isADef) < std::tie(BIn, isBDef);
217 "No def, no use, and no predicateinfo should not occur");
219 "Middle of block should only occur for assumes");
220 return cast<PredicateAssume>(VD.
PInfo)->AssumeInst;
229 return cast<Instruction>(
Def);
230 return cast<Instruction>(U->getUser());
236 auto *ADef = getMiddleDef(A);
237 auto *BDef = getMiddleDef(B);
242 auto *ArgA = dyn_cast_or_null<Argument>(ADef);
243 auto *ArgB = dyn_cast_or_null<Argument>(BDef);
248 auto *AInst = getDefOrUser(ADef, A.
U);
249 auto *BInst = getDefOrUser(BDef, B.
U);
256 bool PredicateInfo::stackIsInScope(
const ValueDFSStack &Stack,
265 if (Stack.back().EdgeOnly) {
272 BasicBlock *EdgePred = PHI->getIncomingBlock(*VDUse.
U);
273 if (EdgePred != getBranchBlock(Stack.back().PInfo))
277 return DT.dominates(getBlockEdge(Stack.back().PInfo), *VDUse.
U);
280 return (VDUse.
DFSIn >= Stack.back().DFSIn &&
281 VDUse.
DFSOut <= Stack.back().DFSOut);
284 void PredicateInfo::popStackUntilDFSScope(ValueDFSStack &Stack,
286 while (!Stack.empty() && !stackIsInScope(Stack, VD))
292 void PredicateInfo::convertUsesToDFSOrdered(
294 for (
auto &U : Op->
uses()) {
295 if (
auto *
I = dyn_cast<Instruction>(U.getUser())) {
299 if (
auto *PN = dyn_cast<PHINode>(
I)) {
300 IBlock = PN->getIncomingBlock(U);
307 IBlock =
I->getParent();
334 if ((isa<Instruction>(Op0) || isa<Argument>(Op0)) && !Op0->hasOneUse())
336 if ((isa<Instruction>(Op1) || isa<Argument>(Op1)) && !Op1->hasOneUse())
343 auto &OperandInfo = getOrCreateValueInfo(Op);
344 if (OperandInfo.Infos.empty())
346 AllInfos.push_back(PB);
347 OperandInfo.Infos.push_back(PB);
362 ConditionsToProcess.
push_back(cast<BinaryOperator>(Operand)->getOperand(0));
363 ConditionsToProcess.
push_back(cast<BinaryOperator>(Operand)->getOperand(1));
365 }
else if (isa<CmpInst>(Operand)) {
369 for (
auto Cond : ConditionsToProcess) {
370 if (
auto *Cmp = dyn_cast<CmpInst>(Cond)) {
373 for (
auto *Op : CmpOperands) {
375 addInfoFor(OpsToRename, Op, PA);
378 }
else if (
auto *BinOp = dyn_cast<BinaryOperator>(Cond)) {
380 assert(BinOp->getOpcode() == Instruction::And &&
381 "Should have been an AND");
383 addInfoFor(OpsToRename, BinOp, PA);
401 auto InsertHelper = [&](
Value *
Op,
bool isAnd,
bool isOr,
Value *Cond) {
402 for (
auto *Succ : SuccsToProcess) {
405 if (Succ == BranchBB)
407 bool TakenEdge = (Succ == FirstBB);
410 if ((isAnd && !TakenEdge) || (isOr && TakenEdge))
414 addInfoFor(OpsToRename, Op, PB);
415 if (!Succ->getSinglePredecessor())
416 EdgeUsesOnly.insert({BranchBB, Succ});
430 if (BinOp->getOpcode() == Instruction::And)
432 else if (BinOp->getOpcode() == Instruction::Or)
434 ConditionsToProcess.
push_back(BinOp->getOperand(0));
435 ConditionsToProcess.
push_back(BinOp->getOperand(1));
440 for (
auto Cond : ConditionsToProcess) {
441 if (
auto *Cmp = dyn_cast<CmpInst>(Cond)) {
444 for (
auto *Op : CmpOperands)
445 InsertHelper(Op, isAnd, isOr, Cmp);
446 }
else if (
auto *BinOp = dyn_cast<BinaryOperator>(Cond)) {
448 assert((BinOp->getOpcode() == Instruction::And ||
449 BinOp->getOpcode() == Instruction::Or) &&
450 "Should have been an AND or an OR");
453 InsertHelper(BinOp,
false,
false, BinOp);
465 if ((!isa<Instruction>(Op) && !isa<Argument>(Op)) || Op->
hasOneUse())
472 ++SwitchEdges[TargetBlock];
476 for (
auto C : SI->
cases()) {
478 if (SwitchEdges.
lookup(TargetBlock) == 1) {
480 Op, SI->
getParent(), TargetBlock,
C.getCaseValue(),
SI);
481 addInfoFor(OpsToRename, Op, PS);
483 EdgeUsesOnly.insert({BranchBB, TargetBlock});
489 void PredicateInfo::buildPredicateInfo() {
490 DT.updateDFSNumbers();
496 if (
auto *BI = dyn_cast<BranchInst>(BranchBB->
getTerminator())) {
502 processBranch(BI, BranchBB, OpsToRename);
503 }
else if (
auto *SI = dyn_cast<SwitchInst>(BranchBB->
getTerminator())) {
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);
513 renameUses(OpsToRename);
524 std::string
Name =
"llvm.ssa.copy." +
utostr((uintptr_t) Ty);
525 return cast<Function>(
533 Value *PredicateInfo::materializeStack(
unsigned int &Counter,
534 ValueDFSStack &RenameStack,
537 auto RevIter = RenameStack.rbegin();
538 for (; RevIter != RenameStack.rend(); ++RevIter)
542 size_t Start = RevIter - RenameStack.rbegin();
546 for (
auto RenameIter = RenameStack.end() - Start;
547 RenameIter != RenameStack.end(); ++RenameIter) {
549 RenameIter == RenameStack.begin() ? OrigOp : (RenameIter - 1)->
Def;
551 auto *ValInfo = Result.
PInfo;
557 if (isa<PredicateWithEdge>(ValInfo)) {
560 if (IF->
users().empty())
561 CreatedDeclarations.insert(IF);
564 PredicateMap.insert({PIC, ValInfo});
569 "Should not have gotten here without it being an assume");
572 if (IF->
users().empty())
573 CreatedDeclarations.insert(IF);
575 PredicateMap.insert({PIC, ValInfo});
579 return RenameStack.back().Def;
604 for (
auto *Op : OpsToRename) {
606 unsigned Counter = 0;
608 const auto &
ValueInfo = getValueInfo(Op);
612 for (
auto &PossibleCopy :
ValueInfo.Infos) {
619 if (
const auto *PAssume = dyn_cast<PredicateAssume>(PossibleCopy)) {
621 DomTreeNode *DomNode = DT.getNode(PAssume->AssumeInst->getParent());
626 VD.
PInfo = PossibleCopy;
628 }
else if (isa<PredicateWithEdge>(PossibleCopy)) {
632 auto BlockEdge = getBlockEdge(PossibleCopy);
633 if (EdgeUsesOnly.count(BlockEdge)) {
635 auto *DomNode = DT.getNode(BlockEdge.first);
637 VD.
DFSIn = DomNode->getDFSNumIn();
638 VD.
DFSOut = DomNode->getDFSNumOut();
639 VD.
PInfo = PossibleCopy;
648 auto *DomNode = DT.getNode(BlockEdge.second);
650 VD.
DFSIn = DomNode->getDFSNumIn();
651 VD.
DFSOut = DomNode->getDFSNumOut();
652 VD.
PInfo = PossibleCopy;
659 convertUsesToDFSOrdered(Op, OrderedUses);
669 for (
auto &VD : OrderedUses) {
672 bool PossibleCopy = VD.
PInfo !=
nullptr;
673 if (RenameStack.
empty()) {
677 << RenameStack.
back().DFSIn <<
"," 678 << RenameStack.
back().DFSOut <<
")\n");
684 bool ShouldPush = (VD.
Def || PossibleCopy);
685 bool OutOfScope = !stackIsInScope(RenameStack, VD);
686 if (OutOfScope || ShouldPush) {
688 popStackUntilDFSScope(RenameStack, VD);
695 if (RenameStack.
empty())
698 if (VD.
Def || PossibleCopy)
701 LLVM_DEBUG(
dbgs() <<
"Skipping execution due to debug counter\n");
710 Result.
Def = materializeStack(Counter, RenameStack, Op);
713 << *VD.
U->get() <<
" in " << *(VD.
U->getUser())
715 assert(DT.dominates(cast<Instruction>(Result.
Def), *VD.
U) &&
716 "Predicateinfo def should have dominated this use");
717 VD.
U->set(Result.
Def);
722 PredicateInfo::ValueInfo &PredicateInfo::getOrCreateValueInfo(
Value *Operand) {
723 auto OIN = ValueInfoNums.find(Operand);
724 if (OIN == ValueInfoNums.end()) {
726 ValueInfos.resize(ValueInfos.size() + 1);
728 auto InsertResult = ValueInfoNums.insert({Operand, ValueInfos.size() - 1});
729 assert(InsertResult.second &&
"Value info number already existed?");
730 return ValueInfos[InsertResult.first->second];
732 return ValueInfos[OIN->second];
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];
746 : F(F), DT(DT), AC(AC), OI(&DT) {
749 buildPredicateInfo();
758 for (
auto &F : CreatedDeclarations)
760 CreatedDeclarations.clear();
764 "PredicateInfo consumer did not remove all SSA copies.");
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());
805 PredInfo->verifyPredicateInfo();
815 OS <<
"PredicateInfo for function: " << F.
getName() <<
"\n";
816 auto PredInfo = std::make_unique<PredicateInfo>(
F, DT, AC);
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);
844 PB->To->printAsOperand(OS);
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);
851 PS->To->printAsOperand(OS);
853 }
else if (
const auto *PA = dyn_cast<PredicateAssume>(PI)) {
854 OS <<
"; assume predicate info {" 855 <<
" Comparison:" << *PA->Condition <<
" }\n";
863 F.print(OS, &Writer);
868 F.print(
dbgs(), &Writer);
875 std::make_unique<PredicateInfo>(
F, DT, AC)->verifyPredicateInfo();
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
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.
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.
bool operator()(const ValueDFS &A, const ValueDFS &B) const
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents lattice values for constants.
A Module instance is used to store all the information related to an LLVM module. ...
static Function * getCopyDeclaration(Module *M, Type *Ty)
void verifyPredicateInfo() const
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
void push_back(const T &Elt)
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.
Value * getCondition() const
void collectCmpOps(CmpInst *Comparison, SmallVectorImpl< Value *> &CmpOperands)
A cache of @llvm.assume calls within a function.
const std::pair< BasicBlock *, BasicBlock * > getBlockEdge(const ValueDFS &VD) const
PredicateInfoPrinterLegacyPass()
BasicBlock * getSuccessor(unsigned i) const
Analysis pass which computes a DominatorTree.
Value * getCondition() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
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...
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static bool valueComesBefore(OrderedInstructions &OI, const Value *A, const Value *B)
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
ValueDFS_Compare(DominatorTree &DT, OrderedInstructions &OI)
inst_iterator inst_begin(Function *F)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVMContext & getContext() const
Get the global data context.
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...
This file provides an implementation of debug counters.
PredicateInfoAnnotatedWriter(const PredicateInfo *M)
void initializePredicateInfoPrinterLegacyPassPass(PassRegistry &)
Type * getType() const
All values are typed, get the type of this value.
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."))
unsigned getNumSuccessors() const
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
BasicBlock * getSuccessor(unsigned idx) const
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Value * getOperand(unsigned i) const
bool comparePHIRelated(const ValueDFS &A, const ValueDFS &B) const
bool localComesBefore(const ValueDFS &A, const ValueDFS &B) const
unsigned getDFSNumIn() const
getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes in the dominator tree...
initializer< Ty > init(const Ty &Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
A set of analyses that are preserved following a run of a transformation pass.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
Conditional or Unconditional Branch instruction.
INITIALIZE_PASS_BEGIN(PredicateInfoPrinterLegacyPass, "print-predicateinfo", "PredicateInfo Printer", false, false) INITIALIZE_PASS_END(PredicateInfoPrinterLegacyPass
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
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.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Represent the analysis usage information of a pass.
bool dfsBefore(const Instruction *, const Instruction *) const
Return true if the first instruction comes before the second in the dominator tree DFS traversal if t...
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
FunctionPass class - This class is used to implement most global optimizations.
unsigned getDFSNumOut() const
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static bool shouldExecute(unsigned CounterName)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static wasm::ValType getType(const TargetRegisterClass *RC)
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
This file implements the PredicateInfo analysis, which creates an Extended SSA form for operations us...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool verify(const TargetRegisterInfo &TRI) const
Check that information hold by this instance make sense for the given TRI.
Struct that holds a reference to a particular GUID in a global value summary.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
A function analysis which provides an AssumptionCache.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
BlockVerifier::State From
Module.h This file contains the declarations for the Module class.
modulo schedule Modulo Schedule test pass
bool isConditional() const
FunctionCallee getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
std::string utostr(uint64_t X, bool isNeg=false)
static void replaceCreatedSSACopys(PredicateInfo &PredInfo, Function &F)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Encapsulates PredicateInfo, including all data associated with memory accesses.
const PredicateBase * getPredicateInfoFor(const Value *V) const
void setPreservesAll()
Set by analyses that do not transform their input at all.
iterator_range< user_iterator > users()
print PredicateInfo Printer
LLVM_NODISCARD bool empty() const
StringRef getName() const
Return a constant reference to the value's name.
static void rename(GlobalValue *GV)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
An assembly annotator class to print PredicateInfo information in comments.
AnalysisUsage & addRequiredTransitive()
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...
iterator_range< df_iterator< T > > depth_first(const T &G)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
void stable_sort(R &&Range)
LLVM Value Representation.
This class implements an extremely fast bulk output stream that can only output to a stream...
bool hasOneUse() const
Return true if there is exactly one user of this value.
inst_iterator inst_end(Function *F)
A container for analyses that lazily runs them and caches their results.
void print(raw_ostream &) const
Legacy analysis pass which computes a DominatorTree.
DEBUG_COUNTER(RenameCounter, "predicateinfo-rename", "Controls which variables are renamed with predicateinfo")
bool runOnFunction(Function &) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
Value * getMiddleDef(const ValueDFS &VD) const
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
const Instruction * getDefOrUser(const Value *Def, const Use *U) const
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...