40 #define DEBUG_TYPE "predicateinfo" 46 "PredicateInfo Printer",
false,
false)
55 "Controls which variables are renamed with predicateinfo");
61 assert(isa<PredicateWithEdge>(PB) &&
62 "Only branches and switches should have PHIOnly defs that " 63 "require branch blocks.");
64 return cast<PredicateWithEdge>(PB)->From;
70 assert(isa<PredicateWithEdge>(PB) &&
71 "Not a predicate info type we know how to get a terminator from.");
72 return cast<PredicateWithEdge>(PB)->From->getTerminator();
77 const std::pair<BasicBlock *, BasicBlock *>
79 assert(isa<PredicateWithEdge>(PB) &&
80 "Not a predicate info type we know how to get an edge from.");
81 const auto *PEdge = cast<PredicateWithEdge>(PB);
82 return std::make_pair(PEdge->From, PEdge->To);
87 namespace PredicateInfoClasses {
109 bool EdgeOnly =
false;
115 auto *ArgA = dyn_cast_or_null<Argument>(A);
116 auto *ArgB = dyn_cast_or_null<Argument>(
B);
122 return ArgA->getArgNo() < ArgB->getArgNo();
123 return OI.
dfsBefore(cast<Instruction>(A), cast<Instruction>(B));
148 return comparePHIRelated(A, B);
153 return localComesBefore(A, B);
157 const std::pair<BasicBlock *, BasicBlock *>
159 if (!VD.
Def && VD.
U) {
160 auto *PHI = cast<PHINode>(VD.
U->getUser());
161 return std::make_pair(PHI->getIncomingBlock(*VD.
U), PHI->getParent());
164 return ::getBlockEdge(VD.
PInfo);
169 auto &ABlockEdge = getBlockEdge(A);
170 auto &BBlockEdge = getBlockEdge(B);
172 return std::tie(ABlockEdge, A.
Def, A.
U) < std::tie(BBlockEdge, B.
Def, B.
U);
187 "No def, no use, and no predicateinfo should not occur");
189 "Middle of block should only occur for assumes");
190 return cast<PredicateAssume>(VD.
PInfo)->AssumeInst;
199 return cast<Instruction>(
Def);
200 return cast<Instruction>(U->getUser());
206 auto *ADef = getMiddleDef(A);
207 auto *BDef = getMiddleDef(B);
212 auto *ArgA = dyn_cast_or_null<Argument>(ADef);
213 auto *ArgB = dyn_cast_or_null<Argument>(BDef);
218 auto *AInst = getDefOrUser(ADef, A.
U);
219 auto *BInst = getDefOrUser(BDef, B.
U);
226 bool PredicateInfo::stackIsInScope(
const ValueDFSStack &Stack,
235 if (Stack.back().EdgeOnly) {
242 BasicBlock *EdgePred = PHI->getIncomingBlock(*VDUse.
U);
243 if (EdgePred != getBranchBlock(Stack.back().PInfo))
247 return DT.dominates(getBlockEdge(Stack.back().PInfo), *VDUse.
U);
250 return (VDUse.
DFSIn >= Stack.back().DFSIn &&
251 VDUse.
DFSOut <= Stack.back().DFSOut);
254 void PredicateInfo::popStackUntilDFSScope(ValueDFSStack &Stack,
256 while (!Stack.empty() && !stackIsInScope(Stack, VD))
262 void PredicateInfo::convertUsesToDFSOrdered(
264 for (
auto &U : Op->
uses()) {
265 if (
auto *
I = dyn_cast<Instruction>(U.getUser())) {
269 if (
auto *PN = dyn_cast<PHINode>(
I)) {
270 IBlock = PN->getIncomingBlock(U);
277 IBlock =
I->getParent();
304 if ((isa<Instruction>(Op0) || isa<Argument>(Op0)) && !Op0->hasOneUse())
306 if ((isa<Instruction>(Op1) || isa<Argument>(Op1)) && !Op1->hasOneUse())
314 auto &OperandInfo = getOrCreateValueInfo(Op);
315 AllInfos.push_back(PB);
316 OperandInfo.Infos.push_back(PB);
331 ConditionsToProcess.
push_back(cast<BinaryOperator>(Operand)->getOperand(0));
332 ConditionsToProcess.
push_back(cast<BinaryOperator>(Operand)->getOperand(1));
334 }
else if (isa<CmpInst>(Operand)) {
338 for (
auto Cond : ConditionsToProcess) {
339 if (
auto *Cmp = dyn_cast<CmpInst>(Cond)) {
342 for (
auto *Op : CmpOperands) {
344 addInfoFor(OpsToRename, Op, PA);
347 }
else if (
auto *BinOp = dyn_cast<BinaryOperator>(Cond)) {
349 assert(BinOp->getOpcode() == Instruction::And &&
350 "Should have been an AND");
352 addInfoFor(OpsToRename, BinOp, PA);
370 auto InsertHelper = [&](
Value *
Op,
bool isAnd,
bool isOr,
Value *Cond) {
371 for (
auto *Succ : SuccsToProcess) {
374 if (Succ == BranchBB)
376 bool TakenEdge = (Succ == FirstBB);
379 if ((isAnd && !TakenEdge) || (isOr && TakenEdge))
383 addInfoFor(OpsToRename, Op, PB);
384 if (!Succ->getSinglePredecessor())
385 EdgeUsesOnly.insert({BranchBB, Succ});
399 if (BinOp->getOpcode() == Instruction::And)
401 else if (BinOp->getOpcode() == Instruction::Or)
403 ConditionsToProcess.
push_back(BinOp->getOperand(0));
404 ConditionsToProcess.
push_back(BinOp->getOperand(1));
409 for (
auto Cond : ConditionsToProcess) {
410 if (
auto *Cmp = dyn_cast<CmpInst>(Cond)) {
413 for (
auto *Op : CmpOperands)
414 InsertHelper(Op, isAnd, isOr, Cmp);
415 }
else if (
auto *BinOp = dyn_cast<BinaryOperator>(Cond)) {
417 assert((BinOp->getOpcode() == Instruction::And ||
418 BinOp->getOpcode() == Instruction::Or) &&
419 "Should have been an AND or an OR");
422 InsertHelper(BinOp,
false,
false, BinOp);
434 if ((!isa<Instruction>(Op) && !isa<Argument>(Op)) || Op->
hasOneUse())
441 ++SwitchEdges[TargetBlock];
445 for (
auto C : SI->
cases()) {
447 if (SwitchEdges.
lookup(TargetBlock) == 1) {
449 Op, SI->
getParent(), TargetBlock,
C.getCaseValue(),
SI);
450 addInfoFor(OpsToRename, Op, PS);
452 EdgeUsesOnly.insert({BranchBB, TargetBlock});
458 void PredicateInfo::buildPredicateInfo() {
459 DT.updateDFSNumbers();
465 if (
auto *BI = dyn_cast<BranchInst>(BranchBB->
getTerminator())) {
471 processBranch(BI, BranchBB, OpsToRename);
472 }
else if (
auto *SI = dyn_cast<SwitchInst>(BranchBB->
getTerminator())) {
476 for (
auto &Assume : AC.assumptions()) {
477 if (
auto *II = dyn_cast_or_null<IntrinsicInst>(Assume))
478 processAssume(II, II->
getParent(), OpsToRename);
481 renameUses(OpsToRename);
492 std::string
Name =
"llvm.ssa.copy." +
utostr((uintptr_t) Ty);
499 Value *PredicateInfo::materializeStack(
unsigned int &Counter,
500 ValueDFSStack &RenameStack,
503 auto RevIter = RenameStack.rbegin();
504 for (; RevIter != RenameStack.rend(); ++RevIter)
508 size_t Start = RevIter - RenameStack.rbegin();
512 for (
auto RenameIter = RenameStack.end() - Start;
513 RenameIter != RenameStack.end(); ++RenameIter) {
515 RenameIter == RenameStack.begin() ? OrigOp : (RenameIter - 1)->
Def;
517 auto *ValInfo = Result.
PInfo;
523 if (isa<PredicateWithEdge>(ValInfo)) {
527 CreatedDeclarations.insert(IF);
530 PredicateMap.insert({PIC, ValInfo});
535 "Should not have gotten here without it being an assume");
539 CreatedDeclarations.insert(IF);
541 PredicateMap.insert({PIC, ValInfo});
545 return RenameStack.back().Def;
570 auto Comparator = [&](
const Value *A,
const Value *
B) {
576 for (
auto *Op : OpsToRename) {
578 unsigned Counter = 0;
580 const auto &
ValueInfo = getValueInfo(Op);
584 for (
auto &PossibleCopy :
ValueInfo.Infos) {
591 if (
const auto *PAssume = dyn_cast<PredicateAssume>(PossibleCopy)) {
593 DomTreeNode *DomNode = DT.getNode(PAssume->AssumeInst->getParent());
598 VD.
PInfo = PossibleCopy;
600 }
else if (isa<PredicateWithEdge>(PossibleCopy)) {
604 auto BlockEdge = getBlockEdge(PossibleCopy);
605 if (EdgeUsesOnly.count(BlockEdge)) {
607 auto *DomNode = DT.getNode(BlockEdge.first);
609 VD.
DFSIn = DomNode->getDFSNumIn();
610 VD.
DFSOut = DomNode->getDFSNumOut();
611 VD.
PInfo = PossibleCopy;
620 auto *DomNode = DT.getNode(BlockEdge.second);
622 VD.
DFSIn = DomNode->getDFSNumIn();
623 VD.
DFSOut = DomNode->getDFSNumOut();
624 VD.
PInfo = PossibleCopy;
631 convertUsesToDFSOrdered(Op, OrderedUses);
641 for (
auto &VD : OrderedUses) {
644 bool PossibleCopy = VD.
PInfo !=
nullptr;
645 if (RenameStack.empty()) {
649 << RenameStack.back().DFSIn <<
"," 650 << RenameStack.back().DFSOut <<
")\n");
656 bool ShouldPush = (VD.
Def || PossibleCopy);
657 bool OutOfScope = !stackIsInScope(RenameStack, VD);
658 if (OutOfScope || ShouldPush) {
660 popStackUntilDFSScope(RenameStack, VD);
662 RenameStack.push_back(VD);
667 if (RenameStack.empty())
670 if (VD.
Def || PossibleCopy)
673 LLVM_DEBUG(
dbgs() <<
"Skipping execution due to debug counter\n");
682 Result.
Def = materializeStack(Counter, RenameStack, Op);
685 << *VD.
U->get() <<
" in " << *(VD.
U->getUser())
687 assert(DT.dominates(cast<Instruction>(Result.
Def), *VD.
U) &&
688 "Predicateinfo def should have dominated this use");
689 VD.
U->set(Result.
Def);
694 PredicateInfo::ValueInfo &PredicateInfo::getOrCreateValueInfo(
Value *Operand) {
695 auto OIN = ValueInfoNums.find(Operand);
696 if (OIN == ValueInfoNums.end()) {
698 ValueInfos.resize(ValueInfos.size() + 1);
700 auto InsertResult = ValueInfoNums.insert({Operand, ValueInfos.size() - 1});
701 assert(InsertResult.second &&
"Value info number already existed?");
702 return ValueInfos[InsertResult.first->second];
704 return ValueInfos[OIN->second];
707 const PredicateInfo::ValueInfo &
708 PredicateInfo::getValueInfo(
Value *Operand)
const {
709 auto OINI = ValueInfoNums.lookup(Operand);
710 assert(OINI != 0 &&
"Operand was not really in the Value Info Numbers");
711 assert(OINI < ValueInfos.size() &&
712 "Value Info Number greater than size of Value Info Table");
713 return ValueInfos[OINI];
718 : F(F), DT(DT), AC(AC), OI(&DT) {
721 buildPredicateInfo();
730 for (
auto &F : CreatedDeclarations)
732 CreatedDeclarations.clear();
736 "PredicateInfo consumer did not remove all SSA copies.");
772 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
773 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
774 auto PredInfo = make_unique<PredicateInfo>(
F, DT, AC);
775 PredInfo->print(
dbgs());
777 PredInfo->verifyPredicateInfo();
787 OS <<
"PredicateInfo for function: " << F.
getName() <<
"\n";
788 auto PredInfo = make_unique<PredicateInfo>(
F, DT, AC);
810 OS <<
"; Has predicate info\n";
811 if (
const auto *PB = dyn_cast<PredicateBranch>(PI)) {
812 OS <<
"; branch predicate info { TrueEdge: " << PB->TrueEdge
813 <<
" Comparison:" << *PB->Condition <<
" Edge: [";
814 PB->From->printAsOperand(OS);
816 PB->To->printAsOperand(OS);
818 }
else if (
const auto *PS = dyn_cast<PredicateSwitch>(PI)) {
819 OS <<
"; switch predicate info { CaseValue: " << *PS->CaseValue
820 <<
" Switch:" << *PS->Switch <<
" Edge: [";
821 PS->From->printAsOperand(OS);
823 PS->To->printAsOperand(OS);
825 }
else if (
const auto *PA = dyn_cast<PredicateAssume>(PI)) {
826 OS <<
"; assume predicate info {" 827 <<
" Comparison:" << *PA->Condition <<
" }\n";
835 F.print(OS, &Writer);
840 F.print(
dbgs(), &Writer);
847 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.
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.
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.
Compute iterated dominance frontiers using a linear time algorithm.
Constant * getOrInsertFunction(StringRef Name, FunctionType *T, AttributeList AttributeList)
Look up the specified function in the module symbol table.
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
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
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)
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 provides a uniform API for creating instructions and inserting them into a basic block: either a...
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
Value * getOperand(unsigned i_nocapture) 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")
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
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)
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.
void sort(IteratorTy Start, IteratorTy End)
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...
Module.h This file contains the declarations for the Module class.
bool isConditional() const
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.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
print PredicateInfo Printer
ValueDFS_Compare(OrderedInstructions &OI)
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)
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()
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.
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...
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...
CallInst * CreateCall(Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)