xref: /netbsd-src/external/apache2/llvm/dist/llvm/lib/Analysis/MustExecute.cpp (revision 82d56013d7b633d116a93943de88e08335357a7c)
17330f729Sjoerg //===- MustExecute.cpp - Printer for isGuaranteedToExecute ----------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg 
97330f729Sjoerg #include "llvm/Analysis/MustExecute.h"
107330f729Sjoerg #include "llvm/ADT/PostOrderIterator.h"
11*82d56013Sjoerg #include "llvm/ADT/StringExtras.h"
127330f729Sjoerg #include "llvm/Analysis/CFG.h"
137330f729Sjoerg #include "llvm/Analysis/InstructionSimplify.h"
147330f729Sjoerg #include "llvm/Analysis/LoopInfo.h"
157330f729Sjoerg #include "llvm/Analysis/Passes.h"
16*82d56013Sjoerg #include "llvm/Analysis/PostDominators.h"
177330f729Sjoerg #include "llvm/Analysis/ValueTracking.h"
187330f729Sjoerg #include "llvm/IR/AssemblyAnnotationWriter.h"
197330f729Sjoerg #include "llvm/IR/DataLayout.h"
20*82d56013Sjoerg #include "llvm/IR/Dominators.h"
217330f729Sjoerg #include "llvm/IR/InstIterator.h"
227330f729Sjoerg #include "llvm/IR/LLVMContext.h"
237330f729Sjoerg #include "llvm/IR/Module.h"
24*82d56013Sjoerg #include "llvm/IR/PassManager.h"
25*82d56013Sjoerg #include "llvm/InitializePasses.h"
267330f729Sjoerg #include "llvm/Support/ErrorHandling.h"
277330f729Sjoerg #include "llvm/Support/FormattedStream.h"
287330f729Sjoerg #include "llvm/Support/raw_ostream.h"
297330f729Sjoerg 
307330f729Sjoerg using namespace llvm;
317330f729Sjoerg 
327330f729Sjoerg #define DEBUG_TYPE "must-execute"
337330f729Sjoerg 
347330f729Sjoerg const DenseMap<BasicBlock *, ColorVector> &
getBlockColors() const357330f729Sjoerg LoopSafetyInfo::getBlockColors() const {
367330f729Sjoerg   return BlockColors;
377330f729Sjoerg }
387330f729Sjoerg 
copyColors(BasicBlock * New,BasicBlock * Old)397330f729Sjoerg void LoopSafetyInfo::copyColors(BasicBlock *New, BasicBlock *Old) {
407330f729Sjoerg   ColorVector &ColorsForNewBlock = BlockColors[New];
417330f729Sjoerg   ColorVector &ColorsForOldBlock = BlockColors[Old];
427330f729Sjoerg   ColorsForNewBlock = ColorsForOldBlock;
437330f729Sjoerg }
447330f729Sjoerg 
blockMayThrow(const BasicBlock * BB) const457330f729Sjoerg bool SimpleLoopSafetyInfo::blockMayThrow(const BasicBlock *BB) const {
467330f729Sjoerg   (void)BB;
477330f729Sjoerg   return anyBlockMayThrow();
487330f729Sjoerg }
497330f729Sjoerg 
anyBlockMayThrow() const507330f729Sjoerg bool SimpleLoopSafetyInfo::anyBlockMayThrow() const {
517330f729Sjoerg   return MayThrow;
527330f729Sjoerg }
537330f729Sjoerg 
computeLoopSafetyInfo(const Loop * CurLoop)547330f729Sjoerg void SimpleLoopSafetyInfo::computeLoopSafetyInfo(const Loop *CurLoop) {
557330f729Sjoerg   assert(CurLoop != nullptr && "CurLoop can't be null");
567330f729Sjoerg   BasicBlock *Header = CurLoop->getHeader();
577330f729Sjoerg   // Iterate over header and compute safety info.
587330f729Sjoerg   HeaderMayThrow = !isGuaranteedToTransferExecutionToSuccessor(Header);
597330f729Sjoerg   MayThrow = HeaderMayThrow;
607330f729Sjoerg   // Iterate over loop instructions and compute safety info.
617330f729Sjoerg   // Skip header as it has been computed and stored in HeaderMayThrow.
627330f729Sjoerg   // The first block in loopinfo.Blocks is guaranteed to be the header.
637330f729Sjoerg   assert(Header == *CurLoop->getBlocks().begin() &&
647330f729Sjoerg          "First block must be header");
657330f729Sjoerg   for (Loop::block_iterator BB = std::next(CurLoop->block_begin()),
667330f729Sjoerg                             BBE = CurLoop->block_end();
677330f729Sjoerg        (BB != BBE) && !MayThrow; ++BB)
687330f729Sjoerg     MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(*BB);
697330f729Sjoerg 
707330f729Sjoerg   computeBlockColors(CurLoop);
717330f729Sjoerg }
727330f729Sjoerg 
blockMayThrow(const BasicBlock * BB) const737330f729Sjoerg bool ICFLoopSafetyInfo::blockMayThrow(const BasicBlock *BB) const {
747330f729Sjoerg   return ICF.hasICF(BB);
757330f729Sjoerg }
767330f729Sjoerg 
anyBlockMayThrow() const777330f729Sjoerg bool ICFLoopSafetyInfo::anyBlockMayThrow() const {
787330f729Sjoerg   return MayThrow;
797330f729Sjoerg }
807330f729Sjoerg 
computeLoopSafetyInfo(const Loop * CurLoop)817330f729Sjoerg void ICFLoopSafetyInfo::computeLoopSafetyInfo(const Loop *CurLoop) {
827330f729Sjoerg   assert(CurLoop != nullptr && "CurLoop can't be null");
837330f729Sjoerg   ICF.clear();
847330f729Sjoerg   MW.clear();
857330f729Sjoerg   MayThrow = false;
867330f729Sjoerg   // Figure out the fact that at least one block may throw.
877330f729Sjoerg   for (auto &BB : CurLoop->blocks())
887330f729Sjoerg     if (ICF.hasICF(&*BB)) {
897330f729Sjoerg       MayThrow = true;
907330f729Sjoerg       break;
917330f729Sjoerg     }
927330f729Sjoerg   computeBlockColors(CurLoop);
937330f729Sjoerg }
947330f729Sjoerg 
insertInstructionTo(const Instruction * Inst,const BasicBlock * BB)957330f729Sjoerg void ICFLoopSafetyInfo::insertInstructionTo(const Instruction *Inst,
967330f729Sjoerg                                             const BasicBlock *BB) {
977330f729Sjoerg   ICF.insertInstructionTo(Inst, BB);
987330f729Sjoerg   MW.insertInstructionTo(Inst, BB);
997330f729Sjoerg }
1007330f729Sjoerg 
removeInstruction(const Instruction * Inst)1017330f729Sjoerg void ICFLoopSafetyInfo::removeInstruction(const Instruction *Inst) {
1027330f729Sjoerg   ICF.removeInstruction(Inst);
1037330f729Sjoerg   MW.removeInstruction(Inst);
1047330f729Sjoerg }
1057330f729Sjoerg 
computeBlockColors(const Loop * CurLoop)1067330f729Sjoerg void LoopSafetyInfo::computeBlockColors(const Loop *CurLoop) {
1077330f729Sjoerg   // Compute funclet colors if we might sink/hoist in a function with a funclet
1087330f729Sjoerg   // personality routine.
1097330f729Sjoerg   Function *Fn = CurLoop->getHeader()->getParent();
1107330f729Sjoerg   if (Fn->hasPersonalityFn())
1117330f729Sjoerg     if (Constant *PersonalityFn = Fn->getPersonalityFn())
1127330f729Sjoerg       if (isScopedEHPersonality(classifyEHPersonality(PersonalityFn)))
1137330f729Sjoerg         BlockColors = colorEHFunclets(*Fn);
1147330f729Sjoerg }
1157330f729Sjoerg 
1167330f729Sjoerg /// Return true if we can prove that the given ExitBlock is not reached on the
1177330f729Sjoerg /// first iteration of the given loop.  That is, the backedge of the loop must
1187330f729Sjoerg /// be executed before the ExitBlock is executed in any dynamic execution trace.
CanProveNotTakenFirstIteration(const BasicBlock * ExitBlock,const DominatorTree * DT,const Loop * CurLoop)1197330f729Sjoerg static bool CanProveNotTakenFirstIteration(const BasicBlock *ExitBlock,
1207330f729Sjoerg                                            const DominatorTree *DT,
1217330f729Sjoerg                                            const Loop *CurLoop) {
1227330f729Sjoerg   auto *CondExitBlock = ExitBlock->getSinglePredecessor();
1237330f729Sjoerg   if (!CondExitBlock)
1247330f729Sjoerg     // expect unique exits
1257330f729Sjoerg     return false;
1267330f729Sjoerg   assert(CurLoop->contains(CondExitBlock) && "meaning of exit block");
1277330f729Sjoerg   auto *BI = dyn_cast<BranchInst>(CondExitBlock->getTerminator());
1287330f729Sjoerg   if (!BI || !BI->isConditional())
1297330f729Sjoerg     return false;
1307330f729Sjoerg   // If condition is constant and false leads to ExitBlock then we always
1317330f729Sjoerg   // execute the true branch.
1327330f729Sjoerg   if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition()))
1337330f729Sjoerg     return BI->getSuccessor(Cond->getZExtValue() ? 1 : 0) == ExitBlock;
1347330f729Sjoerg   auto *Cond = dyn_cast<CmpInst>(BI->getCondition());
1357330f729Sjoerg   if (!Cond)
1367330f729Sjoerg     return false;
1377330f729Sjoerg   // todo: this would be a lot more powerful if we used scev, but all the
1387330f729Sjoerg   // plumbing is currently missing to pass a pointer in from the pass
1397330f729Sjoerg   // Check for cmp (phi [x, preheader] ...), y where (pred x, y is known
1407330f729Sjoerg   auto *LHS = dyn_cast<PHINode>(Cond->getOperand(0));
1417330f729Sjoerg   auto *RHS = Cond->getOperand(1);
1427330f729Sjoerg   if (!LHS || LHS->getParent() != CurLoop->getHeader())
1437330f729Sjoerg     return false;
1447330f729Sjoerg   auto DL = ExitBlock->getModule()->getDataLayout();
1457330f729Sjoerg   auto *IVStart = LHS->getIncomingValueForBlock(CurLoop->getLoopPreheader());
1467330f729Sjoerg   auto *SimpleValOrNull = SimplifyCmpInst(Cond->getPredicate(),
1477330f729Sjoerg                                           IVStart, RHS,
1487330f729Sjoerg                                           {DL, /*TLI*/ nullptr,
1497330f729Sjoerg                                               DT, /*AC*/ nullptr, BI});
1507330f729Sjoerg   auto *SimpleCst = dyn_cast_or_null<Constant>(SimpleValOrNull);
1517330f729Sjoerg   if (!SimpleCst)
1527330f729Sjoerg     return false;
1537330f729Sjoerg   if (ExitBlock == BI->getSuccessor(0))
1547330f729Sjoerg     return SimpleCst->isZeroValue();
1557330f729Sjoerg   assert(ExitBlock == BI->getSuccessor(1) && "implied by above");
1567330f729Sjoerg   return SimpleCst->isAllOnesValue();
1577330f729Sjoerg }
1587330f729Sjoerg 
1597330f729Sjoerg /// Collect all blocks from \p CurLoop which lie on all possible paths from
1607330f729Sjoerg /// the header of \p CurLoop (inclusive) to BB (exclusive) into the set
1617330f729Sjoerg /// \p Predecessors. If \p BB is the header, \p Predecessors will be empty.
collectTransitivePredecessors(const Loop * CurLoop,const BasicBlock * BB,SmallPtrSetImpl<const BasicBlock * > & Predecessors)1627330f729Sjoerg static void collectTransitivePredecessors(
1637330f729Sjoerg     const Loop *CurLoop, const BasicBlock *BB,
1647330f729Sjoerg     SmallPtrSetImpl<const BasicBlock *> &Predecessors) {
1657330f729Sjoerg   assert(Predecessors.empty() && "Garbage in predecessors set?");
1667330f729Sjoerg   assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
1677330f729Sjoerg   if (BB == CurLoop->getHeader())
1687330f729Sjoerg     return;
1697330f729Sjoerg   SmallVector<const BasicBlock *, 4> WorkList;
1707330f729Sjoerg   for (auto *Pred : predecessors(BB)) {
1717330f729Sjoerg     Predecessors.insert(Pred);
1727330f729Sjoerg     WorkList.push_back(Pred);
1737330f729Sjoerg   }
1747330f729Sjoerg   while (!WorkList.empty()) {
1757330f729Sjoerg     auto *Pred = WorkList.pop_back_val();
1767330f729Sjoerg     assert(CurLoop->contains(Pred) && "Should only reach loop blocks!");
1777330f729Sjoerg     // We are not interested in backedges and we don't want to leave loop.
1787330f729Sjoerg     if (Pred == CurLoop->getHeader())
1797330f729Sjoerg       continue;
1807330f729Sjoerg     // TODO: If BB lies in an inner loop of CurLoop, this will traverse over all
1817330f729Sjoerg     // blocks of this inner loop, even those that are always executed AFTER the
1827330f729Sjoerg     // BB. It may make our analysis more conservative than it could be, see test
1837330f729Sjoerg     // @nested and @nested_no_throw in test/Analysis/MustExecute/loop-header.ll.
1847330f729Sjoerg     // We can ignore backedge of all loops containing BB to get a sligtly more
1857330f729Sjoerg     // optimistic result.
1867330f729Sjoerg     for (auto *PredPred : predecessors(Pred))
1877330f729Sjoerg       if (Predecessors.insert(PredPred).second)
1887330f729Sjoerg         WorkList.push_back(PredPred);
1897330f729Sjoerg   }
1907330f729Sjoerg }
1917330f729Sjoerg 
allLoopPathsLeadToBlock(const Loop * CurLoop,const BasicBlock * BB,const DominatorTree * DT) const1927330f729Sjoerg bool LoopSafetyInfo::allLoopPathsLeadToBlock(const Loop *CurLoop,
1937330f729Sjoerg                                              const BasicBlock *BB,
1947330f729Sjoerg                                              const DominatorTree *DT) const {
1957330f729Sjoerg   assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
1967330f729Sjoerg 
1977330f729Sjoerg   // Fast path: header is always reached once the loop is entered.
1987330f729Sjoerg   if (BB == CurLoop->getHeader())
1997330f729Sjoerg     return true;
2007330f729Sjoerg 
2017330f729Sjoerg   // Collect all transitive predecessors of BB in the same loop. This set will
2027330f729Sjoerg   // be a subset of the blocks within the loop.
2037330f729Sjoerg   SmallPtrSet<const BasicBlock *, 4> Predecessors;
2047330f729Sjoerg   collectTransitivePredecessors(CurLoop, BB, Predecessors);
2057330f729Sjoerg 
2067330f729Sjoerg   // Make sure that all successors of, all predecessors of BB which are not
2077330f729Sjoerg   // dominated by BB, are either:
2087330f729Sjoerg   // 1) BB,
2097330f729Sjoerg   // 2) Also predecessors of BB,
2107330f729Sjoerg   // 3) Exit blocks which are not taken on 1st iteration.
2117330f729Sjoerg   // Memoize blocks we've already checked.
2127330f729Sjoerg   SmallPtrSet<const BasicBlock *, 4> CheckedSuccessors;
2137330f729Sjoerg   for (auto *Pred : Predecessors) {
2147330f729Sjoerg     // Predecessor block may throw, so it has a side exit.
2157330f729Sjoerg     if (blockMayThrow(Pred))
2167330f729Sjoerg       return false;
2177330f729Sjoerg 
2187330f729Sjoerg     // BB dominates Pred, so if Pred runs, BB must run.
2197330f729Sjoerg     // This is true when Pred is a loop latch.
2207330f729Sjoerg     if (DT->dominates(BB, Pred))
2217330f729Sjoerg       continue;
2227330f729Sjoerg 
2237330f729Sjoerg     for (auto *Succ : successors(Pred))
2247330f729Sjoerg       if (CheckedSuccessors.insert(Succ).second &&
2257330f729Sjoerg           Succ != BB && !Predecessors.count(Succ))
2267330f729Sjoerg         // By discharging conditions that are not executed on the 1st iteration,
2277330f729Sjoerg         // we guarantee that *at least* on the first iteration all paths from
2287330f729Sjoerg         // header that *may* execute will lead us to the block of interest. So
2297330f729Sjoerg         // that if we had virtually peeled one iteration away, in this peeled
2307330f729Sjoerg         // iteration the set of predecessors would contain only paths from
2317330f729Sjoerg         // header to BB without any exiting edges that may execute.
2327330f729Sjoerg         //
2337330f729Sjoerg         // TODO: We only do it for exiting edges currently. We could use the
2347330f729Sjoerg         // same function to skip some of the edges within the loop if we know
2357330f729Sjoerg         // that they will not be taken on the 1st iteration.
2367330f729Sjoerg         //
2377330f729Sjoerg         // TODO: If we somehow know the number of iterations in loop, the same
2387330f729Sjoerg         // check may be done for any arbitrary N-th iteration as long as N is
2397330f729Sjoerg         // not greater than minimum number of iterations in this loop.
2407330f729Sjoerg         if (CurLoop->contains(Succ) ||
2417330f729Sjoerg             !CanProveNotTakenFirstIteration(Succ, DT, CurLoop))
2427330f729Sjoerg           return false;
2437330f729Sjoerg   }
2447330f729Sjoerg 
2457330f729Sjoerg   // All predecessors can only lead us to BB.
2467330f729Sjoerg   return true;
2477330f729Sjoerg }
2487330f729Sjoerg 
2497330f729Sjoerg /// Returns true if the instruction in a loop is guaranteed to execute at least
2507330f729Sjoerg /// once.
isGuaranteedToExecute(const Instruction & Inst,const DominatorTree * DT,const Loop * CurLoop) const2517330f729Sjoerg bool SimpleLoopSafetyInfo::isGuaranteedToExecute(const Instruction &Inst,
2527330f729Sjoerg                                                  const DominatorTree *DT,
2537330f729Sjoerg                                                  const Loop *CurLoop) const {
2547330f729Sjoerg   // If the instruction is in the header block for the loop (which is very
2557330f729Sjoerg   // common), it is always guaranteed to dominate the exit blocks.  Since this
2567330f729Sjoerg   // is a common case, and can save some work, check it now.
2577330f729Sjoerg   if (Inst.getParent() == CurLoop->getHeader())
2587330f729Sjoerg     // If there's a throw in the header block, we can't guarantee we'll reach
2597330f729Sjoerg     // Inst unless we can prove that Inst comes before the potential implicit
2607330f729Sjoerg     // exit.  At the moment, we use a (cheap) hack for the common case where
2617330f729Sjoerg     // the instruction of interest is the first one in the block.
2627330f729Sjoerg     return !HeaderMayThrow ||
2637330f729Sjoerg            Inst.getParent()->getFirstNonPHIOrDbg() == &Inst;
2647330f729Sjoerg 
2657330f729Sjoerg   // If there is a path from header to exit or latch that doesn't lead to our
2667330f729Sjoerg   // instruction's block, return false.
2677330f729Sjoerg   return allLoopPathsLeadToBlock(CurLoop, Inst.getParent(), DT);
2687330f729Sjoerg }
2697330f729Sjoerg 
isGuaranteedToExecute(const Instruction & Inst,const DominatorTree * DT,const Loop * CurLoop) const2707330f729Sjoerg bool ICFLoopSafetyInfo::isGuaranteedToExecute(const Instruction &Inst,
2717330f729Sjoerg                                               const DominatorTree *DT,
2727330f729Sjoerg                                               const Loop *CurLoop) const {
2737330f729Sjoerg   return !ICF.isDominatedByICFIFromSameBlock(&Inst) &&
2747330f729Sjoerg          allLoopPathsLeadToBlock(CurLoop, Inst.getParent(), DT);
2757330f729Sjoerg }
2767330f729Sjoerg 
doesNotWriteMemoryBefore(const BasicBlock * BB,const Loop * CurLoop) const2777330f729Sjoerg bool ICFLoopSafetyInfo::doesNotWriteMemoryBefore(const BasicBlock *BB,
2787330f729Sjoerg                                                  const Loop *CurLoop) const {
2797330f729Sjoerg   assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
2807330f729Sjoerg 
2817330f729Sjoerg   // Fast path: there are no instructions before header.
2827330f729Sjoerg   if (BB == CurLoop->getHeader())
2837330f729Sjoerg     return true;
2847330f729Sjoerg 
2857330f729Sjoerg   // Collect all transitive predecessors of BB in the same loop. This set will
2867330f729Sjoerg   // be a subset of the blocks within the loop.
2877330f729Sjoerg   SmallPtrSet<const BasicBlock *, 4> Predecessors;
2887330f729Sjoerg   collectTransitivePredecessors(CurLoop, BB, Predecessors);
2897330f729Sjoerg   // Find if there any instruction in either predecessor that could write
2907330f729Sjoerg   // to memory.
2917330f729Sjoerg   for (auto *Pred : Predecessors)
2927330f729Sjoerg     if (MW.mayWriteToMemory(Pred))
2937330f729Sjoerg       return false;
2947330f729Sjoerg   return true;
2957330f729Sjoerg }
2967330f729Sjoerg 
doesNotWriteMemoryBefore(const Instruction & I,const Loop * CurLoop) const2977330f729Sjoerg bool ICFLoopSafetyInfo::doesNotWriteMemoryBefore(const Instruction &I,
2987330f729Sjoerg                                                  const Loop *CurLoop) const {
2997330f729Sjoerg   auto *BB = I.getParent();
3007330f729Sjoerg   assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
3017330f729Sjoerg   return !MW.isDominatedByMemoryWriteFromSameBlock(&I) &&
3027330f729Sjoerg          doesNotWriteMemoryBefore(BB, CurLoop);
3037330f729Sjoerg }
3047330f729Sjoerg 
3057330f729Sjoerg namespace {
3067330f729Sjoerg struct MustExecutePrinter : public FunctionPass {
3077330f729Sjoerg 
3087330f729Sjoerg   static char ID; // Pass identification, replacement for typeid
MustExecutePrinter__anon0d8be90a0111::MustExecutePrinter3097330f729Sjoerg   MustExecutePrinter() : FunctionPass(ID) {
3107330f729Sjoerg     initializeMustExecutePrinterPass(*PassRegistry::getPassRegistry());
3117330f729Sjoerg   }
getAnalysisUsage__anon0d8be90a0111::MustExecutePrinter3127330f729Sjoerg   void getAnalysisUsage(AnalysisUsage &AU) const override {
3137330f729Sjoerg     AU.setPreservesAll();
3147330f729Sjoerg     AU.addRequired<DominatorTreeWrapperPass>();
3157330f729Sjoerg     AU.addRequired<LoopInfoWrapperPass>();
3167330f729Sjoerg   }
3177330f729Sjoerg   bool runOnFunction(Function &F) override;
3187330f729Sjoerg };
3197330f729Sjoerg struct MustBeExecutedContextPrinter : public ModulePass {
3207330f729Sjoerg   static char ID;
3217330f729Sjoerg 
MustBeExecutedContextPrinter__anon0d8be90a0111::MustBeExecutedContextPrinter3227330f729Sjoerg   MustBeExecutedContextPrinter() : ModulePass(ID) {
323*82d56013Sjoerg     initializeMustBeExecutedContextPrinterPass(
324*82d56013Sjoerg         *PassRegistry::getPassRegistry());
3257330f729Sjoerg   }
getAnalysisUsage__anon0d8be90a0111::MustBeExecutedContextPrinter3267330f729Sjoerg   void getAnalysisUsage(AnalysisUsage &AU) const override {
3277330f729Sjoerg     AU.setPreservesAll();
3287330f729Sjoerg   }
3297330f729Sjoerg   bool runOnModule(Module &M) override;
3307330f729Sjoerg };
3317330f729Sjoerg }
3327330f729Sjoerg 
3337330f729Sjoerg char MustExecutePrinter::ID = 0;
3347330f729Sjoerg INITIALIZE_PASS_BEGIN(MustExecutePrinter, "print-mustexecute",
3357330f729Sjoerg                       "Instructions which execute on loop entry", false, true)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)3367330f729Sjoerg INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3377330f729Sjoerg INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
3387330f729Sjoerg INITIALIZE_PASS_END(MustExecutePrinter, "print-mustexecute",
3397330f729Sjoerg                     "Instructions which execute on loop entry", false, true)
3407330f729Sjoerg 
3417330f729Sjoerg FunctionPass *llvm::createMustExecutePrinter() {
3427330f729Sjoerg   return new MustExecutePrinter();
3437330f729Sjoerg }
3447330f729Sjoerg 
3457330f729Sjoerg char MustBeExecutedContextPrinter::ID = 0;
346*82d56013Sjoerg INITIALIZE_PASS_BEGIN(MustBeExecutedContextPrinter,
347*82d56013Sjoerg                       "print-must-be-executed-contexts",
348*82d56013Sjoerg                       "print the must-be-executed-context for all instructions",
349*82d56013Sjoerg                       false, true)
INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)3507330f729Sjoerg INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
3517330f729Sjoerg INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3527330f729Sjoerg INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
3537330f729Sjoerg INITIALIZE_PASS_END(MustBeExecutedContextPrinter,
3547330f729Sjoerg                     "print-must-be-executed-contexts",
355*82d56013Sjoerg                     "print the must-be-executed-context for all instructions",
3567330f729Sjoerg                     false, true)
3577330f729Sjoerg 
3587330f729Sjoerg ModulePass *llvm::createMustBeExecutedContextPrinter() {
3597330f729Sjoerg   return new MustBeExecutedContextPrinter();
3607330f729Sjoerg }
3617330f729Sjoerg 
runOnModule(Module & M)3627330f729Sjoerg bool MustBeExecutedContextPrinter::runOnModule(Module &M) {
363*82d56013Sjoerg   // We provide non-PM analysis here because the old PM doesn't like to query
364*82d56013Sjoerg   // function passes from a module pass.
365*82d56013Sjoerg   SmallVector<std::unique_ptr<PostDominatorTree>, 8> PDTs;
366*82d56013Sjoerg   SmallVector<std::unique_ptr<DominatorTree>, 8> DTs;
367*82d56013Sjoerg   SmallVector<std::unique_ptr<LoopInfo>, 8> LIs;
368*82d56013Sjoerg 
369*82d56013Sjoerg   GetterTy<LoopInfo> LIGetter = [&](const Function &F) {
370*82d56013Sjoerg     DTs.push_back(std::make_unique<DominatorTree>(const_cast<Function &>(F)));
371*82d56013Sjoerg     LIs.push_back(std::make_unique<LoopInfo>(*DTs.back()));
372*82d56013Sjoerg     return LIs.back().get();
373*82d56013Sjoerg   };
374*82d56013Sjoerg   GetterTy<DominatorTree> DTGetter = [&](const Function &F) {
375*82d56013Sjoerg     DTs.push_back(std::make_unique<DominatorTree>(const_cast<Function&>(F)));
376*82d56013Sjoerg     return DTs.back().get();
377*82d56013Sjoerg   };
378*82d56013Sjoerg   GetterTy<PostDominatorTree> PDTGetter = [&](const Function &F) {
379*82d56013Sjoerg     PDTs.push_back(
380*82d56013Sjoerg         std::make_unique<PostDominatorTree>(const_cast<Function &>(F)));
381*82d56013Sjoerg     return PDTs.back().get();
382*82d56013Sjoerg   };
383*82d56013Sjoerg   MustBeExecutedContextExplorer Explorer(
384*82d56013Sjoerg       /* ExploreInterBlock */ true,
385*82d56013Sjoerg       /* ExploreCFGForward */ true,
386*82d56013Sjoerg       /* ExploreCFGBackward */ true, LIGetter, DTGetter, PDTGetter);
387*82d56013Sjoerg 
3887330f729Sjoerg   for (Function &F : M) {
3897330f729Sjoerg     for (Instruction &I : instructions(F)) {
3907330f729Sjoerg       dbgs() << "-- Explore context of: " << I << "\n";
3917330f729Sjoerg       for (const Instruction *CI : Explorer.range(&I))
3927330f729Sjoerg         dbgs() << "  [F: " << CI->getFunction()->getName() << "] " << *CI
3937330f729Sjoerg                << "\n";
3947330f729Sjoerg     }
3957330f729Sjoerg   }
3967330f729Sjoerg 
3977330f729Sjoerg   return false;
3987330f729Sjoerg }
3997330f729Sjoerg 
isMustExecuteIn(const Instruction & I,Loop * L,DominatorTree * DT)4007330f729Sjoerg static bool isMustExecuteIn(const Instruction &I, Loop *L, DominatorTree *DT) {
4017330f729Sjoerg   // TODO: merge these two routines.  For the moment, we display the best
4027330f729Sjoerg   // result obtained by *either* implementation.  This is a bit unfair since no
4037330f729Sjoerg   // caller actually gets the full power at the moment.
4047330f729Sjoerg   SimpleLoopSafetyInfo LSI;
4057330f729Sjoerg   LSI.computeLoopSafetyInfo(L);
4067330f729Sjoerg   return LSI.isGuaranteedToExecute(I, DT, L) ||
4077330f729Sjoerg     isGuaranteedToExecuteForEveryIteration(&I, L);
4087330f729Sjoerg }
4097330f729Sjoerg 
4107330f729Sjoerg namespace {
4117330f729Sjoerg /// An assembly annotator class to print must execute information in
4127330f729Sjoerg /// comments.
4137330f729Sjoerg class MustExecuteAnnotatedWriter : public AssemblyAnnotationWriter {
4147330f729Sjoerg   DenseMap<const Value*, SmallVector<Loop*, 4> > MustExec;
4157330f729Sjoerg 
4167330f729Sjoerg public:
MustExecuteAnnotatedWriter(const Function & F,DominatorTree & DT,LoopInfo & LI)4177330f729Sjoerg   MustExecuteAnnotatedWriter(const Function &F,
4187330f729Sjoerg                              DominatorTree &DT, LoopInfo &LI) {
4197330f729Sjoerg     for (auto &I: instructions(F)) {
4207330f729Sjoerg       Loop *L = LI.getLoopFor(I.getParent());
4217330f729Sjoerg       while (L) {
4227330f729Sjoerg         if (isMustExecuteIn(I, L, &DT)) {
4237330f729Sjoerg           MustExec[&I].push_back(L);
4247330f729Sjoerg         }
4257330f729Sjoerg         L = L->getParentLoop();
4267330f729Sjoerg       };
4277330f729Sjoerg     }
4287330f729Sjoerg   }
MustExecuteAnnotatedWriter(const Module & M,DominatorTree & DT,LoopInfo & LI)4297330f729Sjoerg   MustExecuteAnnotatedWriter(const Module &M,
4307330f729Sjoerg                              DominatorTree &DT, LoopInfo &LI) {
4317330f729Sjoerg     for (auto &F : M)
4327330f729Sjoerg     for (auto &I: instructions(F)) {
4337330f729Sjoerg       Loop *L = LI.getLoopFor(I.getParent());
4347330f729Sjoerg       while (L) {
4357330f729Sjoerg         if (isMustExecuteIn(I, L, &DT)) {
4367330f729Sjoerg           MustExec[&I].push_back(L);
4377330f729Sjoerg         }
4387330f729Sjoerg         L = L->getParentLoop();
4397330f729Sjoerg       };
4407330f729Sjoerg     }
4417330f729Sjoerg   }
4427330f729Sjoerg 
4437330f729Sjoerg 
printInfoComment(const Value & V,formatted_raw_ostream & OS)4447330f729Sjoerg   void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
4457330f729Sjoerg     if (!MustExec.count(&V))
4467330f729Sjoerg       return;
4477330f729Sjoerg 
4487330f729Sjoerg     const auto &Loops = MustExec.lookup(&V);
4497330f729Sjoerg     const auto NumLoops = Loops.size();
4507330f729Sjoerg     if (NumLoops > 1)
4517330f729Sjoerg       OS << " ; (mustexec in " << NumLoops << " loops: ";
4527330f729Sjoerg     else
4537330f729Sjoerg       OS << " ; (mustexec in: ";
4547330f729Sjoerg 
455*82d56013Sjoerg     ListSeparator LS;
456*82d56013Sjoerg     for (const Loop *L : Loops)
457*82d56013Sjoerg       OS << LS << L->getHeader()->getName();
4587330f729Sjoerg     OS << ")";
4597330f729Sjoerg   }
4607330f729Sjoerg };
4617330f729Sjoerg } // namespace
4627330f729Sjoerg 
runOnFunction(Function & F)4637330f729Sjoerg bool MustExecutePrinter::runOnFunction(Function &F) {
4647330f729Sjoerg   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4657330f729Sjoerg   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4667330f729Sjoerg 
4677330f729Sjoerg   MustExecuteAnnotatedWriter Writer(F, DT, LI);
4687330f729Sjoerg   F.print(dbgs(), &Writer);
4697330f729Sjoerg 
4707330f729Sjoerg   return false;
4717330f729Sjoerg }
4727330f729Sjoerg 
473*82d56013Sjoerg /// Return true if \p L might be an endless loop.
maybeEndlessLoop(const Loop & L)474*82d56013Sjoerg static bool maybeEndlessLoop(const Loop &L) {
475*82d56013Sjoerg   if (L.getHeader()->getParent()->hasFnAttribute(Attribute::WillReturn))
476*82d56013Sjoerg     return false;
477*82d56013Sjoerg   // TODO: Actually try to prove it is not.
478*82d56013Sjoerg   // TODO: If maybeEndlessLoop is going to be expensive, cache it.
479*82d56013Sjoerg   return true;
480*82d56013Sjoerg }
481*82d56013Sjoerg 
mayContainIrreducibleControl(const Function & F,const LoopInfo * LI)482*82d56013Sjoerg bool llvm::mayContainIrreducibleControl(const Function &F, const LoopInfo *LI) {
483*82d56013Sjoerg   if (!LI)
484*82d56013Sjoerg     return false;
485*82d56013Sjoerg   using RPOTraversal = ReversePostOrderTraversal<const Function *>;
486*82d56013Sjoerg   RPOTraversal FuncRPOT(&F);
487*82d56013Sjoerg   return containsIrreducibleCFG<const BasicBlock *, const RPOTraversal,
488*82d56013Sjoerg                                 const LoopInfo>(FuncRPOT, *LI);
489*82d56013Sjoerg }
490*82d56013Sjoerg 
491*82d56013Sjoerg /// Lookup \p Key in \p Map and return the result, potentially after
492*82d56013Sjoerg /// initializing the optional through \p Fn(\p args).
493*82d56013Sjoerg template <typename K, typename V, typename FnTy, typename... ArgsTy>
getOrCreateCachedOptional(K Key,DenseMap<K,Optional<V>> & Map,FnTy && Fn,ArgsTy &&...args)494*82d56013Sjoerg static V getOrCreateCachedOptional(K Key, DenseMap<K, Optional<V>> &Map,
495*82d56013Sjoerg                                    FnTy &&Fn, ArgsTy&&... args) {
496*82d56013Sjoerg   Optional<V> &OptVal = Map[Key];
497*82d56013Sjoerg   if (!OptVal.hasValue())
498*82d56013Sjoerg     OptVal = Fn(std::forward<ArgsTy>(args)...);
499*82d56013Sjoerg   return OptVal.getValue();
500*82d56013Sjoerg }
501*82d56013Sjoerg 
502*82d56013Sjoerg const BasicBlock *
findForwardJoinPoint(const BasicBlock * InitBB)503*82d56013Sjoerg MustBeExecutedContextExplorer::findForwardJoinPoint(const BasicBlock *InitBB) {
504*82d56013Sjoerg   const LoopInfo *LI = LIGetter(*InitBB->getParent());
505*82d56013Sjoerg   const PostDominatorTree *PDT = PDTGetter(*InitBB->getParent());
506*82d56013Sjoerg 
507*82d56013Sjoerg   LLVM_DEBUG(dbgs() << "\tFind forward join point for " << InitBB->getName()
508*82d56013Sjoerg                     << (LI ? " [LI]" : "") << (PDT ? " [PDT]" : ""));
509*82d56013Sjoerg 
510*82d56013Sjoerg   const Function &F = *InitBB->getParent();
511*82d56013Sjoerg   const Loop *L = LI ? LI->getLoopFor(InitBB) : nullptr;
512*82d56013Sjoerg   const BasicBlock *HeaderBB = L ? L->getHeader() : InitBB;
513*82d56013Sjoerg   bool WillReturnAndNoThrow = (F.hasFnAttribute(Attribute::WillReturn) ||
514*82d56013Sjoerg                                (L && !maybeEndlessLoop(*L))) &&
515*82d56013Sjoerg                               F.doesNotThrow();
516*82d56013Sjoerg   LLVM_DEBUG(dbgs() << (L ? " [in loop]" : "")
517*82d56013Sjoerg                     << (WillReturnAndNoThrow ? " [WillReturn] [NoUnwind]" : "")
518*82d56013Sjoerg                     << "\n");
519*82d56013Sjoerg 
520*82d56013Sjoerg   // Determine the adjacent blocks in the given direction but exclude (self)
521*82d56013Sjoerg   // loops under certain circumstances.
522*82d56013Sjoerg   SmallVector<const BasicBlock *, 8> Worklist;
523*82d56013Sjoerg   for (const BasicBlock *SuccBB : successors(InitBB)) {
524*82d56013Sjoerg     bool IsLatch = SuccBB == HeaderBB;
525*82d56013Sjoerg     // Loop latches are ignored in forward propagation if the loop cannot be
526*82d56013Sjoerg     // endless and may not throw: control has to go somewhere.
527*82d56013Sjoerg     if (!WillReturnAndNoThrow || !IsLatch)
528*82d56013Sjoerg       Worklist.push_back(SuccBB);
529*82d56013Sjoerg   }
530*82d56013Sjoerg   LLVM_DEBUG(dbgs() << "\t\t#Worklist: " << Worklist.size() << "\n");
531*82d56013Sjoerg 
532*82d56013Sjoerg   // If there are no other adjacent blocks, there is no join point.
533*82d56013Sjoerg   if (Worklist.empty())
534*82d56013Sjoerg     return nullptr;
535*82d56013Sjoerg 
536*82d56013Sjoerg   // If there is one adjacent block, it is the join point.
537*82d56013Sjoerg   if (Worklist.size() == 1)
538*82d56013Sjoerg     return Worklist[0];
539*82d56013Sjoerg 
540*82d56013Sjoerg   // Try to determine a join block through the help of the post-dominance
541*82d56013Sjoerg   // tree. If no tree was provided, we perform simple pattern matching for one
542*82d56013Sjoerg   // block conditionals and one block loops only.
543*82d56013Sjoerg   const BasicBlock *JoinBB = nullptr;
544*82d56013Sjoerg   if (PDT)
545*82d56013Sjoerg     if (const auto *InitNode = PDT->getNode(InitBB))
546*82d56013Sjoerg       if (const auto *IDomNode = InitNode->getIDom())
547*82d56013Sjoerg         JoinBB = IDomNode->getBlock();
548*82d56013Sjoerg 
549*82d56013Sjoerg   if (!JoinBB && Worklist.size() == 2) {
550*82d56013Sjoerg     const BasicBlock *Succ0 = Worklist[0];
551*82d56013Sjoerg     const BasicBlock *Succ1 = Worklist[1];
552*82d56013Sjoerg     const BasicBlock *Succ0UniqueSucc = Succ0->getUniqueSuccessor();
553*82d56013Sjoerg     const BasicBlock *Succ1UniqueSucc = Succ1->getUniqueSuccessor();
554*82d56013Sjoerg     if (Succ0UniqueSucc == InitBB) {
555*82d56013Sjoerg       // InitBB -> Succ0 -> InitBB
556*82d56013Sjoerg       // InitBB -> Succ1  = JoinBB
557*82d56013Sjoerg       JoinBB = Succ1;
558*82d56013Sjoerg     } else if (Succ1UniqueSucc == InitBB) {
559*82d56013Sjoerg       // InitBB -> Succ1 -> InitBB
560*82d56013Sjoerg       // InitBB -> Succ0  = JoinBB
561*82d56013Sjoerg       JoinBB = Succ0;
562*82d56013Sjoerg     } else if (Succ0 == Succ1UniqueSucc) {
563*82d56013Sjoerg       // InitBB ->          Succ0 = JoinBB
564*82d56013Sjoerg       // InitBB -> Succ1 -> Succ0 = JoinBB
565*82d56013Sjoerg       JoinBB = Succ0;
566*82d56013Sjoerg     } else if (Succ1 == Succ0UniqueSucc) {
567*82d56013Sjoerg       // InitBB -> Succ0 -> Succ1 = JoinBB
568*82d56013Sjoerg       // InitBB ->          Succ1 = JoinBB
569*82d56013Sjoerg       JoinBB = Succ1;
570*82d56013Sjoerg     } else if (Succ0UniqueSucc == Succ1UniqueSucc) {
571*82d56013Sjoerg       // InitBB -> Succ0 -> JoinBB
572*82d56013Sjoerg       // InitBB -> Succ1 -> JoinBB
573*82d56013Sjoerg       JoinBB = Succ0UniqueSucc;
574*82d56013Sjoerg     }
575*82d56013Sjoerg   }
576*82d56013Sjoerg 
577*82d56013Sjoerg   if (!JoinBB && L)
578*82d56013Sjoerg     JoinBB = L->getUniqueExitBlock();
579*82d56013Sjoerg 
580*82d56013Sjoerg   if (!JoinBB)
581*82d56013Sjoerg     return nullptr;
582*82d56013Sjoerg 
583*82d56013Sjoerg   LLVM_DEBUG(dbgs() << "\t\tJoin block candidate: " << JoinBB->getName() << "\n");
584*82d56013Sjoerg 
585*82d56013Sjoerg   // In forward direction we check if control will for sure reach JoinBB from
586*82d56013Sjoerg   // InitBB, thus it can not be "stopped" along the way. Ways to "stop" control
587*82d56013Sjoerg   // are: infinite loops and instructions that do not necessarily transfer
588*82d56013Sjoerg   // execution to their successor. To check for them we traverse the CFG from
589*82d56013Sjoerg   // the adjacent blocks to the JoinBB, looking at all intermediate blocks.
590*82d56013Sjoerg 
591*82d56013Sjoerg   // If we know the function is "will-return" and "no-throw" there is no need
592*82d56013Sjoerg   // for futher checks.
593*82d56013Sjoerg   if (!F.hasFnAttribute(Attribute::WillReturn) || !F.doesNotThrow()) {
594*82d56013Sjoerg 
595*82d56013Sjoerg     auto BlockTransfersExecutionToSuccessor = [](const BasicBlock *BB) {
596*82d56013Sjoerg       return isGuaranteedToTransferExecutionToSuccessor(BB);
597*82d56013Sjoerg     };
598*82d56013Sjoerg 
599*82d56013Sjoerg     SmallPtrSet<const BasicBlock *, 16> Visited;
600*82d56013Sjoerg     while (!Worklist.empty()) {
601*82d56013Sjoerg       const BasicBlock *ToBB = Worklist.pop_back_val();
602*82d56013Sjoerg       if (ToBB == JoinBB)
603*82d56013Sjoerg         continue;
604*82d56013Sjoerg 
605*82d56013Sjoerg       // Make sure all loops in-between are finite.
606*82d56013Sjoerg       if (!Visited.insert(ToBB).second) {
607*82d56013Sjoerg         if (!F.hasFnAttribute(Attribute::WillReturn)) {
608*82d56013Sjoerg           if (!LI)
609*82d56013Sjoerg             return nullptr;
610*82d56013Sjoerg 
611*82d56013Sjoerg           bool MayContainIrreducibleControl = getOrCreateCachedOptional(
612*82d56013Sjoerg               &F, IrreducibleControlMap, mayContainIrreducibleControl, F, LI);
613*82d56013Sjoerg           if (MayContainIrreducibleControl)
614*82d56013Sjoerg             return nullptr;
615*82d56013Sjoerg 
616*82d56013Sjoerg           const Loop *L = LI->getLoopFor(ToBB);
617*82d56013Sjoerg           if (L && maybeEndlessLoop(*L))
618*82d56013Sjoerg             return nullptr;
619*82d56013Sjoerg         }
620*82d56013Sjoerg 
621*82d56013Sjoerg         continue;
622*82d56013Sjoerg       }
623*82d56013Sjoerg 
624*82d56013Sjoerg       // Make sure the block has no instructions that could stop control
625*82d56013Sjoerg       // transfer.
626*82d56013Sjoerg       bool TransfersExecution = getOrCreateCachedOptional(
627*82d56013Sjoerg           ToBB, BlockTransferMap, BlockTransfersExecutionToSuccessor, ToBB);
628*82d56013Sjoerg       if (!TransfersExecution)
629*82d56013Sjoerg         return nullptr;
630*82d56013Sjoerg 
631*82d56013Sjoerg       append_range(Worklist, successors(ToBB));
632*82d56013Sjoerg     }
633*82d56013Sjoerg   }
634*82d56013Sjoerg 
635*82d56013Sjoerg   LLVM_DEBUG(dbgs() << "\tJoin block: " << JoinBB->getName() << "\n");
636*82d56013Sjoerg   return JoinBB;
637*82d56013Sjoerg }
638*82d56013Sjoerg const BasicBlock *
findBackwardJoinPoint(const BasicBlock * InitBB)639*82d56013Sjoerg MustBeExecutedContextExplorer::findBackwardJoinPoint(const BasicBlock *InitBB) {
640*82d56013Sjoerg   const LoopInfo *LI = LIGetter(*InitBB->getParent());
641*82d56013Sjoerg   const DominatorTree *DT = DTGetter(*InitBB->getParent());
642*82d56013Sjoerg   LLVM_DEBUG(dbgs() << "\tFind backward join point for " << InitBB->getName()
643*82d56013Sjoerg                     << (LI ? " [LI]" : "") << (DT ? " [DT]" : ""));
644*82d56013Sjoerg 
645*82d56013Sjoerg   // Try to determine a join block through the help of the dominance tree. If no
646*82d56013Sjoerg   // tree was provided, we perform simple pattern matching for one block
647*82d56013Sjoerg   // conditionals only.
648*82d56013Sjoerg   if (DT)
649*82d56013Sjoerg     if (const auto *InitNode = DT->getNode(InitBB))
650*82d56013Sjoerg       if (const auto *IDomNode = InitNode->getIDom())
651*82d56013Sjoerg         return IDomNode->getBlock();
652*82d56013Sjoerg 
653*82d56013Sjoerg   const Loop *L = LI ? LI->getLoopFor(InitBB) : nullptr;
654*82d56013Sjoerg   const BasicBlock *HeaderBB = L ? L->getHeader() : nullptr;
655*82d56013Sjoerg 
656*82d56013Sjoerg   // Determine the predecessor blocks but ignore backedges.
657*82d56013Sjoerg   SmallVector<const BasicBlock *, 8> Worklist;
658*82d56013Sjoerg   for (const BasicBlock *PredBB : predecessors(InitBB)) {
659*82d56013Sjoerg     bool IsBackedge =
660*82d56013Sjoerg         (PredBB == InitBB) || (HeaderBB == InitBB && L->contains(PredBB));
661*82d56013Sjoerg     // Loop backedges are ignored in backwards propagation: control has to come
662*82d56013Sjoerg     // from somewhere.
663*82d56013Sjoerg     if (!IsBackedge)
664*82d56013Sjoerg       Worklist.push_back(PredBB);
665*82d56013Sjoerg   }
666*82d56013Sjoerg 
667*82d56013Sjoerg   // If there are no other predecessor blocks, there is no join point.
668*82d56013Sjoerg   if (Worklist.empty())
669*82d56013Sjoerg     return nullptr;
670*82d56013Sjoerg 
671*82d56013Sjoerg   // If there is one predecessor block, it is the join point.
672*82d56013Sjoerg   if (Worklist.size() == 1)
673*82d56013Sjoerg     return Worklist[0];
674*82d56013Sjoerg 
675*82d56013Sjoerg   const BasicBlock *JoinBB = nullptr;
676*82d56013Sjoerg   if (Worklist.size() == 2) {
677*82d56013Sjoerg     const BasicBlock *Pred0 = Worklist[0];
678*82d56013Sjoerg     const BasicBlock *Pred1 = Worklist[1];
679*82d56013Sjoerg     const BasicBlock *Pred0UniquePred = Pred0->getUniquePredecessor();
680*82d56013Sjoerg     const BasicBlock *Pred1UniquePred = Pred1->getUniquePredecessor();
681*82d56013Sjoerg     if (Pred0 == Pred1UniquePred) {
682*82d56013Sjoerg       // InitBB <-          Pred0 = JoinBB
683*82d56013Sjoerg       // InitBB <- Pred1 <- Pred0 = JoinBB
684*82d56013Sjoerg       JoinBB = Pred0;
685*82d56013Sjoerg     } else if (Pred1 == Pred0UniquePred) {
686*82d56013Sjoerg       // InitBB <- Pred0 <- Pred1 = JoinBB
687*82d56013Sjoerg       // InitBB <-          Pred1 = JoinBB
688*82d56013Sjoerg       JoinBB = Pred1;
689*82d56013Sjoerg     } else if (Pred0UniquePred == Pred1UniquePred) {
690*82d56013Sjoerg       // InitBB <- Pred0 <- JoinBB
691*82d56013Sjoerg       // InitBB <- Pred1 <- JoinBB
692*82d56013Sjoerg       JoinBB = Pred0UniquePred;
693*82d56013Sjoerg     }
694*82d56013Sjoerg   }
695*82d56013Sjoerg 
696*82d56013Sjoerg   if (!JoinBB && L)
697*82d56013Sjoerg     JoinBB = L->getHeader();
698*82d56013Sjoerg 
699*82d56013Sjoerg   // In backwards direction there is no need to show termination of previous
700*82d56013Sjoerg   // instructions. If they do not terminate, the code afterward is dead, making
701*82d56013Sjoerg   // any information/transformation correct anyway.
702*82d56013Sjoerg   return JoinBB;
703*82d56013Sjoerg }
704*82d56013Sjoerg 
7057330f729Sjoerg const Instruction *
getMustBeExecutedNextInstruction(MustBeExecutedIterator & It,const Instruction * PP)7067330f729Sjoerg MustBeExecutedContextExplorer::getMustBeExecutedNextInstruction(
7077330f729Sjoerg     MustBeExecutedIterator &It, const Instruction *PP) {
7087330f729Sjoerg   if (!PP)
7097330f729Sjoerg     return PP;
7107330f729Sjoerg   LLVM_DEBUG(dbgs() << "Find next instruction for " << *PP << "\n");
7117330f729Sjoerg 
7127330f729Sjoerg   // If we explore only inside a given basic block we stop at terminators.
7137330f729Sjoerg   if (!ExploreInterBlock && PP->isTerminator()) {
7147330f729Sjoerg     LLVM_DEBUG(dbgs() << "\tReached terminator in intra-block mode, done\n");
7157330f729Sjoerg     return nullptr;
7167330f729Sjoerg   }
7177330f729Sjoerg 
7187330f729Sjoerg   // If we do not traverse the call graph we check if we can make progress in
7197330f729Sjoerg   // the current function. First, check if the instruction is guaranteed to
7207330f729Sjoerg   // transfer execution to the successor.
7217330f729Sjoerg   bool TransfersExecution = isGuaranteedToTransferExecutionToSuccessor(PP);
7227330f729Sjoerg   if (!TransfersExecution)
7237330f729Sjoerg     return nullptr;
7247330f729Sjoerg 
7257330f729Sjoerg   // If this is not a terminator we know that there is a single instruction
7267330f729Sjoerg   // after this one that is executed next if control is transfered. If not,
7277330f729Sjoerg   // we can try to go back to a call site we entered earlier. If none exists, we
7287330f729Sjoerg   // do not know any instruction that has to be executd next.
7297330f729Sjoerg   if (!PP->isTerminator()) {
7307330f729Sjoerg     const Instruction *NextPP = PP->getNextNode();
7317330f729Sjoerg     LLVM_DEBUG(dbgs() << "\tIntermediate instruction does transfer control\n");
7327330f729Sjoerg     return NextPP;
7337330f729Sjoerg   }
7347330f729Sjoerg 
7357330f729Sjoerg   // Finally, we have to handle terminators, trivial ones first.
7367330f729Sjoerg   assert(PP->isTerminator() && "Expected a terminator!");
7377330f729Sjoerg 
7387330f729Sjoerg   // A terminator without a successor is not handled yet.
7397330f729Sjoerg   if (PP->getNumSuccessors() == 0) {
7407330f729Sjoerg     LLVM_DEBUG(dbgs() << "\tUnhandled terminator\n");
7417330f729Sjoerg     return nullptr;
7427330f729Sjoerg   }
7437330f729Sjoerg 
7447330f729Sjoerg   // A terminator with a single successor, we will continue at the beginning of
7457330f729Sjoerg   // that one.
7467330f729Sjoerg   if (PP->getNumSuccessors() == 1) {
7477330f729Sjoerg     LLVM_DEBUG(
7487330f729Sjoerg         dbgs() << "\tUnconditional terminator, continue with successor\n");
7497330f729Sjoerg     return &PP->getSuccessor(0)->front();
7507330f729Sjoerg   }
7517330f729Sjoerg 
752*82d56013Sjoerg   // Multiple successors mean we need to find the join point where control flow
753*82d56013Sjoerg   // converges again. We use the findForwardJoinPoint helper function with
754*82d56013Sjoerg   // information about the function and helper analyses, if available.
755*82d56013Sjoerg   if (const BasicBlock *JoinBB = findForwardJoinPoint(PP->getParent()))
756*82d56013Sjoerg     return &JoinBB->front();
757*82d56013Sjoerg 
758*82d56013Sjoerg   LLVM_DEBUG(dbgs() << "\tNo join point found\n");
759*82d56013Sjoerg   return nullptr;
760*82d56013Sjoerg }
761*82d56013Sjoerg 
762*82d56013Sjoerg const Instruction *
getMustBeExecutedPrevInstruction(MustBeExecutedIterator & It,const Instruction * PP)763*82d56013Sjoerg MustBeExecutedContextExplorer::getMustBeExecutedPrevInstruction(
764*82d56013Sjoerg     MustBeExecutedIterator &It, const Instruction *PP) {
765*82d56013Sjoerg   if (!PP)
766*82d56013Sjoerg     return PP;
767*82d56013Sjoerg 
768*82d56013Sjoerg   bool IsFirst = !(PP->getPrevNode());
769*82d56013Sjoerg   LLVM_DEBUG(dbgs() << "Find next instruction for " << *PP
770*82d56013Sjoerg                     << (IsFirst ? " [IsFirst]" : "") << "\n");
771*82d56013Sjoerg 
772*82d56013Sjoerg   // If we explore only inside a given basic block we stop at the first
773*82d56013Sjoerg   // instruction.
774*82d56013Sjoerg   if (!ExploreInterBlock && IsFirst) {
775*82d56013Sjoerg     LLVM_DEBUG(dbgs() << "\tReached block front in intra-block mode, done\n");
776*82d56013Sjoerg     return nullptr;
777*82d56013Sjoerg   }
778*82d56013Sjoerg 
779*82d56013Sjoerg   // The block and function that contains the current position.
780*82d56013Sjoerg   const BasicBlock *PPBlock = PP->getParent();
781*82d56013Sjoerg 
782*82d56013Sjoerg   // If we are inside a block we know what instruction was executed before, the
783*82d56013Sjoerg   // previous one.
784*82d56013Sjoerg   if (!IsFirst) {
785*82d56013Sjoerg     const Instruction *PrevPP = PP->getPrevNode();
786*82d56013Sjoerg     LLVM_DEBUG(
787*82d56013Sjoerg         dbgs() << "\tIntermediate instruction, continue with previous\n");
788*82d56013Sjoerg     // We did not enter a callee so we simply return the previous instruction.
789*82d56013Sjoerg     return PrevPP;
790*82d56013Sjoerg   }
791*82d56013Sjoerg 
792*82d56013Sjoerg   // Finally, we have to handle the case where the program point is the first in
793*82d56013Sjoerg   // a block but not in the function. We use the findBackwardJoinPoint helper
794*82d56013Sjoerg   // function with information about the function and helper analyses, if
795*82d56013Sjoerg   // available.
796*82d56013Sjoerg   if (const BasicBlock *JoinBB = findBackwardJoinPoint(PPBlock))
797*82d56013Sjoerg     return &JoinBB->back();
798*82d56013Sjoerg 
7997330f729Sjoerg   LLVM_DEBUG(dbgs() << "\tNo join point found\n");
8007330f729Sjoerg   return nullptr;
8017330f729Sjoerg }
8027330f729Sjoerg 
MustBeExecutedIterator(MustBeExecutedContextExplorer & Explorer,const Instruction * I)8037330f729Sjoerg MustBeExecutedIterator::MustBeExecutedIterator(
8047330f729Sjoerg     MustBeExecutedContextExplorer &Explorer, const Instruction *I)
8057330f729Sjoerg     : Explorer(Explorer), CurInst(I) {
8067330f729Sjoerg   reset(I);
8077330f729Sjoerg }
8087330f729Sjoerg 
reset(const Instruction * I)8097330f729Sjoerg void MustBeExecutedIterator::reset(const Instruction *I) {
8107330f729Sjoerg   Visited.clear();
811*82d56013Sjoerg   resetInstruction(I);
812*82d56013Sjoerg }
813*82d56013Sjoerg 
resetInstruction(const Instruction * I)814*82d56013Sjoerg void MustBeExecutedIterator::resetInstruction(const Instruction *I) {
815*82d56013Sjoerg   CurInst = I;
816*82d56013Sjoerg   Head = Tail = nullptr;
817*82d56013Sjoerg   Visited.insert({I, ExplorationDirection::FORWARD});
818*82d56013Sjoerg   Visited.insert({I, ExplorationDirection::BACKWARD});
819*82d56013Sjoerg   if (Explorer.ExploreCFGForward)
820*82d56013Sjoerg     Head = I;
821*82d56013Sjoerg   if (Explorer.ExploreCFGBackward)
822*82d56013Sjoerg     Tail = I;
8237330f729Sjoerg }
8247330f729Sjoerg 
advance()8257330f729Sjoerg const Instruction *MustBeExecutedIterator::advance() {
8267330f729Sjoerg   assert(CurInst && "Cannot advance an end iterator!");
827*82d56013Sjoerg   Head = Explorer.getMustBeExecutedNextInstruction(*this, Head);
828*82d56013Sjoerg   if (Head && Visited.insert({Head, ExplorationDirection ::FORWARD}).second)
829*82d56013Sjoerg     return Head;
830*82d56013Sjoerg   Head = nullptr;
831*82d56013Sjoerg 
832*82d56013Sjoerg   Tail = Explorer.getMustBeExecutedPrevInstruction(*this, Tail);
833*82d56013Sjoerg   if (Tail && Visited.insert({Tail, ExplorationDirection ::BACKWARD}).second)
834*82d56013Sjoerg     return Tail;
835*82d56013Sjoerg   Tail = nullptr;
836*82d56013Sjoerg   return nullptr;
837*82d56013Sjoerg }
838*82d56013Sjoerg 
run(Function & F,FunctionAnalysisManager & AM)839*82d56013Sjoerg PreservedAnalyses MustExecutePrinterPass::run(Function &F,
840*82d56013Sjoerg                                               FunctionAnalysisManager &AM) {
841*82d56013Sjoerg   auto &LI = AM.getResult<LoopAnalysis>(F);
842*82d56013Sjoerg   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
843*82d56013Sjoerg 
844*82d56013Sjoerg   MustExecuteAnnotatedWriter Writer(F, DT, LI);
845*82d56013Sjoerg   F.print(OS, &Writer);
846*82d56013Sjoerg   return PreservedAnalyses::all();
847*82d56013Sjoerg }
848*82d56013Sjoerg 
849*82d56013Sjoerg PreservedAnalyses
run(Module & M,ModuleAnalysisManager & AM)850*82d56013Sjoerg MustBeExecutedContextPrinterPass::run(Module &M, ModuleAnalysisManager &AM) {
851*82d56013Sjoerg   FunctionAnalysisManager &FAM =
852*82d56013Sjoerg       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
853*82d56013Sjoerg   GetterTy<const LoopInfo> LIGetter = [&](const Function &F) {
854*82d56013Sjoerg     return &FAM.getResult<LoopAnalysis>(const_cast<Function &>(F));
855*82d56013Sjoerg   };
856*82d56013Sjoerg   GetterTy<const DominatorTree> DTGetter = [&](const Function &F) {
857*82d56013Sjoerg     return &FAM.getResult<DominatorTreeAnalysis>(const_cast<Function &>(F));
858*82d56013Sjoerg   };
859*82d56013Sjoerg   GetterTy<const PostDominatorTree> PDTGetter = [&](const Function &F) {
860*82d56013Sjoerg     return &FAM.getResult<PostDominatorTreeAnalysis>(const_cast<Function &>(F));
861*82d56013Sjoerg   };
862*82d56013Sjoerg 
863*82d56013Sjoerg   MustBeExecutedContextExplorer Explorer(
864*82d56013Sjoerg       /* ExploreInterBlock */ true,
865*82d56013Sjoerg       /* ExploreCFGForward */ true,
866*82d56013Sjoerg       /* ExploreCFGBackward */ true, LIGetter, DTGetter, PDTGetter);
867*82d56013Sjoerg 
868*82d56013Sjoerg   for (Function &F : M) {
869*82d56013Sjoerg     for (Instruction &I : instructions(F)) {
870*82d56013Sjoerg       OS << "-- Explore context of: " << I << "\n";
871*82d56013Sjoerg       for (const Instruction *CI : Explorer.range(&I))
872*82d56013Sjoerg         OS << "  [F: " << CI->getFunction()->getName() << "] " << *CI << "\n";
873*82d56013Sjoerg     }
874*82d56013Sjoerg   }
875*82d56013Sjoerg   return PreservedAnalyses::all();
8767330f729Sjoerg }
877