29 #define DEBUG_TYPE "must-execute" 39 ColorsForNewBlock = ColorsForOldBlock;
52 assert(CurLoop !=
nullptr &&
"CurLoop can't be null");
56 MayThrow = HeaderMayThrow;
61 "First block must be header");
64 (BB != BBE) && !MayThrow; ++BB)
71 return ICF.hasICF(BB);
79 assert(CurLoop !=
nullptr &&
"CurLoop can't be null");
84 for (
auto &BB : CurLoop->
blocks())
85 if (ICF.hasICF(&*BB)) {
94 ICF.insertInstructionTo(Inst, BB);
95 MW.insertInstructionTo(Inst, BB);
99 ICF.removeInstruction(Inst);
100 MW.removeInstruction(Inst);
118 const Loop *CurLoop) {
123 assert(CurLoop->
contains(CondExitBlock) &&
"meaning of exit block");
125 if (!BI || !BI->isConditional())
129 if (
auto *Cond = dyn_cast<ConstantInt>(BI->getCondition()))
130 return BI->
getSuccessor(Cond->getZExtValue() ? 1 : 0) == ExitBlock;
138 auto *RHS = Cond->getOperand(1);
139 if (!LHS || LHS->getParent() != CurLoop->
getHeader())
147 auto *SimpleCst = dyn_cast_or_null<Constant>(SimpleValOrNull);
150 if (ExitBlock == BI->getSuccessor(0))
151 return SimpleCst->isZeroValue();
152 assert(ExitBlock == BI->getSuccessor(1) &&
"implied by above");
153 return SimpleCst->isAllOnesValue();
162 assert(Predecessors.
empty() &&
"Garbage in predecessors set?");
163 assert(CurLoop->
contains(BB) &&
"Should only be called for loop blocks!");
168 Predecessors.
insert(Pred);
171 while (!WorkList.
empty()) {
173 assert(CurLoop->
contains(Pred) &&
"Should only reach loop blocks!");
184 if (Predecessors.
insert(PredPred).second)
192 assert(CurLoop->
contains(BB) &&
"Should only be called for loop blocks!");
210 for (
auto *Pred : Predecessors) {
221 if (CheckedSuccessors.
insert(Succ).second &&
222 Succ != BB && !Predecessors.count(Succ))
250 const Loop *CurLoop)
const {
259 return !HeaderMayThrow ||
269 const Loop *CurLoop)
const {
270 return !ICF.isDominatedByICFIFromSameBlock(&Inst) &&
275 const Loop *CurLoop)
const {
276 assert(CurLoop->
contains(BB) &&
"Should only be called for loop blocks!");
288 for (
auto *Pred : Predecessors)
289 if (MW.mayWriteToMemory(Pred))
295 const Loop *CurLoop)
const {
297 assert(CurLoop->
contains(BB) &&
"Should only be called for loop blocks!");
298 return !MW.isDominatedByMemoryWriteFromSameBlock(&I) &&
299 doesNotWriteMemoryBefore(BB, CurLoop);
316 struct MustBeExecutedContextPrinter :
public ModulePass {
319 MustBeExecutedContextPrinter() :
ModulePass(ID) {
325 bool runOnModule(
Module &M)
override;
331 "Instructions which execute on loop entry",
false,
true)
338 return new MustExecutePrinter();
343 MustBeExecutedContextPrinter,
"print-must-be-executed-contexts",
344 "print the must-be-executed-contexed for all instructions",
false,
true)
349 "print-must-be-executed-contexts",
350 "print the must-be-executed-contexed for all instructions",
354 return new MustBeExecutedContextPrinter();
357 bool MustBeExecutedContextPrinter::runOnModule(
Module &M) {
364 GetterTy<LoopInfo> LIGetter = [&](
const Function &
F) {
371 GetterTy<PostDominatorTree> PDTGetter = [&](
const Function &
F) {
379 dbgs() <<
"-- Explore context of: " <<
I <<
"\n";
381 dbgs() <<
" [F: " << CI->getFunction()->getName() <<
"] " << *CI
409 MustExecuteAnnotatedWriter(
const Function &
F,
415 MustExec[&
I].push_back(L);
421 MustExecuteAnnotatedWriter(
const Module &M,
428 MustExec[&
I].push_back(L);
437 if (!MustExec.
count(&V))
441 const auto NumLoops =
Loops.size();
443 OS <<
" ; (mustexec in " << NumLoops <<
" loops: ";
445 OS <<
" ; (mustexec in: ";
452 OS << L->getHeader()->getName();
460 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
461 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
463 MustExecuteAnnotatedWriter Writer(F, DT, LI);
482 RPOTraversal FuncRPOT(&F);
489 template <
typename K,
typename V,
typename FnTy,
typename... ArgsTy>
491 FnTy &&Fn, ArgsTy&&... args) {
494 OptVal = Fn(std::forward<ArgsTy>(args)...);
504 << (LI ?
" [LI]" :
"") << (PDT ?
" [PDT]" :
""));
509 bool WillReturnAndNoThrow = (F.hasFnAttribute(Attribute::WillReturn) ||
513 << (WillReturnAndNoThrow ?
" [WillReturn] [NoUnwind]" :
"")
520 bool IsLatch = SuccBB == HeaderBB;
523 if (!WillReturnAndNoThrow || !IsLatch)
529 if (Worklist.
empty())
533 if (Worklist.
size() == 1)
541 if (
const auto *InitNode = PDT->getNode(InitBB))
542 if (
const auto *IDomNode = InitNode->getIDom())
543 JoinBB = IDomNode->getBlock();
545 if (!JoinBB && Worklist.
size() == 2) {
550 if (Succ0UniqueSucc == InitBB) {
554 }
else if (Succ1UniqueSucc == InitBB) {
558 }
else if (Succ0 == Succ1UniqueSucc) {
562 }
else if (Succ1 == Succ0UniqueSucc) {
566 }
else if (Succ0UniqueSucc == Succ1UniqueSucc) {
569 JoinBB = Succ0UniqueSucc;
589 if (!F.hasFnAttribute(Attribute::WillReturn) || !F.doesNotThrow()) {
591 auto BlockTransfersExecutionToSuccessor = [](
const BasicBlock *BB) {
596 while (!Worklist.
empty()) {
602 if (!Visited.
insert(ToBB).second) {
603 if (!F.hasFnAttribute(Attribute::WillReturn)) {
609 if (MayContainIrreducibleControl)
623 ToBB, BlockTransferMap, BlockTransfersExecutionToSuccessor, ToBB);
624 if (!TransfersExecution)
641 LLVM_DEBUG(
dbgs() <<
"Find next instruction for " << *PP <<
"\n");
645 LLVM_DEBUG(
dbgs() <<
"\tReached terminator in intra-block mode, done\n");
653 if (!TransfersExecution)
662 LLVM_DEBUG(
dbgs() <<
"\tIntermediate instruction does transfer control\n");
679 dbgs() <<
"\tUnconditional terminator, continue with successor\n");
687 return &JoinBB->front();
695 : Explorer(Explorer), CurInst(I) {
699 void MustBeExecutedIterator::reset(
const Instruction *I) {
705 const Instruction *MustBeExecutedIterator::advance() {
706 assert(CurInst &&
"Cannot advance an end iterator!");
709 if (Next && !Visited.insert(Next).second)
virtual void computeLoopSafetyInfo(const Loop *CurLoop)
Computes safety information for a loop checks loop body & header for the possibility of may throw exc...
void DeleteContainerPointers(Container &C)
For a container of pointers, deletes the pointers and then clears the container.
void insertInstructionTo(const Instruction *Inst, const BasicBlock *BB)
Inform the safety info that we are planning to insert a new instruction Inst into the basic block BB...
This class is the base class for the comparison instructions.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
virtual bool blockMayThrow(const BasicBlock *BB) const =0
Returns true iff the block BB potentially may throw exception.
This class represents lattice values for constants.
static bool CanProveNotTakenFirstIteration(const BasicBlock *ExitBlock, const DominatorTree *DT, const Loop *CurLoop)
Return true if we can prove that the given ExitBlock is not reached on the first iteration of the giv...
A Module instance is used to store all the information related to an LLVM module. ...
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
void push_back(const T &Elt)
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
bool isTerminator() const
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
virtual bool anyBlockMayThrow() const =0
Returns true iff any block of the loop for which this info is contains an instruction that may throw ...
virtual bool blockMayThrow(const BasicBlock *BB) const
Returns true iff the block BB potentially may throw exception.
void initializeMustBeExecutedContextPrinterPass(PassRegistry &)
BasicBlock * getSuccessor(unsigned i) const
block Block Frequency true
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
Simple and conservative implementation of LoopSafetyInfo that can give false-positive answers to its ...
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
#define INITIALIZE_PASS_DEPENDENCY(depName)
virtual void computeLoopSafetyInfo(const Loop *CurLoop)
Computes safety information for a loop checks loop body & header for the possibility of may throw exc...
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Contains a collection of routines for determining if a given instruction is guaranteed to execute if ...
virtual bool anyBlockMayThrow() const
Returns true iff any block of the loop for which this info is contains an instruction that may throw ...
BlockT * getHeader() const
static void collectTransitivePredecessors(const Loop *CurLoop, const BasicBlock *BB, SmallPtrSetImpl< const BasicBlock *> &Predecessors)
Collect all blocks from CurLoop which lie on all possible paths from the header of CurLoop (inclusive...
bool isScopedEHPersonality(EHPersonality Pers)
Returns true if this personality uses scope-style EH IR instructions: catchswitch, catchpad/ret, and cleanuppad/ret.
bool containsIrreducibleCFG(RPOTraversalT &RPOTraversal, const LoopInfoT &LI)
Return true if the control flow in RPOTraversal is irreducible.
llvm::iterator_range< iterator > range(const Instruction *PP)
}
Must be executed iterators visit stretches of instructions that are guaranteed to be executed togethe...
Value * SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a CmpInst, fold the result or return null.
virtual bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT, const Loop *CurLoop) const
Returns true if the instruction in a loop is guaranteed to execute at least once. ...
const T & getValue() const LLVM_LVALUE_FUNCTION
void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW=nullptr, bool ShouldPreserveUseListOrder=false, bool IsForDebug=false) const
Print the function to an output stream with an optional AssemblyAnnotationWriter. ...
const Instruction * getMustBeExecutedNextInstruction(MustBeExecutedIterator &It, const Instruction *PP)
Return the next instruction that is guaranteed to be executed after PP.
bool hasPersonalityFn() const
Check whether this function has a personality function.
void copyColors(BasicBlock *New, BasicBlock *Old)
Copy colors of block Old into the block New.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
FunctionPass * createMustExecutePrinter()
static bool runOnFunction(Function &F, bool PostInlining)
bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
virtual bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT, const Loop *CurLoop) const
Returns true if the instruction in a loop is guaranteed to execute at least once (under the assumptio...
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM Basic Block Representation.
Conditional or Unconditional Branch instruction.
This is an important base class in LLVM.
LLVM_NODISCARD bool empty() const
const Instruction & front() const
const BasicBlock * findForwardJoinPoint(const BasicBlock *InitBB)
Find the next join point from InitBB in forward direction.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Represent the analysis usage information of a pass.
MustBeExecutedIterator(const MustBeExecutedIterator &Other)
FunctionPass class - This class is used to implement most global optimizations.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
INITIALIZE_PASS_BEGIN(MustExecutePrinter, "print-mustexecute", "Instructions which execute on loop entry", false, true) INITIALIZE_PASS_END(MustExecutePrinter
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
bool allLoopPathsLeadToBlock(const Loop *CurLoop, const BasicBlock *BB, const DominatorTree *DT) const
Return true if we must reach the block BB under assumption that the loop CurLoop is entered...
void removeInstruction(const Instruction *Inst)
Inform safety info that we are planning to remove the instruction Inst from its block.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
bool doesNotWriteMemoryBefore(const BasicBlock *BB, const Loop *CurLoop) const
Returns true if we could not execute a memory-modifying instruction before we enter BB under assumpti...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Module.h This file contains the declarations for the Module class.
static bool isMustExecuteIn(const Instruction &I, Loop *L, DominatorTree *DT)
LLVM_NODISCARD T pop_back_val()
void computeBlockColors(const Loop *CurLoop)
Computes block colors.
pred_range predecessors(BasicBlock *BB)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void setPreservesAll()
Set by analyses that do not transform their input at all.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
A "must be executed context" for a given program point PP is the set of instructions, potentially before and after PP, that are executed always when PP is reached.
LoopT * getParentLoop() const
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
ModulePass * createMustBeExecutedContextPrinter()
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
static V getOrCreateCachedOptional(K Key, DenseMap< K, Optional< V >> &Map, FnTy &&Fn, ArgsTy &&... args)
Lookup Key in Map and return the result, potentially after initializing the optional through Fn(args)...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
block_iterator block_end() const
virtual bool blockMayThrow(const BasicBlock *BB) const
Returns true iff the block BB potentially may throw exception.
bool isGuaranteedToExecuteForEveryIteration(const Instruction *I, const Loop *L)
Return true if this function can prove that the instruction I is executed for every iteration of the ...
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
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...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
succ_range successors(Instruction *I)
The legacy pass manager's analysis pass to compute loop information.
print Instructions which execute on loop entry
inst_range instructions(Function *F)
void initializeMustExecutePrinterPass(PassRegistry &)
const Instruction * getFirstNonPHIOrDbg() const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic...
Legacy analysis pass which computes a DominatorTree.
virtual bool anyBlockMayThrow() const
Returns true iff any block of the loop for which this info is contains an instruction that may throw ...
DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
iterator_range< block_iterator > blocks() const
block_iterator block_begin() const
static bool maybeEndlessLoop(const Loop &L)
Return true if L might be an endless loop.
const BasicBlock * getParent() const
static bool mayContainIrreducibleControl(const Function &F, const LoopInfo *LI)
const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
const DenseMap< BasicBlock *, ColorVector > & getBlockColors() const
Returns block colors map that is used to update funclet operand bundles.