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. Given that this is a printer, we don't
359   // care much about memory leaks.
360   GetterTy<LoopInfo> LIGetter = [](const Function &F) {
361     DominatorTree *DT = new DominatorTree(const_cast<Function &>(F));
362     LoopInfo *LI = new LoopInfo(*DT);
363     return LI;
364   };
365   GetterTy<PostDominatorTree> PDTGetter = [](const Function &F) {
366     PostDominatorTree *PDT = new PostDominatorTree(const_cast<Function &>(F));
367     return PDT;
368   };
369   MustBeExecutedContextExplorer Explorer(true, LIGetter, PDTGetter);
370   for (Function &F : M) {
371     for (Instruction &I : instructions(F)) {
372       dbgs() << "-- Explore context of: " << I << "\n";
373       for (const Instruction *CI : Explorer.range(&I))
374         dbgs() << "  [F: " << CI->getFunction()->getName() << "] " << *CI
375                << "\n";
376     }
377   }
378 
379   return false;
380 }
381 
382 static bool isMustExecuteIn(const Instruction &I, Loop *L, DominatorTree *DT) {
383   // TODO: merge these two routines.  For the moment, we display the best
384   // result obtained by *either* implementation.  This is a bit unfair since no
385   // caller actually gets the full power at the moment.
386   SimpleLoopSafetyInfo LSI;
387   LSI.computeLoopSafetyInfo(L);
388   return LSI.isGuaranteedToExecute(I, DT, L) ||
389     isGuaranteedToExecuteForEveryIteration(&I, L);
390 }
391 
392 namespace {
393 /// An assembly annotator class to print must execute information in
394 /// comments.
395 class MustExecuteAnnotatedWriter : public AssemblyAnnotationWriter {
396   DenseMap<const Value*, SmallVector<Loop*, 4> > MustExec;
397 
398 public:
399   MustExecuteAnnotatedWriter(const Function &F,
400                              DominatorTree &DT, LoopInfo &LI) {
401     for (auto &I: instructions(F)) {
402       Loop *L = LI.getLoopFor(I.getParent());
403       while (L) {
404         if (isMustExecuteIn(I, L, &DT)) {
405           MustExec[&I].push_back(L);
406         }
407         L = L->getParentLoop();
408       };
409     }
410   }
411   MustExecuteAnnotatedWriter(const Module &M,
412                              DominatorTree &DT, LoopInfo &LI) {
413     for (auto &F : M)
414     for (auto &I: instructions(F)) {
415       Loop *L = LI.getLoopFor(I.getParent());
416       while (L) {
417         if (isMustExecuteIn(I, L, &DT)) {
418           MustExec[&I].push_back(L);
419         }
420         L = L->getParentLoop();
421       };
422     }
423   }
424 
425 
426   void printInfoComment(const Value &V, formatted_raw_ostream &OS) override {
427     if (!MustExec.count(&V))
428       return;
429 
430     const auto &Loops = MustExec.lookup(&V);
431     const auto NumLoops = Loops.size();
432     if (NumLoops > 1)
433       OS << " ; (mustexec in " << NumLoops << " loops: ";
434     else
435       OS << " ; (mustexec in: ";
436 
437     bool first = true;
438     for (const Loop *L : Loops) {
439       if (!first)
440         OS << ", ";
441       first = false;
442       OS << L->getHeader()->getName();
443     }
444     OS << ")";
445   }
446 };
447 } // namespace
448 
449 bool MustExecutePrinter::runOnFunction(Function &F) {
450   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
451   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
452 
453   MustExecuteAnnotatedWriter Writer(F, DT, LI);
454   F.print(dbgs(), &Writer);
455 
456   return false;
457 }
458 
459 /// Return true if \p L might be an endless loop.
460 static bool maybeEndlessLoop(const Loop &L) {
461   if (L.getHeader()->getParent()->hasFnAttribute(Attribute::WillReturn))
462     return false;
463   // TODO: Actually try to prove it is not.
464   // TODO: If maybeEndlessLoop is going to be expensive, cache it.
465   return true;
466 }
467 
468 static bool mayContainIrreducibleControl(const Function &F, const LoopInfo *LI) {
469   if (!LI)
470     return false;
471   using RPOTraversal = ReversePostOrderTraversal<const Function *>;
472   RPOTraversal FuncRPOT(&F);
473   return !containsIrreducibleCFG<const BasicBlock *, const RPOTraversal,
474                                  const LoopInfo>(FuncRPOT, *LI);
475 }
476 
477 /// Lookup \p Key in \p Map and return the result, potentially after
478 /// initializing the optional through \p Fn(\p args).
479 template <typename K, typename V, typename FnTy, typename... ArgsTy>
480 static V getOrCreateCachedOptional(K Key, DenseMap<K, Optional<V>> &Map,
481                                    FnTy &&Fn, ArgsTy&&... args) {
482   Optional<V> &OptVal = Map[Key];
483   if (!OptVal.hasValue())
484     OptVal = Fn(std::forward<ArgsTy>(args)...);
485   return OptVal.getValue();
486 }
487 
488 const BasicBlock *
489 MustBeExecutedContextExplorer::findForwardJoinPoint(const BasicBlock *InitBB) {
490   const LoopInfo *LI = LIGetter(*InitBB->getParent());
491   const PostDominatorTree *PDT = PDTGetter(*InitBB->getParent());
492 
493   LLVM_DEBUG(dbgs() << "\tFind forward join point for " << InitBB->getName()
494                     << (LI ? " [LI]" : "") << (PDT ? " [PDT]" : ""));
495 
496   const Function &F = *InitBB->getParent();
497   const Loop *L = LI ? LI->getLoopFor(InitBB) : nullptr;
498   const BasicBlock *HeaderBB = L ? L->getHeader() : InitBB;
499   bool WillReturnAndNoThrow = (F.hasFnAttribute(Attribute::WillReturn) ||
500                                (L && !maybeEndlessLoop(*L))) &&
501                               F.doesNotThrow();
502   LLVM_DEBUG(dbgs() << (L ? " [in loop]" : "")
503                     << (WillReturnAndNoThrow ? " [WillReturn] [NoUnwind]" : "")
504                     << "\n");
505 
506   // Determine the adjacent blocks in the given direction but exclude (self)
507   // loops under certain circumstances.
508   SmallVector<const BasicBlock *, 8> Worklist;
509   for (const BasicBlock *SuccBB : successors(InitBB)) {
510     bool IsLatch = SuccBB == HeaderBB;
511     // Loop latches are ignored in forward propagation if the loop cannot be
512     // endless and may not throw: control has to go somewhere.
513     if (!WillReturnAndNoThrow || !IsLatch)
514       Worklist.push_back(SuccBB);
515   }
516   LLVM_DEBUG(dbgs() << "\t\t#Worklist: " << Worklist.size() << "\n");
517 
518   // If there are no other adjacent blocks, there is no join point.
519   if (Worklist.empty())
520     return nullptr;
521 
522   // If there is one adjacent block, it is the join point.
523   if (Worklist.size() == 1)
524     return Worklist[0];
525 
526   // Try to determine a join block through the help of the post-dominance
527   // tree. If no tree was provided, we perform simple pattern matching for one
528   // block conditionals and one block loops only.
529   const BasicBlock *JoinBB = nullptr;
530   if (PDT)
531     if (const auto *InitNode = PDT->getNode(InitBB))
532       if (const auto *IDomNode = InitNode->getIDom())
533         JoinBB = IDomNode->getBlock();
534 
535   if (!JoinBB && Worklist.size() == 2) {
536     const BasicBlock *Succ0 = Worklist[0];
537     const BasicBlock *Succ1 = Worklist[1];
538     const BasicBlock *Succ0UniqueSucc = Succ0->getUniqueSuccessor();
539     const BasicBlock *Succ1UniqueSucc = Succ1->getUniqueSuccessor();
540     if (Succ0UniqueSucc == InitBB) {
541       // InitBB -> Succ0 -> InitBB
542       // InitBB -> Succ1  = JoinBB
543       JoinBB = Succ1;
544     } else if (Succ1UniqueSucc == InitBB) {
545       // InitBB -> Succ1 -> InitBB
546       // InitBB -> Succ0  = JoinBB
547       JoinBB = Succ0;
548     } else if (Succ0 == Succ1UniqueSucc) {
549       // InitBB ->          Succ0 = JoinBB
550       // InitBB -> Succ1 -> Succ0 = JoinBB
551       JoinBB = Succ0;
552     } else if (Succ1 == Succ0UniqueSucc) {
553       // InitBB -> Succ0 -> Succ1 = JoinBB
554       // InitBB ->          Succ1 = JoinBB
555       JoinBB = Succ1;
556     } else if (Succ0UniqueSucc == Succ1UniqueSucc) {
557       // InitBB -> Succ0 -> JoinBB
558       // InitBB -> Succ1 -> JoinBB
559       JoinBB = Succ0UniqueSucc;
560     }
561   }
562 
563   if (!JoinBB && L)
564     JoinBB = L->getUniqueExitBlock();
565 
566   if (!JoinBB)
567     return nullptr;
568 
569   LLVM_DEBUG(dbgs() << "\t\tJoin block candidate: " << JoinBB->getName() << "\n");
570 
571   // In forward direction we check if control will for sure reach JoinBB from
572   // InitBB, thus it can not be "stopped" along the way. Ways to "stop" control
573   // are: infinite loops and instructions that do not necessarily transfer
574   // execution to their successor. To check for them we traverse the CFG from
575   // the adjacent blocks to the JoinBB, looking at all intermediate blocks.
576 
577   // If we know the function is "will-return" and "no-throw" there is no need
578   // for futher checks.
579   if (!F.hasFnAttribute(Attribute::WillReturn) || !F.doesNotThrow()) {
580 
581     auto BlockTransfersExecutionToSuccessor = [](const BasicBlock *BB) {
582       return isGuaranteedToTransferExecutionToSuccessor(BB);
583     };
584 
585     SmallPtrSet<const BasicBlock *, 16> Visited;
586     while (!Worklist.empty()) {
587       const BasicBlock *ToBB = Worklist.pop_back_val();
588       if (ToBB == JoinBB)
589         continue;
590 
591       // Make sure all loops in-between are finite.
592       if (!Visited.insert(ToBB).second) {
593         if (!F.hasFnAttribute(Attribute::WillReturn)) {
594           if (!LI)
595             return nullptr;
596 
597           bool MayContainIrreducibleControl = getOrCreateCachedOptional(
598               &F, IrreducibleControlMap, mayContainIrreducibleControl, F, LI);
599           if (MayContainIrreducibleControl)
600             return nullptr;
601 
602           const Loop *L = LI->getLoopFor(ToBB);
603           if (L && maybeEndlessLoop(*L))
604             return nullptr;
605         }
606 
607         continue;
608       }
609 
610       // Make sure the block has no instructions that could stop control
611       // transfer.
612       bool TransfersExecution = getOrCreateCachedOptional(
613           ToBB, BlockTransferMap, BlockTransfersExecutionToSuccessor, ToBB);
614       if (!TransfersExecution)
615         return nullptr;
616 
617       for (const BasicBlock *AdjacentBB : successors(ToBB))
618         Worklist.push_back(AdjacentBB);
619     }
620   }
621 
622   LLVM_DEBUG(dbgs() << "\tJoin block: " << JoinBB->getName() << "\n");
623   return JoinBB;
624 }
625 
626 const Instruction *
627 MustBeExecutedContextExplorer::getMustBeExecutedNextInstruction(
628     MustBeExecutedIterator &It, const Instruction *PP) {
629   if (!PP)
630     return PP;
631   LLVM_DEBUG(dbgs() << "Find next instruction for " << *PP << "\n");
632 
633   // If we explore only inside a given basic block we stop at terminators.
634   if (!ExploreInterBlock && PP->isTerminator()) {
635     LLVM_DEBUG(dbgs() << "\tReached terminator in intra-block mode, done\n");
636     return nullptr;
637   }
638 
639   // If we do not traverse the call graph we check if we can make progress in
640   // the current function. First, check if the instruction is guaranteed to
641   // transfer execution to the successor.
642   bool TransfersExecution = isGuaranteedToTransferExecutionToSuccessor(PP);
643   if (!TransfersExecution)
644     return nullptr;
645 
646   // If this is not a terminator we know that there is a single instruction
647   // after this one that is executed next if control is transfered. If not,
648   // we can try to go back to a call site we entered earlier. If none exists, we
649   // do not know any instruction that has to be executd next.
650   if (!PP->isTerminator()) {
651     const Instruction *NextPP = PP->getNextNode();
652     LLVM_DEBUG(dbgs() << "\tIntermediate instruction does transfer control\n");
653     return NextPP;
654   }
655 
656   // Finally, we have to handle terminators, trivial ones first.
657   assert(PP->isTerminator() && "Expected a terminator!");
658 
659   // A terminator without a successor is not handled yet.
660   if (PP->getNumSuccessors() == 0) {
661     LLVM_DEBUG(dbgs() << "\tUnhandled terminator\n");
662     return nullptr;
663   }
664 
665   // A terminator with a single successor, we will continue at the beginning of
666   // that one.
667   if (PP->getNumSuccessors() == 1) {
668     LLVM_DEBUG(
669         dbgs() << "\tUnconditional terminator, continue with successor\n");
670     return &PP->getSuccessor(0)->front();
671   }
672 
673   // Multiple successors mean we need to find the join point where control flow
674   // converges again. We use the findForwardJoinPoint helper function with
675   // information about the function and helper analyses, if available.
676   if (const BasicBlock *JoinBB = findForwardJoinPoint(PP->getParent()))
677     return &JoinBB->front();
678 
679   LLVM_DEBUG(dbgs() << "\tNo join point found\n");
680   return nullptr;
681 }
682 
683 MustBeExecutedIterator::MustBeExecutedIterator(
684     MustBeExecutedContextExplorer &Explorer, const Instruction *I)
685     : Explorer(Explorer), CurInst(I) {
686   reset(I);
687 }
688 
689 void MustBeExecutedIterator::reset(const Instruction *I) {
690   CurInst = I;
691   Visited.clear();
692   Visited.insert(I);
693 }
694 
695 const Instruction *MustBeExecutedIterator::advance() {
696   assert(CurInst && "Cannot advance an end iterator!");
697   const Instruction *Next =
698       Explorer.getMustBeExecutedNextInstruction(*this, CurInst);
699   if (Next && !Visited.insert(Next).second)
700     Next = nullptr;
701   return Next;
702 }
703