1 //===- MustExecute.cpp - Printer for isGuaranteedToExecute ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/Analysis/MustExecute.h"
10 #include "llvm/ADT/PostOrderIterator.h"
11 #include "llvm/Analysis/CFG.h"
12 #include "llvm/Analysis/InstructionSimplify.h"
13 #include "llvm/Analysis/LoopInfo.h"
14 #include "llvm/Analysis/Passes.h"
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/Analysis/PostDominators.h"
17 #include "llvm/IR/AssemblyAnnotationWriter.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/InstIterator.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/FormattedStream.h"
24 #include "llvm/Support/raw_ostream.h"
25 
26 using namespace llvm;
27 
28 #define DEBUG_TYPE "must-execute"
29 
30 const DenseMap<BasicBlock *, ColorVector> &
31 LoopSafetyInfo::getBlockColors() const {
32   return BlockColors;
33 }
34 
35 void LoopSafetyInfo::copyColors(BasicBlock *New, BasicBlock *Old) {
36   ColorVector &ColorsForNewBlock = BlockColors[New];
37   ColorVector &ColorsForOldBlock = BlockColors[Old];
38   ColorsForNewBlock = ColorsForOldBlock;
39 }
40 
41 bool SimpleLoopSafetyInfo::blockMayThrow(const BasicBlock *BB) const {
42   (void)BB;
43   return anyBlockMayThrow();
44 }
45 
46 bool SimpleLoopSafetyInfo::anyBlockMayThrow() const {
47   return MayThrow;
48 }
49 
50 void SimpleLoopSafetyInfo::computeLoopSafetyInfo(const Loop *CurLoop) {
51   assert(CurLoop != nullptr && "CurLoop can't be null");
52   BasicBlock *Header = CurLoop->getHeader();
53   // Iterate over header and compute safety info.
54   HeaderMayThrow = !isGuaranteedToTransferExecutionToSuccessor(Header);
55   MayThrow = HeaderMayThrow;
56   // Iterate over loop instructions and compute safety info.
57   // Skip header as it has been computed and stored in HeaderMayThrow.
58   // The first block in loopinfo.Blocks is guaranteed to be the header.
59   assert(Header == *CurLoop->getBlocks().begin() &&
60          "First block must be header");
61   for (Loop::block_iterator BB = std::next(CurLoop->block_begin()),
62                             BBE = CurLoop->block_end();
63        (BB != BBE) && !MayThrow; ++BB)
64     MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(*BB);
65 
66   computeBlockColors(CurLoop);
67 }
68 
69 bool ICFLoopSafetyInfo::blockMayThrow(const BasicBlock *BB) const {
70   return ICF.hasICF(BB);
71 }
72 
73 bool ICFLoopSafetyInfo::anyBlockMayThrow() const {
74   return MayThrow;
75 }
76 
77 void ICFLoopSafetyInfo::computeLoopSafetyInfo(const Loop *CurLoop) {
78   assert(CurLoop != nullptr && "CurLoop can't be null");
79   ICF.clear();
80   MW.clear();
81   MayThrow = false;
82   // Figure out the fact that at least one block may throw.
83   for (auto &BB : CurLoop->blocks())
84     if (ICF.hasICF(&*BB)) {
85       MayThrow = true;
86       break;
87     }
88   computeBlockColors(CurLoop);
89 }
90 
91 void ICFLoopSafetyInfo::insertInstructionTo(const Instruction *Inst,
92                                             const BasicBlock *BB) {
93   ICF.insertInstructionTo(Inst, BB);
94   MW.insertInstructionTo(Inst, BB);
95 }
96 
97 void ICFLoopSafetyInfo::removeInstruction(const Instruction *Inst) {
98   ICF.removeInstruction(Inst);
99   MW.removeInstruction(Inst);
100 }
101 
102 void LoopSafetyInfo::computeBlockColors(const Loop *CurLoop) {
103   // Compute funclet colors if we might sink/hoist in a function with a funclet
104   // personality routine.
105   Function *Fn = CurLoop->getHeader()->getParent();
106   if (Fn->hasPersonalityFn())
107     if (Constant *PersonalityFn = Fn->getPersonalityFn())
108       if (isScopedEHPersonality(classifyEHPersonality(PersonalityFn)))
109         BlockColors = colorEHFunclets(*Fn);
110 }
111 
112 /// Return true if we can prove that the given ExitBlock is not reached on the
113 /// first iteration of the given loop.  That is, the backedge of the loop must
114 /// be executed before the ExitBlock is executed in any dynamic execution trace.
115 static bool CanProveNotTakenFirstIteration(const BasicBlock *ExitBlock,
116                                            const DominatorTree *DT,
117                                            const Loop *CurLoop) {
118   auto *CondExitBlock = ExitBlock->getSinglePredecessor();
119   if (!CondExitBlock)
120     // expect unique exits
121     return false;
122   assert(CurLoop->contains(CondExitBlock) && "meaning of exit block");
123   auto *BI = dyn_cast<BranchInst>(CondExitBlock->getTerminator());
124   if (!BI || !BI->isConditional())
125     return false;
126   // If condition is constant and false leads to ExitBlock then we always
127   // execute the true branch.
128   if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition()))
129     return BI->getSuccessor(Cond->getZExtValue() ? 1 : 0) == ExitBlock;
130   auto *Cond = dyn_cast<CmpInst>(BI->getCondition());
131   if (!Cond)
132     return false;
133   // todo: this would be a lot more powerful if we used scev, but all the
134   // plumbing is currently missing to pass a pointer in from the pass
135   // Check for cmp (phi [x, preheader] ...), y where (pred x, y is known
136   auto *LHS = dyn_cast<PHINode>(Cond->getOperand(0));
137   auto *RHS = Cond->getOperand(1);
138   if (!LHS || LHS->getParent() != CurLoop->getHeader())
139     return false;
140   auto DL = ExitBlock->getModule()->getDataLayout();
141   auto *IVStart = LHS->getIncomingValueForBlock(CurLoop->getLoopPreheader());
142   auto *SimpleValOrNull = SimplifyCmpInst(Cond->getPredicate(),
143                                           IVStart, RHS,
144                                           {DL, /*TLI*/ nullptr,
145                                               DT, /*AC*/ nullptr, BI});
146   auto *SimpleCst = dyn_cast_or_null<Constant>(SimpleValOrNull);
147   if (!SimpleCst)
148     return false;
149   if (ExitBlock == BI->getSuccessor(0))
150     return SimpleCst->isZeroValue();
151   assert(ExitBlock == BI->getSuccessor(1) && "implied by above");
152   return SimpleCst->isAllOnesValue();
153 }
154 
155 /// Collect all blocks from \p CurLoop which lie on all possible paths from
156 /// the header of \p CurLoop (inclusive) to BB (exclusive) into the set
157 /// \p Predecessors. If \p BB is the header, \p Predecessors will be empty.
158 static void collectTransitivePredecessors(
159     const Loop *CurLoop, const BasicBlock *BB,
160     SmallPtrSetImpl<const BasicBlock *> &Predecessors) {
161   assert(Predecessors.empty() && "Garbage in predecessors set?");
162   assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
163   if (BB == CurLoop->getHeader())
164     return;
165   SmallVector<const BasicBlock *, 4> WorkList;
166   for (auto *Pred : predecessors(BB)) {
167     Predecessors.insert(Pred);
168     WorkList.push_back(Pred);
169   }
170   while (!WorkList.empty()) {
171     auto *Pred = WorkList.pop_back_val();
172     assert(CurLoop->contains(Pred) && "Should only reach loop blocks!");
173     // We are not interested in backedges and we don't want to leave loop.
174     if (Pred == CurLoop->getHeader())
175       continue;
176     // TODO: If BB lies in an inner loop of CurLoop, this will traverse over all
177     // blocks of this inner loop, even those that are always executed AFTER the
178     // BB. It may make our analysis more conservative than it could be, see test
179     // @nested and @nested_no_throw in test/Analysis/MustExecute/loop-header.ll.
180     // We can ignore backedge of all loops containing BB to get a sligtly more
181     // optimistic result.
182     for (auto *PredPred : predecessors(Pred))
183       if (Predecessors.insert(PredPred).second)
184         WorkList.push_back(PredPred);
185   }
186 }
187 
188 bool LoopSafetyInfo::allLoopPathsLeadToBlock(const Loop *CurLoop,
189                                              const BasicBlock *BB,
190                                              const DominatorTree *DT) const {
191   assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
192 
193   // Fast path: header is always reached once the loop is entered.
194   if (BB == CurLoop->getHeader())
195     return true;
196 
197   // Collect all transitive predecessors of BB in the same loop. This set will
198   // be a subset of the blocks within the loop.
199   SmallPtrSet<const BasicBlock *, 4> Predecessors;
200   collectTransitivePredecessors(CurLoop, BB, Predecessors);
201 
202   // Make sure that all successors of, all predecessors of BB which are not
203   // dominated by BB, are either:
204   // 1) BB,
205   // 2) Also predecessors of BB,
206   // 3) Exit blocks which are not taken on 1st iteration.
207   // Memoize blocks we've already checked.
208   SmallPtrSet<const BasicBlock *, 4> CheckedSuccessors;
209   for (auto *Pred : Predecessors) {
210     // Predecessor block may throw, so it has a side exit.
211     if (blockMayThrow(Pred))
212       return false;
213 
214     // BB dominates Pred, so if Pred runs, BB must run.
215     // This is true when Pred is a loop latch.
216     if (DT->dominates(BB, Pred))
217       continue;
218 
219     for (auto *Succ : successors(Pred))
220       if (CheckedSuccessors.insert(Succ).second &&
221           Succ != BB && !Predecessors.count(Succ))
222         // By discharging conditions that are not executed on the 1st iteration,
223         // we guarantee that *at least* on the first iteration all paths from
224         // header that *may* execute will lead us to the block of interest. So
225         // that if we had virtually peeled one iteration away, in this peeled
226         // iteration the set of predecessors would contain only paths from
227         // header to BB without any exiting edges that may execute.
228         //
229         // TODO: We only do it for exiting edges currently. We could use the
230         // same function to skip some of the edges within the loop if we know
231         // that they will not be taken on the 1st iteration.
232         //
233         // TODO: If we somehow know the number of iterations in loop, the same
234         // check may be done for any arbitrary N-th iteration as long as N is
235         // not greater than minimum number of iterations in this loop.
236         if (CurLoop->contains(Succ) ||
237             !CanProveNotTakenFirstIteration(Succ, DT, CurLoop))
238           return false;
239   }
240 
241   // All predecessors can only lead us to BB.
242   return true;
243 }
244 
245 /// Returns true if the instruction in a loop is guaranteed to execute at least
246 /// once.
247 bool SimpleLoopSafetyInfo::isGuaranteedToExecute(const Instruction &Inst,
248                                                  const DominatorTree *DT,
249                                                  const Loop *CurLoop) const {
250   // If the instruction is in the header block for the loop (which is very
251   // common), it is always guaranteed to dominate the exit blocks.  Since this
252   // is a common case, and can save some work, check it now.
253   if (Inst.getParent() == CurLoop->getHeader())
254     // If there's a throw in the header block, we can't guarantee we'll reach
255     // Inst unless we can prove that Inst comes before the potential implicit
256     // exit.  At the moment, we use a (cheap) hack for the common case where
257     // the instruction of interest is the first one in the block.
258     return !HeaderMayThrow ||
259            Inst.getParent()->getFirstNonPHIOrDbg() == &Inst;
260 
261   // If there is a path from header to exit or latch that doesn't lead to our
262   // instruction's block, return false.
263   return allLoopPathsLeadToBlock(CurLoop, Inst.getParent(), DT);
264 }
265 
266 bool ICFLoopSafetyInfo::isGuaranteedToExecute(const Instruction &Inst,
267                                               const DominatorTree *DT,
268                                               const Loop *CurLoop) const {
269   return !ICF.isDominatedByICFIFromSameBlock(&Inst) &&
270          allLoopPathsLeadToBlock(CurLoop, Inst.getParent(), DT);
271 }
272 
273 bool ICFLoopSafetyInfo::doesNotWriteMemoryBefore(const BasicBlock *BB,
274                                                  const Loop *CurLoop) const {
275   assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
276 
277   // Fast path: there are no instructions before header.
278   if (BB == CurLoop->getHeader())
279     return true;
280 
281   // Collect all transitive predecessors of BB in the same loop. This set will
282   // be a subset of the blocks within the loop.
283   SmallPtrSet<const BasicBlock *, 4> Predecessors;
284   collectTransitivePredecessors(CurLoop, BB, Predecessors);
285   // Find if there any instruction in either predecessor that could write
286   // to memory.
287   for (auto *Pred : Predecessors)
288     if (MW.mayWriteToMemory(Pred))
289       return false;
290   return true;
291 }
292 
293 bool ICFLoopSafetyInfo::doesNotWriteMemoryBefore(const Instruction &I,
294                                                  const Loop *CurLoop) const {
295   auto *BB = I.getParent();
296   assert(CurLoop->contains(BB) && "Should only be called for loop blocks!");
297   return !MW.isDominatedByMemoryWriteFromSameBlock(&I) &&
298          doesNotWriteMemoryBefore(BB, CurLoop);
299 }
300 
301 namespace {
302   struct MustExecutePrinter : public FunctionPass {
303 
304     static char ID; // Pass identification, replacement for typeid
305     MustExecutePrinter() : FunctionPass(ID) {
306       initializeMustExecutePrinterPass(*PassRegistry::getPassRegistry());
307     }
308     void getAnalysisUsage(AnalysisUsage &AU) const override {
309       AU.setPreservesAll();
310       AU.addRequired<DominatorTreeWrapperPass>();
311       AU.addRequired<LoopInfoWrapperPass>();
312     }
313     bool runOnFunction(Function &F) override;
314   };
315   struct MustBeExecutedContextPrinter : public ModulePass {
316     static char ID;
317 
318     MustBeExecutedContextPrinter() : ModulePass(ID) {
319       initializeMustBeExecutedContextPrinterPass(*PassRegistry::getPassRegistry());
320     }
321     void getAnalysisUsage(AnalysisUsage &AU) const override {
322       AU.setPreservesAll();
323     }
324     bool runOnModule(Module &M) override;
325   };
326 }
327 
328 char MustExecutePrinter::ID = 0;
329 INITIALIZE_PASS_BEGIN(MustExecutePrinter, "print-mustexecute",
330                       "Instructions which execute on loop entry", false, true)
331 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
332 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
333 INITIALIZE_PASS_END(MustExecutePrinter, "print-mustexecute",
334                     "Instructions which execute on loop entry", false, true)
335 
336 FunctionPass *llvm::createMustExecutePrinter() {
337   return new MustExecutePrinter();
338 }
339 
340 char MustBeExecutedContextPrinter::ID = 0;
341 INITIALIZE_PASS_BEGIN(
342     MustBeExecutedContextPrinter, "print-must-be-executed-contexts",
343     "print the must-be-executed-contexed for all instructions", false, true)
344 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
345 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
346 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
347 INITIALIZE_PASS_END(MustBeExecutedContextPrinter,
348                     "print-must-be-executed-contexts",
349                     "print the must-be-executed-contexed for all instructions",
350                     false, true)
351 
352 ModulePass *llvm::createMustBeExecutedContextPrinter() {
353   return new MustBeExecutedContextPrinter();
354 }
355 
356 bool MustBeExecutedContextPrinter::runOnModule(Module &M) {
357   // We provide non-PM analysis here because the old PM doesn't like to query
358   // function passes from a module pass.
359   SmallVector<PostDominatorTree *, 8> PDTs;
360   SmallVector<DominatorTree *, 8> DTs;
361   SmallVector<LoopInfo *, 8> LIs;
362 
363   GetterTy<LoopInfo> LIGetter = [&](const Function &F) {
364     DominatorTree *DT = new DominatorTree(const_cast<Function &>(F));
365     LoopInfo *LI = new LoopInfo(*DT);
366     DTs.push_back(DT);
367     LIs.push_back(LI);
368     return LI;
369   };
370   GetterTy<PostDominatorTree> PDTGetter = [&](const Function &F) {
371     PostDominatorTree *PDT = new PostDominatorTree(const_cast<Function &>(F));
372     PDTs.push_back(PDT);
373     return PDT;
374   };
375   MustBeExecutedContextExplorer Explorer(true, LIGetter, PDTGetter);
376   for (Function &F : M) {
377     for (Instruction &I : instructions(F)) {
378       dbgs() << "-- Explore context of: " << I << "\n";
379       for (const Instruction *CI : Explorer.range(&I))
380         dbgs() << "  [F: " << CI->getFunction()->getName() << "] " << *CI
381                << "\n";
382     }
383   }
384 
385   DeleteContainerPointers(PDTs);
386   DeleteContainerPointers(LIs);
387   DeleteContainerPointers(DTs);
388   return false;
389 }
390 
391 static bool isMustExecuteIn(const Instruction &I, Loop *L, DominatorTree *DT) {
392   // TODO: merge these two routines.  For the moment, we display the best
393   // result obtained by *either* implementation.  This is a bit unfair since no
394   // caller actually gets the full power at the moment.
395   SimpleLoopSafetyInfo LSI;
396   LSI.computeLoopSafetyInfo(L);
397   return LSI.isGuaranteedToExecute(I, DT, L) ||
398     isGuaranteedToExecuteForEveryIteration(&I, L);
399 }
400 
401 namespace {
402 /// An assembly annotator class to print must execute information in
403 /// comments.
404 class MustExecuteAnnotatedWriter : public AssemblyAnnotationWriter {
405   DenseMap<const Value*, SmallVector<Loop*, 4> > MustExec;
406 
407 public:
408   MustExecuteAnnotatedWriter(const Function &F,
409                              DominatorTree &DT, LoopInfo &LI) {
410     for (auto &I: instructions(F)) {
411       Loop *L = LI.getLoopFor(I.getParent());
412       while (L) {
413         if (isMustExecuteIn(I, L, &DT)) {
414           MustExec[&I].push_back(L);
415         }
416         L = L->getParentLoop();
417       };
418     }
419   }
420   MustExecuteAnnotatedWriter(const Module &M,
421                              DominatorTree &DT, LoopInfo &LI) {
422     for (auto &F : M)
423     for (auto &I: instructions(F)) {
424       Loop *L = LI.getLoopFor(I.getParent());
425       while (L) {
426         if (isMustExecuteIn(I, L, &DT)) {
427           MustExec[&I].push_back(L);
428         }
429         L = L->getParentLoop();
430       };
431     }
432   }
433 
434 
435   void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
436     if (!MustExec.count(&V))
437       return;
438 
439     const auto &Loops = MustExec.lookup(&V);
440     const auto NumLoops = Loops.size();
441     if (NumLoops > 1)
442       OS << " ; (mustexec in " << NumLoops << " loops: ";
443     else
444       OS << " ; (mustexec in: ";
445 
446     bool first = true;
447     for (const Loop *L : Loops) {
448       if (!first)
449         OS << ", ";
450       first = false;
451       OS << L->getHeader()->getName();
452     }
453     OS << ")";
454   }
455 };
456 } // namespace
457 
458 bool MustExecutePrinter::runOnFunction(Function &F) {
459   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
460   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
461 
462   MustExecuteAnnotatedWriter Writer(F, DT, LI);
463   F.print(dbgs(), &Writer);
464 
465   return false;
466 }
467 
468 /// Return true if \p L might be an endless loop.
469 static bool maybeEndlessLoop(const Loop &L) {
470   if (L.getHeader()->getParent()->hasFnAttribute(Attribute::WillReturn))
471     return false;
472   // TODO: Actually try to prove it is not.
473   // TODO: If maybeEndlessLoop is going to be expensive, cache it.
474   return true;
475 }
476 
477 static bool mayContainIrreducibleControl(const Function &F, const LoopInfo *LI) {
478   if (!LI)
479     return false;
480   using RPOTraversal = ReversePostOrderTraversal<const Function *>;
481   RPOTraversal FuncRPOT(&F);
482   return !containsIrreducibleCFG<const BasicBlock *, const RPOTraversal,
483                                  const LoopInfo>(FuncRPOT, *LI);
484 }
485 
486 /// Lookup \p Key in \p Map and return the result, potentially after
487 /// initializing the optional through \p Fn(\p args).
488 template <typename K, typename V, typename FnTy, typename... ArgsTy>
489 static V getOrCreateCachedOptional(K Key, DenseMap<K, Optional<V>> &Map,
490                                    FnTy &&Fn, ArgsTy&&... args) {
491   Optional<V> &OptVal = Map[Key];
492   if (!OptVal.hasValue())
493     OptVal = Fn(std::forward<ArgsTy>(args)...);
494   return OptVal.getValue();
495 }
496 
497 const BasicBlock *
498 MustBeExecutedContextExplorer::findForwardJoinPoint(const BasicBlock *InitBB) {
499   const LoopInfo *LI = LIGetter(*InitBB->getParent());
500   const PostDominatorTree *PDT = PDTGetter(*InitBB->getParent());
501 
502   LLVM_DEBUG(dbgs() << "\tFind forward join point for " << InitBB->getName()
503                     << (LI ? " [LI]" : "") << (PDT ? " [PDT]" : ""));
504 
505   const Function &F = *InitBB->getParent();
506   const Loop *L = LI ? LI->getLoopFor(InitBB) : nullptr;
507   const BasicBlock *HeaderBB = L ? L->getHeader() : InitBB;
508   bool WillReturnAndNoThrow = (F.hasFnAttribute(Attribute::WillReturn) ||
509                                (L && !maybeEndlessLoop(*L))) &&
510                               F.doesNotThrow();
511   LLVM_DEBUG(dbgs() << (L ? " [in loop]" : "")
512                     << (WillReturnAndNoThrow ? " [WillReturn] [NoUnwind]" : "")
513                     << "\n");
514 
515   // Determine the adjacent blocks in the given direction but exclude (self)
516   // loops under certain circumstances.
517   SmallVector<const BasicBlock *, 8> Worklist;
518   for (const BasicBlock *SuccBB : successors(InitBB)) {
519     bool IsLatch = SuccBB == HeaderBB;
520     // Loop latches are ignored in forward propagation if the loop cannot be
521     // endless and may not throw: control has to go somewhere.
522     if (!WillReturnAndNoThrow || !IsLatch)
523       Worklist.push_back(SuccBB);
524   }
525   LLVM_DEBUG(dbgs() << "\t\t#Worklist: " << Worklist.size() << "\n");
526 
527   // If there are no other adjacent blocks, there is no join point.
528   if (Worklist.empty())
529     return nullptr;
530 
531   // If there is one adjacent block, it is the join point.
532   if (Worklist.size() == 1)
533     return Worklist[0];
534 
535   // Try to determine a join block through the help of the post-dominance
536   // tree. If no tree was provided, we perform simple pattern matching for one
537   // block conditionals and one block loops only.
538   const BasicBlock *JoinBB = nullptr;
539   if (PDT)
540     if (const auto *InitNode = PDT->getNode(InitBB))
541       if (const auto *IDomNode = InitNode->getIDom())
542         JoinBB = IDomNode->getBlock();
543 
544   if (!JoinBB && Worklist.size() == 2) {
545     const BasicBlock *Succ0 = Worklist[0];
546     const BasicBlock *Succ1 = Worklist[1];
547     const BasicBlock *Succ0UniqueSucc = Succ0->getUniqueSuccessor();
548     const BasicBlock *Succ1UniqueSucc = Succ1->getUniqueSuccessor();
549     if (Succ0UniqueSucc == InitBB) {
550       // InitBB -> Succ0 -> InitBB
551       // InitBB -> Succ1  = JoinBB
552       JoinBB = Succ1;
553     } else if (Succ1UniqueSucc == InitBB) {
554       // InitBB -> Succ1 -> InitBB
555       // InitBB -> Succ0  = JoinBB
556       JoinBB = Succ0;
557     } else if (Succ0 == Succ1UniqueSucc) {
558       // InitBB ->          Succ0 = JoinBB
559       // InitBB -> Succ1 -> Succ0 = JoinBB
560       JoinBB = Succ0;
561     } else if (Succ1 == Succ0UniqueSucc) {
562       // InitBB -> Succ0 -> Succ1 = JoinBB
563       // InitBB ->          Succ1 = JoinBB
564       JoinBB = Succ1;
565     } else if (Succ0UniqueSucc == Succ1UniqueSucc) {
566       // InitBB -> Succ0 -> JoinBB
567       // InitBB -> Succ1 -> JoinBB
568       JoinBB = Succ0UniqueSucc;
569     }
570   }
571 
572   if (!JoinBB && L)
573     JoinBB = L->getUniqueExitBlock();
574 
575   if (!JoinBB)
576     return nullptr;
577 
578   LLVM_DEBUG(dbgs() << "\t\tJoin block candidate: " << JoinBB->getName() << "\n");
579 
580   // In forward direction we check if control will for sure reach JoinBB from
581   // InitBB, thus it can not be "stopped" along the way. Ways to "stop" control
582   // are: infinite loops and instructions that do not necessarily transfer
583   // execution to their successor. To check for them we traverse the CFG from
584   // the adjacent blocks to the JoinBB, looking at all intermediate blocks.
585 
586   // If we know the function is "will-return" and "no-throw" there is no need
587   // for futher checks.
588   if (!F.hasFnAttribute(Attribute::WillReturn) || !F.doesNotThrow()) {
589 
590     auto BlockTransfersExecutionToSuccessor = [](const BasicBlock *BB) {
591       return isGuaranteedToTransferExecutionToSuccessor(BB);
592     };
593 
594     SmallPtrSet<const BasicBlock *, 16> Visited;
595     while (!Worklist.empty()) {
596       const BasicBlock *ToBB = Worklist.pop_back_val();
597       if (ToBB == JoinBB)
598         continue;
599 
600       // Make sure all loops in-between are finite.
601       if (!Visited.insert(ToBB).second) {
602         if (!F.hasFnAttribute(Attribute::WillReturn)) {
603           if (!LI)
604             return nullptr;
605 
606           bool MayContainIrreducibleControl = getOrCreateCachedOptional(
607               &F, IrreducibleControlMap, mayContainIrreducibleControl, F, LI);
608           if (MayContainIrreducibleControl)
609             return nullptr;
610 
611           const Loop *L = LI->getLoopFor(ToBB);
612           if (L && maybeEndlessLoop(*L))
613             return nullptr;
614         }
615 
616         continue;
617       }
618 
619       // Make sure the block has no instructions that could stop control
620       // transfer.
621       bool TransfersExecution = getOrCreateCachedOptional(
622           ToBB, BlockTransferMap, BlockTransfersExecutionToSuccessor, ToBB);
623       if (!TransfersExecution)
624         return nullptr;
625 
626       for (const BasicBlock *AdjacentBB : successors(ToBB))
627         Worklist.push_back(AdjacentBB);
628     }
629   }
630 
631   LLVM_DEBUG(dbgs() << "\tJoin block: " << JoinBB->getName() << "\n");
632   return JoinBB;
633 }
634 
635 const Instruction *
636 MustBeExecutedContextExplorer::getMustBeExecutedNextInstruction(
637     MustBeExecutedIterator &It, const Instruction *PP) {
638   if (!PP)
639     return PP;
640   LLVM_DEBUG(dbgs() << "Find next instruction for " << *PP << "\n");
641 
642   // If we explore only inside a given basic block we stop at terminators.
643   if (!ExploreInterBlock && PP->isTerminator()) {
644     LLVM_DEBUG(dbgs() << "\tReached terminator in intra-block mode, done\n");
645     return nullptr;
646   }
647 
648   // If we do not traverse the call graph we check if we can make progress in
649   // the current function. First, check if the instruction is guaranteed to
650   // transfer execution to the successor.
651   bool TransfersExecution = isGuaranteedToTransferExecutionToSuccessor(PP);
652   if (!TransfersExecution)
653     return nullptr;
654 
655   // If this is not a terminator we know that there is a single instruction
656   // after this one that is executed next if control is transfered. If not,
657   // we can try to go back to a call site we entered earlier. If none exists, we
658   // do not know any instruction that has to be executd next.
659   if (!PP->isTerminator()) {
660     const Instruction *NextPP = PP->getNextNode();
661     LLVM_DEBUG(dbgs() << "\tIntermediate instruction does transfer control\n");
662     return NextPP;
663   }
664 
665   // Finally, we have to handle terminators, trivial ones first.
666   assert(PP->isTerminator() && "Expected a terminator!");
667 
668   // A terminator without a successor is not handled yet.
669   if (PP->getNumSuccessors() == 0) {
670     LLVM_DEBUG(dbgs() << "\tUnhandled terminator\n");
671     return nullptr;
672   }
673 
674   // A terminator with a single successor, we will continue at the beginning of
675   // that one.
676   if (PP->getNumSuccessors() == 1) {
677     LLVM_DEBUG(
678         dbgs() << "\tUnconditional terminator, continue with successor\n");
679     return &PP->getSuccessor(0)->front();
680   }
681 
682   // Multiple successors mean we need to find the join point where control flow
683   // converges again. We use the findForwardJoinPoint helper function with
684   // information about the function and helper analyses, if available.
685   if (const BasicBlock *JoinBB = findForwardJoinPoint(PP->getParent()))
686     return &JoinBB->front();
687 
688   LLVM_DEBUG(dbgs() << "\tNo join point found\n");
689   return nullptr;
690 }
691 
692 MustBeExecutedIterator::MustBeExecutedIterator(
693     MustBeExecutedContextExplorer &Explorer, const Instruction *I)
694     : Explorer(Explorer), CurInst(I) {
695   reset(I);
696 }
697 
698 void MustBeExecutedIterator::reset(const Instruction *I) {
699   CurInst = I;
700   Visited.clear();
701   Visited.insert(I);
702 }
703 
704 const Instruction *MustBeExecutedIterator::advance() {
705   assert(CurInst && "Cannot advance an end iterator!");
706   const Instruction *Next =
707       Explorer.getMustBeExecutedNextInstruction(*this, CurInst);
708   if (Next && !Visited.insert(Next).second)
709     Next = nullptr;
710   return Next;
711 }
712