xref: /llvm-project/llvm/lib/Transforms/Scalar/JumpThreading.cpp (revision a1b78fb929fccf96acaa0212cf68fee82298e747)
1 //===- JumpThreading.cpp - Thread control through conditional blocks ------===//
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 // This file implements the Jump Threading pass.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Transforms/Scalar/JumpThreading.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/DenseSet.h"
16 #include "llvm/ADT/MapVector.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/BlockFrequencyInfo.h"
23 #include "llvm/Analysis/BranchProbabilityInfo.h"
24 #include "llvm/Analysis/CFG.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/GlobalsModRef.h"
27 #include "llvm/Analysis/GuardUtils.h"
28 #include "llvm/Analysis/InstructionSimplify.h"
29 #include "llvm/Analysis/LazyValueInfo.h"
30 #include "llvm/Analysis/Loads.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/Analysis/MemoryLocation.h"
33 #include "llvm/Analysis/PostDominators.h"
34 #include "llvm/Analysis/TargetLibraryInfo.h"
35 #include "llvm/Analysis/TargetTransformInfo.h"
36 #include "llvm/Analysis/ValueTracking.h"
37 #include "llvm/IR/BasicBlock.h"
38 #include "llvm/IR/CFG.h"
39 #include "llvm/IR/Constant.h"
40 #include "llvm/IR/ConstantRange.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/DataLayout.h"
43 #include "llvm/IR/DebugInfo.h"
44 #include "llvm/IR/Dominators.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/InstrTypes.h"
47 #include "llvm/IR/Instruction.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/IntrinsicInst.h"
50 #include "llvm/IR/Intrinsics.h"
51 #include "llvm/IR/LLVMContext.h"
52 #include "llvm/IR/MDBuilder.h"
53 #include "llvm/IR/Metadata.h"
54 #include "llvm/IR/Module.h"
55 #include "llvm/IR/PassManager.h"
56 #include "llvm/IR/PatternMatch.h"
57 #include "llvm/IR/ProfDataUtils.h"
58 #include "llvm/IR/Type.h"
59 #include "llvm/IR/Use.h"
60 #include "llvm/IR/Value.h"
61 #include "llvm/InitializePasses.h"
62 #include "llvm/Pass.h"
63 #include "llvm/Support/BlockFrequency.h"
64 #include "llvm/Support/BranchProbability.h"
65 #include "llvm/Support/Casting.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/Debug.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Transforms/Scalar.h"
70 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
71 #include "llvm/Transforms/Utils/Cloning.h"
72 #include "llvm/Transforms/Utils/Local.h"
73 #include "llvm/Transforms/Utils/SSAUpdater.h"
74 #include "llvm/Transforms/Utils/ValueMapper.h"
75 #include <algorithm>
76 #include <cassert>
77 #include <cstdint>
78 #include <iterator>
79 #include <memory>
80 #include <utility>
81 
82 using namespace llvm;
83 using namespace jumpthreading;
84 
85 #define DEBUG_TYPE "jump-threading"
86 
87 STATISTIC(NumThreads, "Number of jumps threaded");
88 STATISTIC(NumFolds,   "Number of terminators folded");
89 STATISTIC(NumDupes,   "Number of branch blocks duplicated to eliminate phi");
90 
91 static cl::opt<unsigned>
92 BBDuplicateThreshold("jump-threading-threshold",
93           cl::desc("Max block size to duplicate for jump threading"),
94           cl::init(6), cl::Hidden);
95 
96 static cl::opt<unsigned>
97 ImplicationSearchThreshold(
98   "jump-threading-implication-search-threshold",
99   cl::desc("The number of predecessors to search for a stronger "
100            "condition to use to thread over a weaker condition"),
101   cl::init(3), cl::Hidden);
102 
103 static cl::opt<unsigned> PhiDuplicateThreshold(
104     "jump-threading-phi-threshold",
105     cl::desc("Max PHIs in BB to duplicate for jump threading"), cl::init(76),
106     cl::Hidden);
107 
108 static cl::opt<bool> PrintLVIAfterJumpThreading(
109     "print-lvi-after-jump-threading",
110     cl::desc("Print the LazyValueInfo cache after JumpThreading"), cl::init(false),
111     cl::Hidden);
112 
113 static cl::opt<bool> ThreadAcrossLoopHeaders(
114     "jump-threading-across-loop-headers",
115     cl::desc("Allow JumpThreading to thread across loop headers, for testing"),
116     cl::init(false), cl::Hidden);
117 
118 
119 namespace {
120 
121   /// This pass performs 'jump threading', which looks at blocks that have
122   /// multiple predecessors and multiple successors.  If one or more of the
123   /// predecessors of the block can be proven to always jump to one of the
124   /// successors, we forward the edge from the predecessor to the successor by
125   /// duplicating the contents of this block.
126   ///
127   /// An example of when this can occur is code like this:
128   ///
129   ///   if () { ...
130   ///     X = 4;
131   ///   }
132   ///   if (X < 3) {
133   ///
134   /// In this case, the unconditional branch at the end of the first if can be
135   /// revectored to the false side of the second if.
136   class JumpThreading : public FunctionPass {
137   public:
138     static char ID; // Pass identification
139 
140     JumpThreading(int T = -1) : FunctionPass(ID) {
141       initializeJumpThreadingPass(*PassRegistry::getPassRegistry());
142     }
143 
144     bool runOnFunction(Function &F) override;
145 
146     void getAnalysisUsage(AnalysisUsage &AU) const override {
147       AU.addRequired<DominatorTreeWrapperPass>();
148       AU.addPreserved<DominatorTreeWrapperPass>();
149       AU.addRequired<AAResultsWrapperPass>();
150       AU.addRequired<LazyValueInfoWrapperPass>();
151       AU.addPreserved<LazyValueInfoWrapperPass>();
152       AU.addPreserved<GlobalsAAWrapperPass>();
153       AU.addRequired<TargetLibraryInfoWrapperPass>();
154       AU.addRequired<TargetTransformInfoWrapperPass>();
155     }
156   };
157 
158 } // end anonymous namespace
159 
160 char JumpThreading::ID = 0;
161 
162 INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading",
163                 "Jump Threading", false, false)
164 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
165 INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
166 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
167 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
168 INITIALIZE_PASS_END(JumpThreading, "jump-threading",
169                 "Jump Threading", false, false)
170 
171 // Public interface to the Jump Threading pass
172 FunctionPass *llvm::createJumpThreadingPass(int Threshold) {
173   return new JumpThreading(Threshold);
174 }
175 
176 JumpThreadingPass::JumpThreadingPass(int T) {
177   DefaultBBDupThreshold = (T == -1) ? BBDuplicateThreshold : unsigned(T);
178 }
179 
180 // Update branch probability information according to conditional
181 // branch probability. This is usually made possible for cloned branches
182 // in inline instances by the context specific profile in the caller.
183 // For instance,
184 //
185 //  [Block PredBB]
186 //  [Branch PredBr]
187 //  if (t) {
188 //     Block A;
189 //  } else {
190 //     Block B;
191 //  }
192 //
193 //  [Block BB]
194 //  cond = PN([true, %A], [..., %B]); // PHI node
195 //  [Branch CondBr]
196 //  if (cond) {
197 //    ...  // P(cond == true) = 1%
198 //  }
199 //
200 //  Here we know that when block A is taken, cond must be true, which means
201 //      P(cond == true | A) = 1
202 //
203 //  Given that P(cond == true) = P(cond == true | A) * P(A) +
204 //                               P(cond == true | B) * P(B)
205 //  we get:
206 //     P(cond == true ) = P(A) + P(cond == true | B) * P(B)
207 //
208 //  which gives us:
209 //     P(A) is less than P(cond == true), i.e.
210 //     P(t == true) <= P(cond == true)
211 //
212 //  In other words, if we know P(cond == true) is unlikely, we know
213 //  that P(t == true) is also unlikely.
214 //
215 static void updatePredecessorProfileMetadata(PHINode *PN, BasicBlock *BB) {
216   BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
217   if (!CondBr)
218     return;
219 
220   uint64_t TrueWeight, FalseWeight;
221   if (!extractBranchWeights(*CondBr, TrueWeight, FalseWeight))
222     return;
223 
224   if (TrueWeight + FalseWeight == 0)
225     // Zero branch_weights do not give a hint for getting branch probabilities.
226     // Technically it would result in division by zero denominator, which is
227     // TrueWeight + FalseWeight.
228     return;
229 
230   // Returns the outgoing edge of the dominating predecessor block
231   // that leads to the PhiNode's incoming block:
232   auto GetPredOutEdge =
233       [](BasicBlock *IncomingBB,
234          BasicBlock *PhiBB) -> std::pair<BasicBlock *, BasicBlock *> {
235     auto *PredBB = IncomingBB;
236     auto *SuccBB = PhiBB;
237     SmallPtrSet<BasicBlock *, 16> Visited;
238     while (true) {
239       BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
240       if (PredBr && PredBr->isConditional())
241         return {PredBB, SuccBB};
242       Visited.insert(PredBB);
243       auto *SinglePredBB = PredBB->getSinglePredecessor();
244       if (!SinglePredBB)
245         return {nullptr, nullptr};
246 
247       // Stop searching when SinglePredBB has been visited. It means we see
248       // an unreachable loop.
249       if (Visited.count(SinglePredBB))
250         return {nullptr, nullptr};
251 
252       SuccBB = PredBB;
253       PredBB = SinglePredBB;
254     }
255   };
256 
257   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
258     Value *PhiOpnd = PN->getIncomingValue(i);
259     ConstantInt *CI = dyn_cast<ConstantInt>(PhiOpnd);
260 
261     if (!CI || !CI->getType()->isIntegerTy(1))
262       continue;
263 
264     BranchProbability BP =
265         (CI->isOne() ? BranchProbability::getBranchProbability(
266                            TrueWeight, TrueWeight + FalseWeight)
267                      : BranchProbability::getBranchProbability(
268                            FalseWeight, TrueWeight + FalseWeight));
269 
270     auto PredOutEdge = GetPredOutEdge(PN->getIncomingBlock(i), BB);
271     if (!PredOutEdge.first)
272       return;
273 
274     BasicBlock *PredBB = PredOutEdge.first;
275     BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
276     if (!PredBr)
277       return;
278 
279     uint64_t PredTrueWeight, PredFalseWeight;
280     // FIXME: We currently only set the profile data when it is missing.
281     // With PGO, this can be used to refine even existing profile data with
282     // context information. This needs to be done after more performance
283     // testing.
284     if (extractBranchWeights(*PredBr, PredTrueWeight, PredFalseWeight))
285       continue;
286 
287     // We can not infer anything useful when BP >= 50%, because BP is the
288     // upper bound probability value.
289     if (BP >= BranchProbability(50, 100))
290       continue;
291 
292     SmallVector<uint32_t, 2> Weights;
293     if (PredBr->getSuccessor(0) == PredOutEdge.second) {
294       Weights.push_back(BP.getNumerator());
295       Weights.push_back(BP.getCompl().getNumerator());
296     } else {
297       Weights.push_back(BP.getCompl().getNumerator());
298       Weights.push_back(BP.getNumerator());
299     }
300     PredBr->setMetadata(LLVMContext::MD_prof,
301                         MDBuilder(PredBr->getParent()->getContext())
302                             .createBranchWeights(Weights));
303   }
304 }
305 
306 /// runOnFunction - Toplevel algorithm.
307 bool JumpThreading::runOnFunction(Function &F) {
308   if (skipFunction(F))
309     return false;
310   auto TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
311   // Jump Threading has no sense for the targets with divergent CF
312   if (TTI->hasBranchDivergence())
313     return false;
314   auto TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
315   auto DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
316   auto LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
317   auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
318   std::unique_ptr<BlockFrequencyInfo> BFI;
319   std::unique_ptr<BranchProbabilityInfo> BPI;
320   if (F.hasProfileData()) {
321     LoopInfo LI{*DT};
322     BPI.reset(new BranchProbabilityInfo(F, LI, TLI));
323     BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
324   }
325 
326   JumpThreadingPass Impl;
327   bool Changed = Impl.runImpl(F, nullptr, TLI, TTI, LVI, AA,
328                               std::make_unique<DomTreeUpdater>(
329                                   DT, DomTreeUpdater::UpdateStrategy::Lazy),
330                               BFI.get(), BPI.get());
331   if (PrintLVIAfterJumpThreading) {
332     dbgs() << "LVI for function '" << F.getName() << "':\n";
333     LVI->printLVI(F, Impl.getDomTreeUpdater()->getDomTree(), dbgs());
334   }
335   return Changed;
336 }
337 
338 PreservedAnalyses JumpThreadingPass::run(Function &F,
339                                          FunctionAnalysisManager &AM) {
340   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
341   // Jump Threading has no sense for the targets with divergent CF
342   if (TTI.hasBranchDivergence())
343     return PreservedAnalyses::all();
344   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
345   auto &LVI = AM.getResult<LazyValueAnalysis>(F);
346   auto &AA = AM.getResult<AAManager>(F);
347   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
348 
349   bool Changed =
350       runImpl(F, &AM, &TLI, &TTI, &LVI, &AA,
351               std::make_unique<DomTreeUpdater>(
352                   &DT, nullptr, DomTreeUpdater::UpdateStrategy::Lazy),
353               std::nullopt, std::nullopt);
354 
355   if (PrintLVIAfterJumpThreading) {
356     dbgs() << "LVI for function '" << F.getName() << "':\n";
357     LVI.printLVI(F, getDomTreeUpdater()->getDomTree(), dbgs());
358   }
359 
360   if (!Changed)
361     return PreservedAnalyses::all();
362 
363 
364   getDomTreeUpdater()->flush();
365 
366 #if defined(EXPENSIVE_CHECKS)
367   assert(getDomTreeUpdater()->getDomTree().verify(
368              DominatorTree::VerificationLevel::Full) &&
369          "DT broken after JumpThreading");
370   assert((!getDomTreeUpdater()->hasPostDomTree() ||
371           getDomTreeUpdater()->getPostDomTree().verify(
372               PostDominatorTree::VerificationLevel::Full)) &&
373          "PDT broken after JumpThreading");
374 #else
375   assert(getDomTreeUpdater()->getDomTree().verify(
376              DominatorTree::VerificationLevel::Fast) &&
377          "DT broken after JumpThreading");
378   assert((!getDomTreeUpdater()->hasPostDomTree() ||
379           getDomTreeUpdater()->getPostDomTree().verify(
380               PostDominatorTree::VerificationLevel::Fast)) &&
381          "PDT broken after JumpThreading");
382 #endif
383 
384   return getPreservedAnalysis();
385 }
386 
387 bool JumpThreadingPass::runImpl(Function &F_, FunctionAnalysisManager *FAM_,
388                                 TargetLibraryInfo *TLI_,
389                                 TargetTransformInfo *TTI_, LazyValueInfo *LVI_,
390                                 AliasAnalysis *AA_,
391                                 std::unique_ptr<DomTreeUpdater> DTU_,
392                                 std::optional<BlockFrequencyInfo *> BFI_,
393                                 std::optional<BranchProbabilityInfo *> BPI_) {
394   LLVM_DEBUG(dbgs() << "Jump threading on function '" << F_.getName() << "'\n");
395   F = &F_;
396   FAM = FAM_;
397   TLI = TLI_;
398   TTI = TTI_;
399   LVI = LVI_;
400   AA = AA_;
401   DTU = std::move(DTU_);
402   BFI = BFI_;
403   BPI = BPI_;
404   auto *GuardDecl = F->getParent()->getFunction(
405       Intrinsic::getName(Intrinsic::experimental_guard));
406   HasGuards = GuardDecl && !GuardDecl->use_empty();
407 
408   // Reduce the number of instructions duplicated when optimizing strictly for
409   // size.
410   if (BBDuplicateThreshold.getNumOccurrences())
411     BBDupThreshold = BBDuplicateThreshold;
412   else if (F->hasFnAttribute(Attribute::MinSize))
413     BBDupThreshold = 3;
414   else
415     BBDupThreshold = DefaultBBDupThreshold;
416 
417   // JumpThreading must not processes blocks unreachable from entry. It's a
418   // waste of compute time and can potentially lead to hangs.
419   SmallPtrSet<BasicBlock *, 16> Unreachable;
420   assert(DTU && "DTU isn't passed into JumpThreading before using it.");
421   assert(DTU->hasDomTree() && "JumpThreading relies on DomTree to proceed.");
422   DominatorTree &DT = DTU->getDomTree();
423   for (auto &BB : *F)
424     if (!DT.isReachableFromEntry(&BB))
425       Unreachable.insert(&BB);
426 
427   if (!ThreadAcrossLoopHeaders)
428     findLoopHeaders(*F);
429 
430   bool EverChanged = false;
431   bool Changed;
432   do {
433     Changed = false;
434     for (auto &BB : *F) {
435       if (Unreachable.count(&BB))
436         continue;
437       while (processBlock(&BB)) // Thread all of the branches we can over BB.
438         Changed = ChangedSinceLastAnalysisUpdate = true;
439 
440       // Jump threading may have introduced redundant debug values into BB
441       // which should be removed.
442       if (Changed)
443         RemoveRedundantDbgInstrs(&BB);
444 
445       // Stop processing BB if it's the entry or is now deleted. The following
446       // routines attempt to eliminate BB and locating a suitable replacement
447       // for the entry is non-trivial.
448       if (&BB == &F->getEntryBlock() || DTU->isBBPendingDeletion(&BB))
449         continue;
450 
451       if (pred_empty(&BB)) {
452         // When processBlock makes BB unreachable it doesn't bother to fix up
453         // the instructions in it. We must remove BB to prevent invalid IR.
454         LLVM_DEBUG(dbgs() << "  JT: Deleting dead block '" << BB.getName()
455                           << "' with terminator: " << *BB.getTerminator()
456                           << '\n');
457         LoopHeaders.erase(&BB);
458         LVI->eraseBlock(&BB);
459         DeleteDeadBlock(&BB, DTU.get());
460         Changed = ChangedSinceLastAnalysisUpdate = true;
461         continue;
462       }
463 
464       // processBlock doesn't thread BBs with unconditional TIs. However, if BB
465       // is "almost empty", we attempt to merge BB with its sole successor.
466       auto *BI = dyn_cast<BranchInst>(BB.getTerminator());
467       if (BI && BI->isUnconditional()) {
468         BasicBlock *Succ = BI->getSuccessor(0);
469         if (
470             // The terminator must be the only non-phi instruction in BB.
471             BB.getFirstNonPHIOrDbg(true)->isTerminator() &&
472             // Don't alter Loop headers and latches to ensure another pass can
473             // detect and transform nested loops later.
474             !LoopHeaders.count(&BB) && !LoopHeaders.count(Succ) &&
475             TryToSimplifyUncondBranchFromEmptyBlock(&BB, DTU.get())) {
476           RemoveRedundantDbgInstrs(Succ);
477           // BB is valid for cleanup here because we passed in DTU. F remains
478           // BB's parent until a DTU->getDomTree() event.
479           LVI->eraseBlock(&BB);
480           Changed = ChangedSinceLastAnalysisUpdate = true;
481         }
482       }
483     }
484     EverChanged |= Changed;
485   } while (Changed);
486 
487   LoopHeaders.clear();
488   return EverChanged;
489 }
490 
491 // Replace uses of Cond with ToVal when safe to do so. If all uses are
492 // replaced, we can remove Cond. We cannot blindly replace all uses of Cond
493 // because we may incorrectly replace uses when guards/assumes are uses of
494 // of `Cond` and we used the guards/assume to reason about the `Cond` value
495 // at the end of block. RAUW unconditionally replaces all uses
496 // including the guards/assumes themselves and the uses before the
497 // guard/assume.
498 static bool replaceFoldableUses(Instruction *Cond, Value *ToVal,
499                                 BasicBlock *KnownAtEndOfBB) {
500   bool Changed = false;
501   assert(Cond->getType() == ToVal->getType());
502   // We can unconditionally replace all uses in non-local blocks (i.e. uses
503   // strictly dominated by BB), since LVI information is true from the
504   // terminator of BB.
505   if (Cond->getParent() == KnownAtEndOfBB)
506     Changed |= replaceNonLocalUsesWith(Cond, ToVal);
507   for (Instruction &I : reverse(*KnownAtEndOfBB)) {
508     // Reached the Cond whose uses we are trying to replace, so there are no
509     // more uses.
510     if (&I == Cond)
511       break;
512     // We only replace uses in instructions that are guaranteed to reach the end
513     // of BB, where we know Cond is ToVal.
514     if (!isGuaranteedToTransferExecutionToSuccessor(&I))
515       break;
516     Changed |= I.replaceUsesOfWith(Cond, ToVal);
517   }
518   if (Cond->use_empty() && !Cond->mayHaveSideEffects()) {
519     Cond->eraseFromParent();
520     Changed = true;
521   }
522   return Changed;
523 }
524 
525 /// Return the cost of duplicating a piece of this block from first non-phi
526 /// and before StopAt instruction to thread across it. Stop scanning the block
527 /// when exceeding the threshold. If duplication is impossible, returns ~0U.
528 static unsigned getJumpThreadDuplicationCost(const TargetTransformInfo *TTI,
529                                              BasicBlock *BB,
530                                              Instruction *StopAt,
531                                              unsigned Threshold) {
532   assert(StopAt->getParent() == BB && "Not an instruction from proper BB?");
533 
534   // Do not duplicate the BB if it has a lot of PHI nodes.
535   // If a threadable chain is too long then the number of PHI nodes can add up,
536   // leading to a substantial increase in compile time when rewriting the SSA.
537   unsigned PhiCount = 0;
538   Instruction *FirstNonPHI = nullptr;
539   for (Instruction &I : *BB) {
540     if (!isa<PHINode>(&I)) {
541       FirstNonPHI = &I;
542       break;
543     }
544     if (++PhiCount > PhiDuplicateThreshold)
545       return ~0U;
546   }
547 
548   /// Ignore PHI nodes, these will be flattened when duplication happens.
549   BasicBlock::const_iterator I(FirstNonPHI);
550 
551   // FIXME: THREADING will delete values that are just used to compute the
552   // branch, so they shouldn't count against the duplication cost.
553 
554   unsigned Bonus = 0;
555   if (BB->getTerminator() == StopAt) {
556     // Threading through a switch statement is particularly profitable.  If this
557     // block ends in a switch, decrease its cost to make it more likely to
558     // happen.
559     if (isa<SwitchInst>(StopAt))
560       Bonus = 6;
561 
562     // The same holds for indirect branches, but slightly more so.
563     if (isa<IndirectBrInst>(StopAt))
564       Bonus = 8;
565   }
566 
567   // Bump the threshold up so the early exit from the loop doesn't skip the
568   // terminator-based Size adjustment at the end.
569   Threshold += Bonus;
570 
571   // Sum up the cost of each instruction until we get to the terminator.  Don't
572   // include the terminator because the copy won't include it.
573   unsigned Size = 0;
574   for (; &*I != StopAt; ++I) {
575 
576     // Stop scanning the block if we've reached the threshold.
577     if (Size > Threshold)
578       return Size;
579 
580     // Bail out if this instruction gives back a token type, it is not possible
581     // to duplicate it if it is used outside this BB.
582     if (I->getType()->isTokenTy() && I->isUsedOutsideOfBlock(BB))
583       return ~0U;
584 
585     // Blocks with NoDuplicate are modelled as having infinite cost, so they
586     // are never duplicated.
587     if (const CallInst *CI = dyn_cast<CallInst>(I))
588       if (CI->cannotDuplicate() || CI->isConvergent())
589         return ~0U;
590 
591     if (TTI->getInstructionCost(&*I, TargetTransformInfo::TCK_SizeAndLatency) ==
592         TargetTransformInfo::TCC_Free)
593       continue;
594 
595     // All other instructions count for at least one unit.
596     ++Size;
597 
598     // Calls are more expensive.  If they are non-intrinsic calls, we model them
599     // as having cost of 4.  If they are a non-vector intrinsic, we model them
600     // as having cost of 2 total, and if they are a vector intrinsic, we model
601     // them as having cost 1.
602     if (const CallInst *CI = dyn_cast<CallInst>(I)) {
603       if (!isa<IntrinsicInst>(CI))
604         Size += 3;
605       else if (!CI->getType()->isVectorTy())
606         Size += 1;
607     }
608   }
609 
610   return Size > Bonus ? Size - Bonus : 0;
611 }
612 
613 /// findLoopHeaders - We do not want jump threading to turn proper loop
614 /// structures into irreducible loops.  Doing this breaks up the loop nesting
615 /// hierarchy and pessimizes later transformations.  To prevent this from
616 /// happening, we first have to find the loop headers.  Here we approximate this
617 /// by finding targets of backedges in the CFG.
618 ///
619 /// Note that there definitely are cases when we want to allow threading of
620 /// edges across a loop header.  For example, threading a jump from outside the
621 /// loop (the preheader) to an exit block of the loop is definitely profitable.
622 /// It is also almost always profitable to thread backedges from within the loop
623 /// to exit blocks, and is often profitable to thread backedges to other blocks
624 /// within the loop (forming a nested loop).  This simple analysis is not rich
625 /// enough to track all of these properties and keep it up-to-date as the CFG
626 /// mutates, so we don't allow any of these transformations.
627 void JumpThreadingPass::findLoopHeaders(Function &F) {
628   SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
629   FindFunctionBackedges(F, Edges);
630 
631   for (const auto &Edge : Edges)
632     LoopHeaders.insert(Edge.second);
633 }
634 
635 /// getKnownConstant - Helper method to determine if we can thread over a
636 /// terminator with the given value as its condition, and if so what value to
637 /// use for that. What kind of value this is depends on whether we want an
638 /// integer or a block address, but an undef is always accepted.
639 /// Returns null if Val is null or not an appropriate constant.
640 static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) {
641   if (!Val)
642     return nullptr;
643 
644   // Undef is "known" enough.
645   if (UndefValue *U = dyn_cast<UndefValue>(Val))
646     return U;
647 
648   if (Preference == WantBlockAddress)
649     return dyn_cast<BlockAddress>(Val->stripPointerCasts());
650 
651   return dyn_cast<ConstantInt>(Val);
652 }
653 
654 /// computeValueKnownInPredecessors - Given a basic block BB and a value V, see
655 /// if we can infer that the value is a known ConstantInt/BlockAddress or undef
656 /// in any of our predecessors.  If so, return the known list of value and pred
657 /// BB in the result vector.
658 ///
659 /// This returns true if there were any known values.
660 bool JumpThreadingPass::computeValueKnownInPredecessorsImpl(
661     Value *V, BasicBlock *BB, PredValueInfo &Result,
662     ConstantPreference Preference, DenseSet<Value *> &RecursionSet,
663     Instruction *CxtI) {
664   // This method walks up use-def chains recursively.  Because of this, we could
665   // get into an infinite loop going around loops in the use-def chain.  To
666   // prevent this, keep track of what (value, block) pairs we've already visited
667   // and terminate the search if we loop back to them
668   if (!RecursionSet.insert(V).second)
669     return false;
670 
671   // If V is a constant, then it is known in all predecessors.
672   if (Constant *KC = getKnownConstant(V, Preference)) {
673     for (BasicBlock *Pred : predecessors(BB))
674       Result.emplace_back(KC, Pred);
675 
676     return !Result.empty();
677   }
678 
679   // If V is a non-instruction value, or an instruction in a different block,
680   // then it can't be derived from a PHI.
681   Instruction *I = dyn_cast<Instruction>(V);
682   if (!I || I->getParent() != BB) {
683 
684     // Okay, if this is a live-in value, see if it has a known value at the any
685     // edge from our predecessors.
686     for (BasicBlock *P : predecessors(BB)) {
687       using namespace PatternMatch;
688       // If the value is known by LazyValueInfo to be a constant in a
689       // predecessor, use that information to try to thread this block.
690       Constant *PredCst = LVI->getConstantOnEdge(V, P, BB, CxtI);
691       // If I is a non-local compare-with-constant instruction, use more-rich
692       // 'getPredicateOnEdge' method. This would be able to handle value
693       // inequalities better, for example if the compare is "X < 4" and "X < 3"
694       // is known true but "X < 4" itself is not available.
695       CmpInst::Predicate Pred;
696       Value *Val;
697       Constant *Cst;
698       if (!PredCst && match(V, m_Cmp(Pred, m_Value(Val), m_Constant(Cst)))) {
699         auto Res = LVI->getPredicateOnEdge(Pred, Val, Cst, P, BB, CxtI);
700         if (Res != LazyValueInfo::Unknown)
701           PredCst = ConstantInt::getBool(V->getContext(), Res);
702       }
703       if (Constant *KC = getKnownConstant(PredCst, Preference))
704         Result.emplace_back(KC, P);
705     }
706 
707     return !Result.empty();
708   }
709 
710   /// If I is a PHI node, then we know the incoming values for any constants.
711   if (PHINode *PN = dyn_cast<PHINode>(I)) {
712     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
713       Value *InVal = PN->getIncomingValue(i);
714       if (Constant *KC = getKnownConstant(InVal, Preference)) {
715         Result.emplace_back(KC, PN->getIncomingBlock(i));
716       } else {
717         Constant *CI = LVI->getConstantOnEdge(InVal,
718                                               PN->getIncomingBlock(i),
719                                               BB, CxtI);
720         if (Constant *KC = getKnownConstant(CI, Preference))
721           Result.emplace_back(KC, PN->getIncomingBlock(i));
722       }
723     }
724 
725     return !Result.empty();
726   }
727 
728   // Handle Cast instructions.
729   if (CastInst *CI = dyn_cast<CastInst>(I)) {
730     Value *Source = CI->getOperand(0);
731     computeValueKnownInPredecessorsImpl(Source, BB, Result, Preference,
732                                         RecursionSet, CxtI);
733     if (Result.empty())
734       return false;
735 
736     // Convert the known values.
737     for (auto &R : Result)
738       R.first = ConstantExpr::getCast(CI->getOpcode(), R.first, CI->getType());
739 
740     return true;
741   }
742 
743   if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) {
744     Value *Source = FI->getOperand(0);
745     computeValueKnownInPredecessorsImpl(Source, BB, Result, Preference,
746                                         RecursionSet, CxtI);
747 
748     erase_if(Result, [](auto &Pair) {
749       return !isGuaranteedNotToBeUndefOrPoison(Pair.first);
750     });
751 
752     return !Result.empty();
753   }
754 
755   // Handle some boolean conditions.
756   if (I->getType()->getPrimitiveSizeInBits() == 1) {
757     using namespace PatternMatch;
758     if (Preference != WantInteger)
759       return false;
760     // X | true -> true
761     // X & false -> false
762     Value *Op0, *Op1;
763     if (match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
764         match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
765       PredValueInfoTy LHSVals, RHSVals;
766 
767       computeValueKnownInPredecessorsImpl(Op0, BB, LHSVals, WantInteger,
768                                           RecursionSet, CxtI);
769       computeValueKnownInPredecessorsImpl(Op1, BB, RHSVals, WantInteger,
770                                           RecursionSet, CxtI);
771 
772       if (LHSVals.empty() && RHSVals.empty())
773         return false;
774 
775       ConstantInt *InterestingVal;
776       if (match(I, m_LogicalOr()))
777         InterestingVal = ConstantInt::getTrue(I->getContext());
778       else
779         InterestingVal = ConstantInt::getFalse(I->getContext());
780 
781       SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
782 
783       // Scan for the sentinel.  If we find an undef, force it to the
784       // interesting value: x|undef -> true and x&undef -> false.
785       for (const auto &LHSVal : LHSVals)
786         if (LHSVal.first == InterestingVal || isa<UndefValue>(LHSVal.first)) {
787           Result.emplace_back(InterestingVal, LHSVal.second);
788           LHSKnownBBs.insert(LHSVal.second);
789         }
790       for (const auto &RHSVal : RHSVals)
791         if (RHSVal.first == InterestingVal || isa<UndefValue>(RHSVal.first)) {
792           // If we already inferred a value for this block on the LHS, don't
793           // re-add it.
794           if (!LHSKnownBBs.count(RHSVal.second))
795             Result.emplace_back(InterestingVal, RHSVal.second);
796         }
797 
798       return !Result.empty();
799     }
800 
801     // Handle the NOT form of XOR.
802     if (I->getOpcode() == Instruction::Xor &&
803         isa<ConstantInt>(I->getOperand(1)) &&
804         cast<ConstantInt>(I->getOperand(1))->isOne()) {
805       computeValueKnownInPredecessorsImpl(I->getOperand(0), BB, Result,
806                                           WantInteger, RecursionSet, CxtI);
807       if (Result.empty())
808         return false;
809 
810       // Invert the known values.
811       for (auto &R : Result)
812         R.first = ConstantExpr::getNot(R.first);
813 
814       return true;
815     }
816 
817   // Try to simplify some other binary operator values.
818   } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
819     if (Preference != WantInteger)
820       return false;
821     if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
822       const DataLayout &DL = BO->getModule()->getDataLayout();
823       PredValueInfoTy LHSVals;
824       computeValueKnownInPredecessorsImpl(BO->getOperand(0), BB, LHSVals,
825                                           WantInteger, RecursionSet, CxtI);
826 
827       // Try to use constant folding to simplify the binary operator.
828       for (const auto &LHSVal : LHSVals) {
829         Constant *V = LHSVal.first;
830         Constant *Folded =
831             ConstantFoldBinaryOpOperands(BO->getOpcode(), V, CI, DL);
832 
833         if (Constant *KC = getKnownConstant(Folded, WantInteger))
834           Result.emplace_back(KC, LHSVal.second);
835       }
836     }
837 
838     return !Result.empty();
839   }
840 
841   // Handle compare with phi operand, where the PHI is defined in this block.
842   if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
843     if (Preference != WantInteger)
844       return false;
845     Type *CmpType = Cmp->getType();
846     Value *CmpLHS = Cmp->getOperand(0);
847     Value *CmpRHS = Cmp->getOperand(1);
848     CmpInst::Predicate Pred = Cmp->getPredicate();
849 
850     PHINode *PN = dyn_cast<PHINode>(CmpLHS);
851     if (!PN)
852       PN = dyn_cast<PHINode>(CmpRHS);
853     if (PN && PN->getParent() == BB) {
854       const DataLayout &DL = PN->getModule()->getDataLayout();
855       // We can do this simplification if any comparisons fold to true or false.
856       // See if any do.
857       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
858         BasicBlock *PredBB = PN->getIncomingBlock(i);
859         Value *LHS, *RHS;
860         if (PN == CmpLHS) {
861           LHS = PN->getIncomingValue(i);
862           RHS = CmpRHS->DoPHITranslation(BB, PredBB);
863         } else {
864           LHS = CmpLHS->DoPHITranslation(BB, PredBB);
865           RHS = PN->getIncomingValue(i);
866         }
867         Value *Res = simplifyCmpInst(Pred, LHS, RHS, {DL});
868         if (!Res) {
869           if (!isa<Constant>(RHS))
870             continue;
871 
872           // getPredicateOnEdge call will make no sense if LHS is defined in BB.
873           auto LHSInst = dyn_cast<Instruction>(LHS);
874           if (LHSInst && LHSInst->getParent() == BB)
875             continue;
876 
877           LazyValueInfo::Tristate
878             ResT = LVI->getPredicateOnEdge(Pred, LHS,
879                                            cast<Constant>(RHS), PredBB, BB,
880                                            CxtI ? CxtI : Cmp);
881           if (ResT == LazyValueInfo::Unknown)
882             continue;
883           Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
884         }
885 
886         if (Constant *KC = getKnownConstant(Res, WantInteger))
887           Result.emplace_back(KC, PredBB);
888       }
889 
890       return !Result.empty();
891     }
892 
893     // If comparing a live-in value against a constant, see if we know the
894     // live-in value on any predecessors.
895     if (isa<Constant>(CmpRHS) && !CmpType->isVectorTy()) {
896       Constant *CmpConst = cast<Constant>(CmpRHS);
897 
898       if (!isa<Instruction>(CmpLHS) ||
899           cast<Instruction>(CmpLHS)->getParent() != BB) {
900         for (BasicBlock *P : predecessors(BB)) {
901           // If the value is known by LazyValueInfo to be a constant in a
902           // predecessor, use that information to try to thread this block.
903           LazyValueInfo::Tristate Res =
904             LVI->getPredicateOnEdge(Pred, CmpLHS,
905                                     CmpConst, P, BB, CxtI ? CxtI : Cmp);
906           if (Res == LazyValueInfo::Unknown)
907             continue;
908 
909           Constant *ResC = ConstantInt::get(CmpType, Res);
910           Result.emplace_back(ResC, P);
911         }
912 
913         return !Result.empty();
914       }
915 
916       // InstCombine can fold some forms of constant range checks into
917       // (icmp (add (x, C1)), C2). See if we have we have such a thing with
918       // x as a live-in.
919       {
920         using namespace PatternMatch;
921 
922         Value *AddLHS;
923         ConstantInt *AddConst;
924         if (isa<ConstantInt>(CmpConst) &&
925             match(CmpLHS, m_Add(m_Value(AddLHS), m_ConstantInt(AddConst)))) {
926           if (!isa<Instruction>(AddLHS) ||
927               cast<Instruction>(AddLHS)->getParent() != BB) {
928             for (BasicBlock *P : predecessors(BB)) {
929               // If the value is known by LazyValueInfo to be a ConstantRange in
930               // a predecessor, use that information to try to thread this
931               // block.
932               ConstantRange CR = LVI->getConstantRangeOnEdge(
933                   AddLHS, P, BB, CxtI ? CxtI : cast<Instruction>(CmpLHS));
934               // Propagate the range through the addition.
935               CR = CR.add(AddConst->getValue());
936 
937               // Get the range where the compare returns true.
938               ConstantRange CmpRange = ConstantRange::makeExactICmpRegion(
939                   Pred, cast<ConstantInt>(CmpConst)->getValue());
940 
941               Constant *ResC;
942               if (CmpRange.contains(CR))
943                 ResC = ConstantInt::getTrue(CmpType);
944               else if (CmpRange.inverse().contains(CR))
945                 ResC = ConstantInt::getFalse(CmpType);
946               else
947                 continue;
948 
949               Result.emplace_back(ResC, P);
950             }
951 
952             return !Result.empty();
953           }
954         }
955       }
956 
957       // Try to find a constant value for the LHS of a comparison,
958       // and evaluate it statically if we can.
959       PredValueInfoTy LHSVals;
960       computeValueKnownInPredecessorsImpl(I->getOperand(0), BB, LHSVals,
961                                           WantInteger, RecursionSet, CxtI);
962 
963       for (const auto &LHSVal : LHSVals) {
964         Constant *V = LHSVal.first;
965         Constant *Folded = ConstantExpr::getCompare(Pred, V, CmpConst);
966         if (Constant *KC = getKnownConstant(Folded, WantInteger))
967           Result.emplace_back(KC, LHSVal.second);
968       }
969 
970       return !Result.empty();
971     }
972   }
973 
974   if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
975     // Handle select instructions where at least one operand is a known constant
976     // and we can figure out the condition value for any predecessor block.
977     Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference);
978     Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference);
979     PredValueInfoTy Conds;
980     if ((TrueVal || FalseVal) &&
981         computeValueKnownInPredecessorsImpl(SI->getCondition(), BB, Conds,
982                                             WantInteger, RecursionSet, CxtI)) {
983       for (auto &C : Conds) {
984         Constant *Cond = C.first;
985 
986         // Figure out what value to use for the condition.
987         bool KnownCond;
988         if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
989           // A known boolean.
990           KnownCond = CI->isOne();
991         } else {
992           assert(isa<UndefValue>(Cond) && "Unexpected condition value");
993           // Either operand will do, so be sure to pick the one that's a known
994           // constant.
995           // FIXME: Do this more cleverly if both values are known constants?
996           KnownCond = (TrueVal != nullptr);
997         }
998 
999         // See if the select has a known constant value for this predecessor.
1000         if (Constant *Val = KnownCond ? TrueVal : FalseVal)
1001           Result.emplace_back(Val, C.second);
1002       }
1003 
1004       return !Result.empty();
1005     }
1006   }
1007 
1008   // If all else fails, see if LVI can figure out a constant value for us.
1009   assert(CxtI->getParent() == BB && "CxtI should be in BB");
1010   Constant *CI = LVI->getConstant(V, CxtI);
1011   if (Constant *KC = getKnownConstant(CI, Preference)) {
1012     for (BasicBlock *Pred : predecessors(BB))
1013       Result.emplace_back(KC, Pred);
1014   }
1015 
1016   return !Result.empty();
1017 }
1018 
1019 /// GetBestDestForBranchOnUndef - If we determine that the specified block ends
1020 /// in an undefined jump, decide which block is best to revector to.
1021 ///
1022 /// Since we can pick an arbitrary destination, we pick the successor with the
1023 /// fewest predecessors.  This should reduce the in-degree of the others.
1024 static unsigned getBestDestForJumpOnUndef(BasicBlock *BB) {
1025   Instruction *BBTerm = BB->getTerminator();
1026   unsigned MinSucc = 0;
1027   BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
1028   // Compute the successor with the minimum number of predecessors.
1029   unsigned MinNumPreds = pred_size(TestBB);
1030   for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
1031     TestBB = BBTerm->getSuccessor(i);
1032     unsigned NumPreds = pred_size(TestBB);
1033     if (NumPreds < MinNumPreds) {
1034       MinSucc = i;
1035       MinNumPreds = NumPreds;
1036     }
1037   }
1038 
1039   return MinSucc;
1040 }
1041 
1042 static bool hasAddressTakenAndUsed(BasicBlock *BB) {
1043   if (!BB->hasAddressTaken()) return false;
1044 
1045   // If the block has its address taken, it may be a tree of dead constants
1046   // hanging off of it.  These shouldn't keep the block alive.
1047   BlockAddress *BA = BlockAddress::get(BB);
1048   BA->removeDeadConstantUsers();
1049   return !BA->use_empty();
1050 }
1051 
1052 /// processBlock - If there are any predecessors whose control can be threaded
1053 /// through to a successor, transform them now.
1054 bool JumpThreadingPass::processBlock(BasicBlock *BB) {
1055   // If the block is trivially dead, just return and let the caller nuke it.
1056   // This simplifies other transformations.
1057   if (DTU->isBBPendingDeletion(BB) ||
1058       (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()))
1059     return false;
1060 
1061   // If this block has a single predecessor, and if that pred has a single
1062   // successor, merge the blocks.  This encourages recursive jump threading
1063   // because now the condition in this block can be threaded through
1064   // predecessors of our predecessor block.
1065   if (maybeMergeBasicBlockIntoOnlyPred(BB))
1066     return true;
1067 
1068   if (tryToUnfoldSelectInCurrBB(BB))
1069     return true;
1070 
1071   // Look if we can propagate guards to predecessors.
1072   if (HasGuards && processGuards(BB))
1073     return true;
1074 
1075   // What kind of constant we're looking for.
1076   ConstantPreference Preference = WantInteger;
1077 
1078   // Look to see if the terminator is a conditional branch, switch or indirect
1079   // branch, if not we can't thread it.
1080   Value *Condition;
1081   Instruction *Terminator = BB->getTerminator();
1082   if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) {
1083     // Can't thread an unconditional jump.
1084     if (BI->isUnconditional()) return false;
1085     Condition = BI->getCondition();
1086   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) {
1087     Condition = SI->getCondition();
1088   } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) {
1089     // Can't thread indirect branch with no successors.
1090     if (IB->getNumSuccessors() == 0) return false;
1091     Condition = IB->getAddress()->stripPointerCasts();
1092     Preference = WantBlockAddress;
1093   } else {
1094     return false; // Must be an invoke or callbr.
1095   }
1096 
1097   // Keep track if we constant folded the condition in this invocation.
1098   bool ConstantFolded = false;
1099 
1100   // Run constant folding to see if we can reduce the condition to a simple
1101   // constant.
1102   if (Instruction *I = dyn_cast<Instruction>(Condition)) {
1103     Value *SimpleVal =
1104         ConstantFoldInstruction(I, BB->getModule()->getDataLayout(), TLI);
1105     if (SimpleVal) {
1106       I->replaceAllUsesWith(SimpleVal);
1107       if (isInstructionTriviallyDead(I, TLI))
1108         I->eraseFromParent();
1109       Condition = SimpleVal;
1110       ConstantFolded = true;
1111     }
1112   }
1113 
1114   // If the terminator is branching on an undef or freeze undef, we can pick any
1115   // of the successors to branch to.  Let getBestDestForJumpOnUndef decide.
1116   auto *FI = dyn_cast<FreezeInst>(Condition);
1117   if (isa<UndefValue>(Condition) ||
1118       (FI && isa<UndefValue>(FI->getOperand(0)) && FI->hasOneUse())) {
1119     unsigned BestSucc = getBestDestForJumpOnUndef(BB);
1120     std::vector<DominatorTree::UpdateType> Updates;
1121 
1122     // Fold the branch/switch.
1123     Instruction *BBTerm = BB->getTerminator();
1124     Updates.reserve(BBTerm->getNumSuccessors());
1125     for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
1126       if (i == BestSucc) continue;
1127       BasicBlock *Succ = BBTerm->getSuccessor(i);
1128       Succ->removePredecessor(BB, true);
1129       Updates.push_back({DominatorTree::Delete, BB, Succ});
1130     }
1131 
1132     LLVM_DEBUG(dbgs() << "  In block '" << BB->getName()
1133                       << "' folding undef terminator: " << *BBTerm << '\n');
1134     BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
1135     ++NumFolds;
1136     BBTerm->eraseFromParent();
1137     DTU->applyUpdatesPermissive(Updates);
1138     if (FI)
1139       FI->eraseFromParent();
1140     return true;
1141   }
1142 
1143   // If the terminator of this block is branching on a constant, simplify the
1144   // terminator to an unconditional branch.  This can occur due to threading in
1145   // other blocks.
1146   if (getKnownConstant(Condition, Preference)) {
1147     LLVM_DEBUG(dbgs() << "  In block '" << BB->getName()
1148                       << "' folding terminator: " << *BB->getTerminator()
1149                       << '\n');
1150     ++NumFolds;
1151     ConstantFoldTerminator(BB, true, nullptr, DTU.get());
1152     if (auto *BPI = getBPI())
1153       BPI->eraseBlock(BB);
1154     return true;
1155   }
1156 
1157   Instruction *CondInst = dyn_cast<Instruction>(Condition);
1158 
1159   // All the rest of our checks depend on the condition being an instruction.
1160   if (!CondInst) {
1161     // FIXME: Unify this with code below.
1162     if (processThreadableEdges(Condition, BB, Preference, Terminator))
1163       return true;
1164     return ConstantFolded;
1165   }
1166 
1167   // Some of the following optimization can safely work on the unfrozen cond.
1168   Value *CondWithoutFreeze = CondInst;
1169   if (auto *FI = dyn_cast<FreezeInst>(CondInst))
1170     CondWithoutFreeze = FI->getOperand(0);
1171 
1172   if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondWithoutFreeze)) {
1173     // If we're branching on a conditional, LVI might be able to determine
1174     // it's value at the branch instruction.  We only handle comparisons
1175     // against a constant at this time.
1176     if (Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1))) {
1177       LazyValueInfo::Tristate Ret =
1178           LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0),
1179                               CondConst, BB->getTerminator(),
1180                               /*UseBlockValue=*/false);
1181       if (Ret != LazyValueInfo::Unknown) {
1182         // We can safely replace *some* uses of the CondInst if it has
1183         // exactly one value as returned by LVI. RAUW is incorrect in the
1184         // presence of guards and assumes, that have the `Cond` as the use. This
1185         // is because we use the guards/assume to reason about the `Cond` value
1186         // at the end of block, but RAUW unconditionally replaces all uses
1187         // including the guards/assumes themselves and the uses before the
1188         // guard/assume.
1189         auto *CI = Ret == LazyValueInfo::True ?
1190           ConstantInt::getTrue(CondCmp->getType()) :
1191           ConstantInt::getFalse(CondCmp->getType());
1192         if (replaceFoldableUses(CondCmp, CI, BB))
1193           return true;
1194       }
1195 
1196       // We did not manage to simplify this branch, try to see whether
1197       // CondCmp depends on a known phi-select pattern.
1198       if (tryToUnfoldSelect(CondCmp, BB))
1199         return true;
1200     }
1201   }
1202 
1203   if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
1204     if (tryToUnfoldSelect(SI, BB))
1205       return true;
1206 
1207   // Check for some cases that are worth simplifying.  Right now we want to look
1208   // for loads that are used by a switch or by the condition for the branch.  If
1209   // we see one, check to see if it's partially redundant.  If so, insert a PHI
1210   // which can then be used to thread the values.
1211   Value *SimplifyValue = CondWithoutFreeze;
1212 
1213   if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
1214     if (isa<Constant>(CondCmp->getOperand(1)))
1215       SimplifyValue = CondCmp->getOperand(0);
1216 
1217   // TODO: There are other places where load PRE would be profitable, such as
1218   // more complex comparisons.
1219   if (LoadInst *LoadI = dyn_cast<LoadInst>(SimplifyValue))
1220     if (simplifyPartiallyRedundantLoad(LoadI))
1221       return true;
1222 
1223   // Before threading, try to propagate profile data backwards:
1224   if (PHINode *PN = dyn_cast<PHINode>(CondInst))
1225     if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
1226       updatePredecessorProfileMetadata(PN, BB);
1227 
1228   // Handle a variety of cases where we are branching on something derived from
1229   // a PHI node in the current block.  If we can prove that any predecessors
1230   // compute a predictable value based on a PHI node, thread those predecessors.
1231   if (processThreadableEdges(CondInst, BB, Preference, Terminator))
1232     return true;
1233 
1234   // If this is an otherwise-unfoldable branch on a phi node or freeze(phi) in
1235   // the current block, see if we can simplify.
1236   PHINode *PN = dyn_cast<PHINode>(CondWithoutFreeze);
1237   if (PN && PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
1238     return processBranchOnPHI(PN);
1239 
1240   // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
1241   if (CondInst->getOpcode() == Instruction::Xor &&
1242       CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
1243     return processBranchOnXOR(cast<BinaryOperator>(CondInst));
1244 
1245   // Search for a stronger dominating condition that can be used to simplify a
1246   // conditional branch leaving BB.
1247   if (processImpliedCondition(BB))
1248     return true;
1249 
1250   return false;
1251 }
1252 
1253 bool JumpThreadingPass::processImpliedCondition(BasicBlock *BB) {
1254   auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
1255   if (!BI || !BI->isConditional())
1256     return false;
1257 
1258   Value *Cond = BI->getCondition();
1259   // Assuming that predecessor's branch was taken, if pred's branch condition
1260   // (V) implies Cond, Cond can be either true, undef, or poison. In this case,
1261   // freeze(Cond) is either true or a nondeterministic value.
1262   // If freeze(Cond) has only one use, we can freely fold freeze(Cond) to true
1263   // without affecting other instructions.
1264   auto *FICond = dyn_cast<FreezeInst>(Cond);
1265   if (FICond && FICond->hasOneUse())
1266     Cond = FICond->getOperand(0);
1267   else
1268     FICond = nullptr;
1269 
1270   BasicBlock *CurrentBB = BB;
1271   BasicBlock *CurrentPred = BB->getSinglePredecessor();
1272   unsigned Iter = 0;
1273 
1274   auto &DL = BB->getModule()->getDataLayout();
1275 
1276   while (CurrentPred && Iter++ < ImplicationSearchThreshold) {
1277     auto *PBI = dyn_cast<BranchInst>(CurrentPred->getTerminator());
1278     if (!PBI || !PBI->isConditional())
1279       return false;
1280     if (PBI->getSuccessor(0) != CurrentBB && PBI->getSuccessor(1) != CurrentBB)
1281       return false;
1282 
1283     bool CondIsTrue = PBI->getSuccessor(0) == CurrentBB;
1284     std::optional<bool> Implication =
1285         isImpliedCondition(PBI->getCondition(), Cond, DL, CondIsTrue);
1286 
1287     // If the branch condition of BB (which is Cond) and CurrentPred are
1288     // exactly the same freeze instruction, Cond can be folded into CondIsTrue.
1289     if (!Implication && FICond && isa<FreezeInst>(PBI->getCondition())) {
1290       if (cast<FreezeInst>(PBI->getCondition())->getOperand(0) ==
1291           FICond->getOperand(0))
1292         Implication = CondIsTrue;
1293     }
1294 
1295     if (Implication) {
1296       BasicBlock *KeepSucc = BI->getSuccessor(*Implication ? 0 : 1);
1297       BasicBlock *RemoveSucc = BI->getSuccessor(*Implication ? 1 : 0);
1298       RemoveSucc->removePredecessor(BB);
1299       BranchInst *UncondBI = BranchInst::Create(KeepSucc, BI);
1300       UncondBI->setDebugLoc(BI->getDebugLoc());
1301       ++NumFolds;
1302       BI->eraseFromParent();
1303       if (FICond)
1304         FICond->eraseFromParent();
1305 
1306       DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, RemoveSucc}});
1307       if (auto *BPI = getBPI())
1308         BPI->eraseBlock(BB);
1309       return true;
1310     }
1311     CurrentBB = CurrentPred;
1312     CurrentPred = CurrentBB->getSinglePredecessor();
1313   }
1314 
1315   return false;
1316 }
1317 
1318 /// Return true if Op is an instruction defined in the given block.
1319 static bool isOpDefinedInBlock(Value *Op, BasicBlock *BB) {
1320   if (Instruction *OpInst = dyn_cast<Instruction>(Op))
1321     if (OpInst->getParent() == BB)
1322       return true;
1323   return false;
1324 }
1325 
1326 /// simplifyPartiallyRedundantLoad - If LoadI is an obviously partially
1327 /// redundant load instruction, eliminate it by replacing it with a PHI node.
1328 /// This is an important optimization that encourages jump threading, and needs
1329 /// to be run interlaced with other jump threading tasks.
1330 bool JumpThreadingPass::simplifyPartiallyRedundantLoad(LoadInst *LoadI) {
1331   // Don't hack volatile and ordered loads.
1332   if (!LoadI->isUnordered()) return false;
1333 
1334   // If the load is defined in a block with exactly one predecessor, it can't be
1335   // partially redundant.
1336   BasicBlock *LoadBB = LoadI->getParent();
1337   if (LoadBB->getSinglePredecessor())
1338     return false;
1339 
1340   // If the load is defined in an EH pad, it can't be partially redundant,
1341   // because the edges between the invoke and the EH pad cannot have other
1342   // instructions between them.
1343   if (LoadBB->isEHPad())
1344     return false;
1345 
1346   Value *LoadedPtr = LoadI->getOperand(0);
1347 
1348   // If the loaded operand is defined in the LoadBB and its not a phi,
1349   // it can't be available in predecessors.
1350   if (isOpDefinedInBlock(LoadedPtr, LoadBB) && !isa<PHINode>(LoadedPtr))
1351     return false;
1352 
1353   // Scan a few instructions up from the load, to see if it is obviously live at
1354   // the entry to its block.
1355   BasicBlock::iterator BBIt(LoadI);
1356   bool IsLoadCSE;
1357   if (Value *AvailableVal = FindAvailableLoadedValue(
1358           LoadI, LoadBB, BBIt, DefMaxInstsToScan, AA, &IsLoadCSE)) {
1359     // If the value of the load is locally available within the block, just use
1360     // it.  This frequently occurs for reg2mem'd allocas.
1361 
1362     if (IsLoadCSE) {
1363       LoadInst *NLoadI = cast<LoadInst>(AvailableVal);
1364       combineMetadataForCSE(NLoadI, LoadI, false);
1365     };
1366 
1367     // If the returned value is the load itself, replace with poison. This can
1368     // only happen in dead loops.
1369     if (AvailableVal == LoadI)
1370       AvailableVal = PoisonValue::get(LoadI->getType());
1371     if (AvailableVal->getType() != LoadI->getType())
1372       AvailableVal = CastInst::CreateBitOrPointerCast(
1373           AvailableVal, LoadI->getType(), "", LoadI);
1374     LoadI->replaceAllUsesWith(AvailableVal);
1375     LoadI->eraseFromParent();
1376     return true;
1377   }
1378 
1379   // Otherwise, if we scanned the whole block and got to the top of the block,
1380   // we know the block is locally transparent to the load.  If not, something
1381   // might clobber its value.
1382   if (BBIt != LoadBB->begin())
1383     return false;
1384 
1385   // If all of the loads and stores that feed the value have the same AA tags,
1386   // then we can propagate them onto any newly inserted loads.
1387   AAMDNodes AATags = LoadI->getAAMetadata();
1388 
1389   SmallPtrSet<BasicBlock*, 8> PredsScanned;
1390 
1391   using AvailablePredsTy = SmallVector<std::pair<BasicBlock *, Value *>, 8>;
1392 
1393   AvailablePredsTy AvailablePreds;
1394   BasicBlock *OneUnavailablePred = nullptr;
1395   SmallVector<LoadInst*, 8> CSELoads;
1396 
1397   // If we got here, the loaded value is transparent through to the start of the
1398   // block.  Check to see if it is available in any of the predecessor blocks.
1399   for (BasicBlock *PredBB : predecessors(LoadBB)) {
1400     // If we already scanned this predecessor, skip it.
1401     if (!PredsScanned.insert(PredBB).second)
1402       continue;
1403 
1404     BBIt = PredBB->end();
1405     unsigned NumScanedInst = 0;
1406     Value *PredAvailable = nullptr;
1407     // NOTE: We don't CSE load that is volatile or anything stronger than
1408     // unordered, that should have been checked when we entered the function.
1409     assert(LoadI->isUnordered() &&
1410            "Attempting to CSE volatile or atomic loads");
1411     // If this is a load on a phi pointer, phi-translate it and search
1412     // for available load/store to the pointer in predecessors.
1413     Type *AccessTy = LoadI->getType();
1414     const auto &DL = LoadI->getModule()->getDataLayout();
1415     MemoryLocation Loc(LoadedPtr->DoPHITranslation(LoadBB, PredBB),
1416                        LocationSize::precise(DL.getTypeStoreSize(AccessTy)),
1417                        AATags);
1418     PredAvailable = findAvailablePtrLoadStore(Loc, AccessTy, LoadI->isAtomic(),
1419                                               PredBB, BBIt, DefMaxInstsToScan,
1420                                               AA, &IsLoadCSE, &NumScanedInst);
1421 
1422     // If PredBB has a single predecessor, continue scanning through the
1423     // single predecessor.
1424     BasicBlock *SinglePredBB = PredBB;
1425     while (!PredAvailable && SinglePredBB && BBIt == SinglePredBB->begin() &&
1426            NumScanedInst < DefMaxInstsToScan) {
1427       SinglePredBB = SinglePredBB->getSinglePredecessor();
1428       if (SinglePredBB) {
1429         BBIt = SinglePredBB->end();
1430         PredAvailable = findAvailablePtrLoadStore(
1431             Loc, AccessTy, LoadI->isAtomic(), SinglePredBB, BBIt,
1432             (DefMaxInstsToScan - NumScanedInst), AA, &IsLoadCSE,
1433             &NumScanedInst);
1434       }
1435     }
1436 
1437     if (!PredAvailable) {
1438       OneUnavailablePred = PredBB;
1439       continue;
1440     }
1441 
1442     if (IsLoadCSE)
1443       CSELoads.push_back(cast<LoadInst>(PredAvailable));
1444 
1445     // If so, this load is partially redundant.  Remember this info so that we
1446     // can create a PHI node.
1447     AvailablePreds.emplace_back(PredBB, PredAvailable);
1448   }
1449 
1450   // If the loaded value isn't available in any predecessor, it isn't partially
1451   // redundant.
1452   if (AvailablePreds.empty()) return false;
1453 
1454   // Okay, the loaded value is available in at least one (and maybe all!)
1455   // predecessors.  If the value is unavailable in more than one unique
1456   // predecessor, we want to insert a merge block for those common predecessors.
1457   // This ensures that we only have to insert one reload, thus not increasing
1458   // code size.
1459   BasicBlock *UnavailablePred = nullptr;
1460 
1461   // If the value is unavailable in one of predecessors, we will end up
1462   // inserting a new instruction into them. It is only valid if all the
1463   // instructions before LoadI are guaranteed to pass execution to its
1464   // successor, or if LoadI is safe to speculate.
1465   // TODO: If this logic becomes more complex, and we will perform PRE insertion
1466   // farther than to a predecessor, we need to reuse the code from GVN's PRE.
1467   // It requires domination tree analysis, so for this simple case it is an
1468   // overkill.
1469   if (PredsScanned.size() != AvailablePreds.size() &&
1470       !isSafeToSpeculativelyExecute(LoadI))
1471     for (auto I = LoadBB->begin(); &*I != LoadI; ++I)
1472       if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
1473         return false;
1474 
1475   // If there is exactly one predecessor where the value is unavailable, the
1476   // already computed 'OneUnavailablePred' block is it.  If it ends in an
1477   // unconditional branch, we know that it isn't a critical edge.
1478   if (PredsScanned.size() == AvailablePreds.size()+1 &&
1479       OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
1480     UnavailablePred = OneUnavailablePred;
1481   } else if (PredsScanned.size() != AvailablePreds.size()) {
1482     // Otherwise, we had multiple unavailable predecessors or we had a critical
1483     // edge from the one.
1484     SmallVector<BasicBlock*, 8> PredsToSplit;
1485     SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
1486 
1487     for (const auto &AvailablePred : AvailablePreds)
1488       AvailablePredSet.insert(AvailablePred.first);
1489 
1490     // Add all the unavailable predecessors to the PredsToSplit list.
1491     for (BasicBlock *P : predecessors(LoadBB)) {
1492       // If the predecessor is an indirect goto, we can't split the edge.
1493       if (isa<IndirectBrInst>(P->getTerminator()))
1494         return false;
1495 
1496       if (!AvailablePredSet.count(P))
1497         PredsToSplit.push_back(P);
1498     }
1499 
1500     // Split them out to their own block.
1501     UnavailablePred = splitBlockPreds(LoadBB, PredsToSplit, "thread-pre-split");
1502   }
1503 
1504   // If the value isn't available in all predecessors, then there will be
1505   // exactly one where it isn't available.  Insert a load on that edge and add
1506   // it to the AvailablePreds list.
1507   if (UnavailablePred) {
1508     assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
1509            "Can't handle critical edge here!");
1510     LoadInst *NewVal = new LoadInst(
1511         LoadI->getType(), LoadedPtr->DoPHITranslation(LoadBB, UnavailablePred),
1512         LoadI->getName() + ".pr", false, LoadI->getAlign(),
1513         LoadI->getOrdering(), LoadI->getSyncScopeID(),
1514         UnavailablePred->getTerminator());
1515     NewVal->setDebugLoc(LoadI->getDebugLoc());
1516     if (AATags)
1517       NewVal->setAAMetadata(AATags);
1518 
1519     AvailablePreds.emplace_back(UnavailablePred, NewVal);
1520   }
1521 
1522   // Now we know that each predecessor of this block has a value in
1523   // AvailablePreds, sort them for efficient access as we're walking the preds.
1524   array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
1525 
1526   // Create a PHI node at the start of the block for the PRE'd load value.
1527   pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
1528   PHINode *PN = PHINode::Create(LoadI->getType(), std::distance(PB, PE), "",
1529                                 &LoadBB->front());
1530   PN->takeName(LoadI);
1531   PN->setDebugLoc(LoadI->getDebugLoc());
1532 
1533   // Insert new entries into the PHI for each predecessor.  A single block may
1534   // have multiple entries here.
1535   for (pred_iterator PI = PB; PI != PE; ++PI) {
1536     BasicBlock *P = *PI;
1537     AvailablePredsTy::iterator I =
1538         llvm::lower_bound(AvailablePreds, std::make_pair(P, (Value *)nullptr));
1539 
1540     assert(I != AvailablePreds.end() && I->first == P &&
1541            "Didn't find entry for predecessor!");
1542 
1543     // If we have an available predecessor but it requires casting, insert the
1544     // cast in the predecessor and use the cast. Note that we have to update the
1545     // AvailablePreds vector as we go so that all of the PHI entries for this
1546     // predecessor use the same bitcast.
1547     Value *&PredV = I->second;
1548     if (PredV->getType() != LoadI->getType())
1549       PredV = CastInst::CreateBitOrPointerCast(PredV, LoadI->getType(), "",
1550                                                P->getTerminator());
1551 
1552     PN->addIncoming(PredV, I->first);
1553   }
1554 
1555   for (LoadInst *PredLoadI : CSELoads) {
1556     combineMetadataForCSE(PredLoadI, LoadI, true);
1557   }
1558 
1559   LoadI->replaceAllUsesWith(PN);
1560   LoadI->eraseFromParent();
1561 
1562   return true;
1563 }
1564 
1565 /// findMostPopularDest - The specified list contains multiple possible
1566 /// threadable destinations.  Pick the one that occurs the most frequently in
1567 /// the list.
1568 static BasicBlock *
1569 findMostPopularDest(BasicBlock *BB,
1570                     const SmallVectorImpl<std::pair<BasicBlock *,
1571                                           BasicBlock *>> &PredToDestList) {
1572   assert(!PredToDestList.empty());
1573 
1574   // Determine popularity.  If there are multiple possible destinations, we
1575   // explicitly choose to ignore 'undef' destinations.  We prefer to thread
1576   // blocks with known and real destinations to threading undef.  We'll handle
1577   // them later if interesting.
1578   MapVector<BasicBlock *, unsigned> DestPopularity;
1579 
1580   // Populate DestPopularity with the successors in the order they appear in the
1581   // successor list.  This way, we ensure determinism by iterating it in the
1582   // same order in std::max_element below.  We map nullptr to 0 so that we can
1583   // return nullptr when PredToDestList contains nullptr only.
1584   DestPopularity[nullptr] = 0;
1585   for (auto *SuccBB : successors(BB))
1586     DestPopularity[SuccBB] = 0;
1587 
1588   for (const auto &PredToDest : PredToDestList)
1589     if (PredToDest.second)
1590       DestPopularity[PredToDest.second]++;
1591 
1592   // Find the most popular dest.
1593   auto MostPopular = std::max_element(
1594       DestPopularity.begin(), DestPopularity.end(), llvm::less_second());
1595 
1596   // Okay, we have finally picked the most popular destination.
1597   return MostPopular->first;
1598 }
1599 
1600 // Try to evaluate the value of V when the control flows from PredPredBB to
1601 // BB->getSinglePredecessor() and then on to BB.
1602 Constant *JumpThreadingPass::evaluateOnPredecessorEdge(BasicBlock *BB,
1603                                                        BasicBlock *PredPredBB,
1604                                                        Value *V) {
1605   BasicBlock *PredBB = BB->getSinglePredecessor();
1606   assert(PredBB && "Expected a single predecessor");
1607 
1608   if (Constant *Cst = dyn_cast<Constant>(V)) {
1609     return Cst;
1610   }
1611 
1612   // Consult LVI if V is not an instruction in BB or PredBB.
1613   Instruction *I = dyn_cast<Instruction>(V);
1614   if (!I || (I->getParent() != BB && I->getParent() != PredBB)) {
1615     return LVI->getConstantOnEdge(V, PredPredBB, PredBB, nullptr);
1616   }
1617 
1618   // Look into a PHI argument.
1619   if (PHINode *PHI = dyn_cast<PHINode>(V)) {
1620     if (PHI->getParent() == PredBB)
1621       return dyn_cast<Constant>(PHI->getIncomingValueForBlock(PredPredBB));
1622     return nullptr;
1623   }
1624 
1625   // If we have a CmpInst, try to fold it for each incoming edge into PredBB.
1626   if (CmpInst *CondCmp = dyn_cast<CmpInst>(V)) {
1627     if (CondCmp->getParent() == BB) {
1628       Constant *Op0 =
1629           evaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(0));
1630       Constant *Op1 =
1631           evaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(1));
1632       if (Op0 && Op1) {
1633         return ConstantExpr::getCompare(CondCmp->getPredicate(), Op0, Op1);
1634       }
1635     }
1636     return nullptr;
1637   }
1638 
1639   return nullptr;
1640 }
1641 
1642 bool JumpThreadingPass::processThreadableEdges(Value *Cond, BasicBlock *BB,
1643                                                ConstantPreference Preference,
1644                                                Instruction *CxtI) {
1645   // If threading this would thread across a loop header, don't even try to
1646   // thread the edge.
1647   if (LoopHeaders.count(BB))
1648     return false;
1649 
1650   PredValueInfoTy PredValues;
1651   if (!computeValueKnownInPredecessors(Cond, BB, PredValues, Preference,
1652                                        CxtI)) {
1653     // We don't have known values in predecessors.  See if we can thread through
1654     // BB and its sole predecessor.
1655     return maybethreadThroughTwoBasicBlocks(BB, Cond);
1656   }
1657 
1658   assert(!PredValues.empty() &&
1659          "computeValueKnownInPredecessors returned true with no values");
1660 
1661   LLVM_DEBUG(dbgs() << "IN BB: " << *BB;
1662              for (const auto &PredValue : PredValues) {
1663                dbgs() << "  BB '" << BB->getName()
1664                       << "': FOUND condition = " << *PredValue.first
1665                       << " for pred '" << PredValue.second->getName() << "'.\n";
1666   });
1667 
1668   // Decide what we want to thread through.  Convert our list of known values to
1669   // a list of known destinations for each pred.  This also discards duplicate
1670   // predecessors and keeps track of the undefined inputs (which are represented
1671   // as a null dest in the PredToDestList).
1672   SmallPtrSet<BasicBlock*, 16> SeenPreds;
1673   SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
1674 
1675   BasicBlock *OnlyDest = nullptr;
1676   BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
1677   Constant *OnlyVal = nullptr;
1678   Constant *MultipleVal = (Constant *)(intptr_t)~0ULL;
1679 
1680   for (const auto &PredValue : PredValues) {
1681     BasicBlock *Pred = PredValue.second;
1682     if (!SeenPreds.insert(Pred).second)
1683       continue;  // Duplicate predecessor entry.
1684 
1685     Constant *Val = PredValue.first;
1686 
1687     BasicBlock *DestBB;
1688     if (isa<UndefValue>(Val))
1689       DestBB = nullptr;
1690     else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
1691       assert(isa<ConstantInt>(Val) && "Expecting a constant integer");
1692       DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
1693     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1694       assert(isa<ConstantInt>(Val) && "Expecting a constant integer");
1695       DestBB = SI->findCaseValue(cast<ConstantInt>(Val))->getCaseSuccessor();
1696     } else {
1697       assert(isa<IndirectBrInst>(BB->getTerminator())
1698               && "Unexpected terminator");
1699       assert(isa<BlockAddress>(Val) && "Expecting a constant blockaddress");
1700       DestBB = cast<BlockAddress>(Val)->getBasicBlock();
1701     }
1702 
1703     // If we have exactly one destination, remember it for efficiency below.
1704     if (PredToDestList.empty()) {
1705       OnlyDest = DestBB;
1706       OnlyVal = Val;
1707     } else {
1708       if (OnlyDest != DestBB)
1709         OnlyDest = MultipleDestSentinel;
1710       // It possible we have same destination, but different value, e.g. default
1711       // case in switchinst.
1712       if (Val != OnlyVal)
1713         OnlyVal = MultipleVal;
1714     }
1715 
1716     // If the predecessor ends with an indirect goto, we can't change its
1717     // destination.
1718     if (isa<IndirectBrInst>(Pred->getTerminator()))
1719       continue;
1720 
1721     PredToDestList.emplace_back(Pred, DestBB);
1722   }
1723 
1724   // If all edges were unthreadable, we fail.
1725   if (PredToDestList.empty())
1726     return false;
1727 
1728   // If all the predecessors go to a single known successor, we want to fold,
1729   // not thread. By doing so, we do not need to duplicate the current block and
1730   // also miss potential opportunities in case we dont/cant duplicate.
1731   if (OnlyDest && OnlyDest != MultipleDestSentinel) {
1732     if (BB->hasNPredecessors(PredToDestList.size())) {
1733       bool SeenFirstBranchToOnlyDest = false;
1734       std::vector <DominatorTree::UpdateType> Updates;
1735       Updates.reserve(BB->getTerminator()->getNumSuccessors() - 1);
1736       for (BasicBlock *SuccBB : successors(BB)) {
1737         if (SuccBB == OnlyDest && !SeenFirstBranchToOnlyDest) {
1738           SeenFirstBranchToOnlyDest = true; // Don't modify the first branch.
1739         } else {
1740           SuccBB->removePredecessor(BB, true); // This is unreachable successor.
1741           Updates.push_back({DominatorTree::Delete, BB, SuccBB});
1742         }
1743       }
1744 
1745       // Finally update the terminator.
1746       Instruction *Term = BB->getTerminator();
1747       BranchInst::Create(OnlyDest, Term);
1748       ++NumFolds;
1749       Term->eraseFromParent();
1750       DTU->applyUpdatesPermissive(Updates);
1751       if (auto *BPI = getBPI())
1752         BPI->eraseBlock(BB);
1753 
1754       // If the condition is now dead due to the removal of the old terminator,
1755       // erase it.
1756       if (auto *CondInst = dyn_cast<Instruction>(Cond)) {
1757         if (CondInst->use_empty() && !CondInst->mayHaveSideEffects())
1758           CondInst->eraseFromParent();
1759         // We can safely replace *some* uses of the CondInst if it has
1760         // exactly one value as returned by LVI. RAUW is incorrect in the
1761         // presence of guards and assumes, that have the `Cond` as the use. This
1762         // is because we use the guards/assume to reason about the `Cond` value
1763         // at the end of block, but RAUW unconditionally replaces all uses
1764         // including the guards/assumes themselves and the uses before the
1765         // guard/assume.
1766         else if (OnlyVal && OnlyVal != MultipleVal)
1767           replaceFoldableUses(CondInst, OnlyVal, BB);
1768       }
1769       return true;
1770     }
1771   }
1772 
1773   // Determine which is the most common successor.  If we have many inputs and
1774   // this block is a switch, we want to start by threading the batch that goes
1775   // to the most popular destination first.  If we only know about one
1776   // threadable destination (the common case) we can avoid this.
1777   BasicBlock *MostPopularDest = OnlyDest;
1778 
1779   if (MostPopularDest == MultipleDestSentinel) {
1780     // Remove any loop headers from the Dest list, threadEdge conservatively
1781     // won't process them, but we might have other destination that are eligible
1782     // and we still want to process.
1783     erase_if(PredToDestList,
1784              [&](const std::pair<BasicBlock *, BasicBlock *> &PredToDest) {
1785                return LoopHeaders.contains(PredToDest.second);
1786              });
1787 
1788     if (PredToDestList.empty())
1789       return false;
1790 
1791     MostPopularDest = findMostPopularDest(BB, PredToDestList);
1792   }
1793 
1794   // Now that we know what the most popular destination is, factor all
1795   // predecessors that will jump to it into a single predecessor.
1796   SmallVector<BasicBlock*, 16> PredsToFactor;
1797   for (const auto &PredToDest : PredToDestList)
1798     if (PredToDest.second == MostPopularDest) {
1799       BasicBlock *Pred = PredToDest.first;
1800 
1801       // This predecessor may be a switch or something else that has multiple
1802       // edges to the block.  Factor each of these edges by listing them
1803       // according to # occurrences in PredsToFactor.
1804       for (BasicBlock *Succ : successors(Pred))
1805         if (Succ == BB)
1806           PredsToFactor.push_back(Pred);
1807     }
1808 
1809   // If the threadable edges are branching on an undefined value, we get to pick
1810   // the destination that these predecessors should get to.
1811   if (!MostPopularDest)
1812     MostPopularDest = BB->getTerminator()->
1813                             getSuccessor(getBestDestForJumpOnUndef(BB));
1814 
1815   // Ok, try to thread it!
1816   return tryThreadEdge(BB, PredsToFactor, MostPopularDest);
1817 }
1818 
1819 /// processBranchOnPHI - We have an otherwise unthreadable conditional branch on
1820 /// a PHI node (or freeze PHI) in the current block.  See if there are any
1821 /// simplifications we can do based on inputs to the phi node.
1822 bool JumpThreadingPass::processBranchOnPHI(PHINode *PN) {
1823   BasicBlock *BB = PN->getParent();
1824 
1825   // TODO: We could make use of this to do it once for blocks with common PHI
1826   // values.
1827   SmallVector<BasicBlock*, 1> PredBBs;
1828   PredBBs.resize(1);
1829 
1830   // If any of the predecessor blocks end in an unconditional branch, we can
1831   // *duplicate* the conditional branch into that block in order to further
1832   // encourage jump threading and to eliminate cases where we have branch on a
1833   // phi of an icmp (branch on icmp is much better).
1834   // This is still beneficial when a frozen phi is used as the branch condition
1835   // because it allows CodeGenPrepare to further canonicalize br(freeze(icmp))
1836   // to br(icmp(freeze ...)).
1837   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1838     BasicBlock *PredBB = PN->getIncomingBlock(i);
1839     if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
1840       if (PredBr->isUnconditional()) {
1841         PredBBs[0] = PredBB;
1842         // Try to duplicate BB into PredBB.
1843         if (duplicateCondBranchOnPHIIntoPred(BB, PredBBs))
1844           return true;
1845       }
1846   }
1847 
1848   return false;
1849 }
1850 
1851 /// processBranchOnXOR - We have an otherwise unthreadable conditional branch on
1852 /// a xor instruction in the current block.  See if there are any
1853 /// simplifications we can do based on inputs to the xor.
1854 bool JumpThreadingPass::processBranchOnXOR(BinaryOperator *BO) {
1855   BasicBlock *BB = BO->getParent();
1856 
1857   // If either the LHS or RHS of the xor is a constant, don't do this
1858   // optimization.
1859   if (isa<ConstantInt>(BO->getOperand(0)) ||
1860       isa<ConstantInt>(BO->getOperand(1)))
1861     return false;
1862 
1863   // If the first instruction in BB isn't a phi, we won't be able to infer
1864   // anything special about any particular predecessor.
1865   if (!isa<PHINode>(BB->front()))
1866     return false;
1867 
1868   // If this BB is a landing pad, we won't be able to split the edge into it.
1869   if (BB->isEHPad())
1870     return false;
1871 
1872   // If we have a xor as the branch input to this block, and we know that the
1873   // LHS or RHS of the xor in any predecessor is true/false, then we can clone
1874   // the condition into the predecessor and fix that value to true, saving some
1875   // logical ops on that path and encouraging other paths to simplify.
1876   //
1877   // This copies something like this:
1878   //
1879   //  BB:
1880   //    %X = phi i1 [1],  [%X']
1881   //    %Y = icmp eq i32 %A, %B
1882   //    %Z = xor i1 %X, %Y
1883   //    br i1 %Z, ...
1884   //
1885   // Into:
1886   //  BB':
1887   //    %Y = icmp ne i32 %A, %B
1888   //    br i1 %Y, ...
1889 
1890   PredValueInfoTy XorOpValues;
1891   bool isLHS = true;
1892   if (!computeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues,
1893                                        WantInteger, BO)) {
1894     assert(XorOpValues.empty());
1895     if (!computeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues,
1896                                          WantInteger, BO))
1897       return false;
1898     isLHS = false;
1899   }
1900 
1901   assert(!XorOpValues.empty() &&
1902          "computeValueKnownInPredecessors returned true with no values");
1903 
1904   // Scan the information to see which is most popular: true or false.  The
1905   // predecessors can be of the set true, false, or undef.
1906   unsigned NumTrue = 0, NumFalse = 0;
1907   for (const auto &XorOpValue : XorOpValues) {
1908     if (isa<UndefValue>(XorOpValue.first))
1909       // Ignore undefs for the count.
1910       continue;
1911     if (cast<ConstantInt>(XorOpValue.first)->isZero())
1912       ++NumFalse;
1913     else
1914       ++NumTrue;
1915   }
1916 
1917   // Determine which value to split on, true, false, or undef if neither.
1918   ConstantInt *SplitVal = nullptr;
1919   if (NumTrue > NumFalse)
1920     SplitVal = ConstantInt::getTrue(BB->getContext());
1921   else if (NumTrue != 0 || NumFalse != 0)
1922     SplitVal = ConstantInt::getFalse(BB->getContext());
1923 
1924   // Collect all of the blocks that this can be folded into so that we can
1925   // factor this once and clone it once.
1926   SmallVector<BasicBlock*, 8> BlocksToFoldInto;
1927   for (const auto &XorOpValue : XorOpValues) {
1928     if (XorOpValue.first != SplitVal && !isa<UndefValue>(XorOpValue.first))
1929       continue;
1930 
1931     BlocksToFoldInto.push_back(XorOpValue.second);
1932   }
1933 
1934   // If we inferred a value for all of the predecessors, then duplication won't
1935   // help us.  However, we can just replace the LHS or RHS with the constant.
1936   if (BlocksToFoldInto.size() ==
1937       cast<PHINode>(BB->front()).getNumIncomingValues()) {
1938     if (!SplitVal) {
1939       // If all preds provide undef, just nuke the xor, because it is undef too.
1940       BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
1941       BO->eraseFromParent();
1942     } else if (SplitVal->isZero() && BO != BO->getOperand(isLHS)) {
1943       // If all preds provide 0, replace the xor with the other input.
1944       BO->replaceAllUsesWith(BO->getOperand(isLHS));
1945       BO->eraseFromParent();
1946     } else {
1947       // If all preds provide 1, set the computed value to 1.
1948       BO->setOperand(!isLHS, SplitVal);
1949     }
1950 
1951     return true;
1952   }
1953 
1954   // If any of predecessors end with an indirect goto, we can't change its
1955   // destination.
1956   if (any_of(BlocksToFoldInto, [](BasicBlock *Pred) {
1957         return isa<IndirectBrInst>(Pred->getTerminator());
1958       }))
1959     return false;
1960 
1961   // Try to duplicate BB into PredBB.
1962   return duplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
1963 }
1964 
1965 /// addPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
1966 /// predecessor to the PHIBB block.  If it has PHI nodes, add entries for
1967 /// NewPred using the entries from OldPred (suitably mapped).
1968 static void addPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
1969                                             BasicBlock *OldPred,
1970                                             BasicBlock *NewPred,
1971                                      DenseMap<Instruction*, Value*> &ValueMap) {
1972   for (PHINode &PN : PHIBB->phis()) {
1973     // Ok, we have a PHI node.  Figure out what the incoming value was for the
1974     // DestBlock.
1975     Value *IV = PN.getIncomingValueForBlock(OldPred);
1976 
1977     // Remap the value if necessary.
1978     if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
1979       DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
1980       if (I != ValueMap.end())
1981         IV = I->second;
1982     }
1983 
1984     PN.addIncoming(IV, NewPred);
1985   }
1986 }
1987 
1988 /// Merge basic block BB into its sole predecessor if possible.
1989 bool JumpThreadingPass::maybeMergeBasicBlockIntoOnlyPred(BasicBlock *BB) {
1990   BasicBlock *SinglePred = BB->getSinglePredecessor();
1991   if (!SinglePred)
1992     return false;
1993 
1994   const Instruction *TI = SinglePred->getTerminator();
1995   if (TI->isExceptionalTerminator() || TI->getNumSuccessors() != 1 ||
1996       SinglePred == BB || hasAddressTakenAndUsed(BB))
1997     return false;
1998 
1999   // If SinglePred was a loop header, BB becomes one.
2000   if (LoopHeaders.erase(SinglePred))
2001     LoopHeaders.insert(BB);
2002 
2003   LVI->eraseBlock(SinglePred);
2004   MergeBasicBlockIntoOnlyPred(BB, DTU.get());
2005 
2006   // Now that BB is merged into SinglePred (i.e. SinglePred code followed by
2007   // BB code within one basic block `BB`), we need to invalidate the LVI
2008   // information associated with BB, because the LVI information need not be
2009   // true for all of BB after the merge. For example,
2010   // Before the merge, LVI info and code is as follows:
2011   // SinglePred: <LVI info1 for %p val>
2012   // %y = use of %p
2013   // call @exit() // need not transfer execution to successor.
2014   // assume(%p) // from this point on %p is true
2015   // br label %BB
2016   // BB: <LVI info2 for %p val, i.e. %p is true>
2017   // %x = use of %p
2018   // br label exit
2019   //
2020   // Note that this LVI info for blocks BB and SinglPred is correct for %p
2021   // (info2 and info1 respectively). After the merge and the deletion of the
2022   // LVI info1 for SinglePred. We have the following code:
2023   // BB: <LVI info2 for %p val>
2024   // %y = use of %p
2025   // call @exit()
2026   // assume(%p)
2027   // %x = use of %p <-- LVI info2 is correct from here onwards.
2028   // br label exit
2029   // LVI info2 for BB is incorrect at the beginning of BB.
2030 
2031   // Invalidate LVI information for BB if the LVI is not provably true for
2032   // all of BB.
2033   if (!isGuaranteedToTransferExecutionToSuccessor(BB))
2034     LVI->eraseBlock(BB);
2035   return true;
2036 }
2037 
2038 /// Update the SSA form.  NewBB contains instructions that are copied from BB.
2039 /// ValueMapping maps old values in BB to new ones in NewBB.
2040 void JumpThreadingPass::updateSSA(
2041     BasicBlock *BB, BasicBlock *NewBB,
2042     DenseMap<Instruction *, Value *> &ValueMapping) {
2043   // If there were values defined in BB that are used outside the block, then we
2044   // now have to update all uses of the value to use either the original value,
2045   // the cloned value, or some PHI derived value.  This can require arbitrary
2046   // PHI insertion, of which we are prepared to do, clean these up now.
2047   SSAUpdater SSAUpdate;
2048   SmallVector<Use *, 16> UsesToRename;
2049   SmallVector<DbgValueInst *, 4> DbgValues;
2050 
2051   for (Instruction &I : *BB) {
2052     // Scan all uses of this instruction to see if it is used outside of its
2053     // block, and if so, record them in UsesToRename.
2054     for (Use &U : I.uses()) {
2055       Instruction *User = cast<Instruction>(U.getUser());
2056       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
2057         if (UserPN->getIncomingBlock(U) == BB)
2058           continue;
2059       } else if (User->getParent() == BB)
2060         continue;
2061 
2062       UsesToRename.push_back(&U);
2063     }
2064 
2065     // Find debug values outside of the block
2066     findDbgValues(DbgValues, &I);
2067     DbgValues.erase(remove_if(DbgValues,
2068                               [&](const DbgValueInst *DbgVal) {
2069                                 return DbgVal->getParent() == BB;
2070                               }),
2071                     DbgValues.end());
2072 
2073     // If there are no uses outside the block, we're done with this instruction.
2074     if (UsesToRename.empty() && DbgValues.empty())
2075       continue;
2076     LLVM_DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n");
2077 
2078     // We found a use of I outside of BB.  Rename all uses of I that are outside
2079     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
2080     // with the two values we know.
2081     SSAUpdate.Initialize(I.getType(), I.getName());
2082     SSAUpdate.AddAvailableValue(BB, &I);
2083     SSAUpdate.AddAvailableValue(NewBB, ValueMapping[&I]);
2084 
2085     while (!UsesToRename.empty())
2086       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
2087     if (!DbgValues.empty()) {
2088       SSAUpdate.UpdateDebugValues(&I, DbgValues);
2089       DbgValues.clear();
2090     }
2091 
2092     LLVM_DEBUG(dbgs() << "\n");
2093   }
2094 }
2095 
2096 /// Clone instructions in range [BI, BE) to NewBB.  For PHI nodes, we only clone
2097 /// arguments that come from PredBB.  Return the map from the variables in the
2098 /// source basic block to the variables in the newly created basic block.
2099 DenseMap<Instruction *, Value *>
2100 JumpThreadingPass::cloneInstructions(BasicBlock::iterator BI,
2101                                      BasicBlock::iterator BE, BasicBlock *NewBB,
2102                                      BasicBlock *PredBB) {
2103   // We are going to have to map operands from the source basic block to the new
2104   // copy of the block 'NewBB'.  If there are PHI nodes in the source basic
2105   // block, evaluate them to account for entry from PredBB.
2106   DenseMap<Instruction *, Value *> ValueMapping;
2107 
2108   // Retargets llvm.dbg.value to any renamed variables.
2109   auto RetargetDbgValueIfPossible = [&](Instruction *NewInst) -> bool {
2110     auto DbgInstruction = dyn_cast<DbgValueInst>(NewInst);
2111     if (!DbgInstruction)
2112       return false;
2113 
2114     SmallSet<std::pair<Value *, Value *>, 16> OperandsToRemap;
2115     for (auto DbgOperand : DbgInstruction->location_ops()) {
2116       auto DbgOperandInstruction = dyn_cast<Instruction>(DbgOperand);
2117       if (!DbgOperandInstruction)
2118         continue;
2119 
2120       auto I = ValueMapping.find(DbgOperandInstruction);
2121       if (I != ValueMapping.end()) {
2122         OperandsToRemap.insert(
2123             std::pair<Value *, Value *>(DbgOperand, I->second));
2124       }
2125     }
2126 
2127     for (auto &[OldOp, MappedOp] : OperandsToRemap)
2128       DbgInstruction->replaceVariableLocationOp(OldOp, MappedOp);
2129     return true;
2130   };
2131 
2132   // Clone the phi nodes of the source basic block into NewBB.  The resulting
2133   // phi nodes are trivial since NewBB only has one predecessor, but SSAUpdater
2134   // might need to rewrite the operand of the cloned phi.
2135   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
2136     PHINode *NewPN = PHINode::Create(PN->getType(), 1, PN->getName(), NewBB);
2137     NewPN->addIncoming(PN->getIncomingValueForBlock(PredBB), PredBB);
2138     ValueMapping[PN] = NewPN;
2139   }
2140 
2141   // Clone noalias scope declarations in the threaded block. When threading a
2142   // loop exit, we would otherwise end up with two idential scope declarations
2143   // visible at the same time.
2144   SmallVector<MDNode *> NoAliasScopes;
2145   DenseMap<MDNode *, MDNode *> ClonedScopes;
2146   LLVMContext &Context = PredBB->getContext();
2147   identifyNoAliasScopesToClone(BI, BE, NoAliasScopes);
2148   cloneNoAliasScopes(NoAliasScopes, ClonedScopes, "thread", Context);
2149 
2150   // Clone the non-phi instructions of the source basic block into NewBB,
2151   // keeping track of the mapping and using it to remap operands in the cloned
2152   // instructions.
2153   for (; BI != BE; ++BI) {
2154     Instruction *New = BI->clone();
2155     New->setName(BI->getName());
2156     New->insertInto(NewBB, NewBB->end());
2157     ValueMapping[&*BI] = New;
2158     adaptNoAliasScopes(New, ClonedScopes, Context);
2159 
2160     if (RetargetDbgValueIfPossible(New))
2161       continue;
2162 
2163     // Remap operands to patch up intra-block references.
2164     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2165       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
2166         DenseMap<Instruction *, Value *>::iterator I = ValueMapping.find(Inst);
2167         if (I != ValueMapping.end())
2168           New->setOperand(i, I->second);
2169       }
2170   }
2171 
2172   return ValueMapping;
2173 }
2174 
2175 /// Attempt to thread through two successive basic blocks.
2176 bool JumpThreadingPass::maybethreadThroughTwoBasicBlocks(BasicBlock *BB,
2177                                                          Value *Cond) {
2178   // Consider:
2179   //
2180   // PredBB:
2181   //   %var = phi i32* [ null, %bb1 ], [ @a, %bb2 ]
2182   //   %tobool = icmp eq i32 %cond, 0
2183   //   br i1 %tobool, label %BB, label ...
2184   //
2185   // BB:
2186   //   %cmp = icmp eq i32* %var, null
2187   //   br i1 %cmp, label ..., label ...
2188   //
2189   // We don't know the value of %var at BB even if we know which incoming edge
2190   // we take to BB.  However, once we duplicate PredBB for each of its incoming
2191   // edges (say, PredBB1 and PredBB2), we know the value of %var in each copy of
2192   // PredBB.  Then we can thread edges PredBB1->BB and PredBB2->BB through BB.
2193 
2194   // Require that BB end with a Branch for simplicity.
2195   BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
2196   if (!CondBr)
2197     return false;
2198 
2199   // BB must have exactly one predecessor.
2200   BasicBlock *PredBB = BB->getSinglePredecessor();
2201   if (!PredBB)
2202     return false;
2203 
2204   // Require that PredBB end with a conditional Branch. If PredBB ends with an
2205   // unconditional branch, we should be merging PredBB and BB instead. For
2206   // simplicity, we don't deal with a switch.
2207   BranchInst *PredBBBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
2208   if (!PredBBBranch || PredBBBranch->isUnconditional())
2209     return false;
2210 
2211   // If PredBB has exactly one incoming edge, we don't gain anything by copying
2212   // PredBB.
2213   if (PredBB->getSinglePredecessor())
2214     return false;
2215 
2216   // Don't thread through PredBB if it contains a successor edge to itself, in
2217   // which case we would infinite loop.  Suppose we are threading an edge from
2218   // PredPredBB through PredBB and BB to SuccBB with PredBB containing a
2219   // successor edge to itself.  If we allowed jump threading in this case, we
2220   // could duplicate PredBB and BB as, say, PredBB.thread and BB.thread.  Since
2221   // PredBB.thread has a successor edge to PredBB, we would immediately come up
2222   // with another jump threading opportunity from PredBB.thread through PredBB
2223   // and BB to SuccBB.  This jump threading would repeatedly occur.  That is, we
2224   // would keep peeling one iteration from PredBB.
2225   if (llvm::is_contained(successors(PredBB), PredBB))
2226     return false;
2227 
2228   // Don't thread across a loop header.
2229   if (LoopHeaders.count(PredBB))
2230     return false;
2231 
2232   // Avoid complication with duplicating EH pads.
2233   if (PredBB->isEHPad())
2234     return false;
2235 
2236   // Find a predecessor that we can thread.  For simplicity, we only consider a
2237   // successor edge out of BB to which we thread exactly one incoming edge into
2238   // PredBB.
2239   unsigned ZeroCount = 0;
2240   unsigned OneCount = 0;
2241   BasicBlock *ZeroPred = nullptr;
2242   BasicBlock *OnePred = nullptr;
2243   for (BasicBlock *P : predecessors(PredBB)) {
2244     // If PredPred ends with IndirectBrInst, we can't handle it.
2245     if (isa<IndirectBrInst>(P->getTerminator()))
2246       continue;
2247     if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>(
2248             evaluateOnPredecessorEdge(BB, P, Cond))) {
2249       if (CI->isZero()) {
2250         ZeroCount++;
2251         ZeroPred = P;
2252       } else if (CI->isOne()) {
2253         OneCount++;
2254         OnePred = P;
2255       }
2256     }
2257   }
2258 
2259   // Disregard complicated cases where we have to thread multiple edges.
2260   BasicBlock *PredPredBB;
2261   if (ZeroCount == 1) {
2262     PredPredBB = ZeroPred;
2263   } else if (OneCount == 1) {
2264     PredPredBB = OnePred;
2265   } else {
2266     return false;
2267   }
2268 
2269   BasicBlock *SuccBB = CondBr->getSuccessor(PredPredBB == ZeroPred);
2270 
2271   // If threading to the same block as we come from, we would infinite loop.
2272   if (SuccBB == BB) {
2273     LLVM_DEBUG(dbgs() << "  Not threading across BB '" << BB->getName()
2274                       << "' - would thread to self!\n");
2275     return false;
2276   }
2277 
2278   // If threading this would thread across a loop header, don't thread the edge.
2279   // See the comments above findLoopHeaders for justifications and caveats.
2280   if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) {
2281     LLVM_DEBUG({
2282       bool BBIsHeader = LoopHeaders.count(BB);
2283       bool SuccIsHeader = LoopHeaders.count(SuccBB);
2284       dbgs() << "  Not threading across "
2285              << (BBIsHeader ? "loop header BB '" : "block BB '")
2286              << BB->getName() << "' to dest "
2287              << (SuccIsHeader ? "loop header BB '" : "block BB '")
2288              << SuccBB->getName()
2289              << "' - it might create an irreducible loop!\n";
2290     });
2291     return false;
2292   }
2293 
2294   // Compute the cost of duplicating BB and PredBB.
2295   unsigned BBCost = getJumpThreadDuplicationCost(
2296       TTI, BB, BB->getTerminator(), BBDupThreshold);
2297   unsigned PredBBCost = getJumpThreadDuplicationCost(
2298       TTI, PredBB, PredBB->getTerminator(), BBDupThreshold);
2299 
2300   // Give up if costs are too high.  We need to check BBCost and PredBBCost
2301   // individually before checking their sum because getJumpThreadDuplicationCost
2302   // return (unsigned)~0 for those basic blocks that cannot be duplicated.
2303   if (BBCost > BBDupThreshold || PredBBCost > BBDupThreshold ||
2304       BBCost + PredBBCost > BBDupThreshold) {
2305     LLVM_DEBUG(dbgs() << "  Not threading BB '" << BB->getName()
2306                       << "' - Cost is too high: " << PredBBCost
2307                       << " for PredBB, " << BBCost << "for BB\n");
2308     return false;
2309   }
2310 
2311   // Now we are ready to duplicate PredBB.
2312   threadThroughTwoBasicBlocks(PredPredBB, PredBB, BB, SuccBB);
2313   return true;
2314 }
2315 
2316 void JumpThreadingPass::threadThroughTwoBasicBlocks(BasicBlock *PredPredBB,
2317                                                     BasicBlock *PredBB,
2318                                                     BasicBlock *BB,
2319                                                     BasicBlock *SuccBB) {
2320   LLVM_DEBUG(dbgs() << "  Threading through '" << PredBB->getName() << "' and '"
2321                     << BB->getName() << "'\n");
2322 
2323   // Build BPI/BFI before any changes are made to IR.
2324   bool HasProfile = doesBlockHaveProfileData(BB);
2325   auto *BFI = getOrCreateBFI(HasProfile);
2326   auto *BPI = getOrCreateBPI(BFI != nullptr);
2327 
2328   BranchInst *CondBr = cast<BranchInst>(BB->getTerminator());
2329   BranchInst *PredBBBranch = cast<BranchInst>(PredBB->getTerminator());
2330 
2331   BasicBlock *NewBB =
2332       BasicBlock::Create(PredBB->getContext(), PredBB->getName() + ".thread",
2333                          PredBB->getParent(), PredBB);
2334   NewBB->moveAfter(PredBB);
2335 
2336   // Set the block frequency of NewBB.
2337   if (BFI) {
2338     assert(BPI && "It's expected BPI to exist along with BFI");
2339     auto NewBBFreq = BFI->getBlockFreq(PredPredBB) *
2340                      BPI->getEdgeProbability(PredPredBB, PredBB);
2341     BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
2342   }
2343 
2344   // We are going to have to map operands from the original BB block to the new
2345   // copy of the block 'NewBB'.  If there are PHI nodes in PredBB, evaluate them
2346   // to account for entry from PredPredBB.
2347   DenseMap<Instruction *, Value *> ValueMapping =
2348       cloneInstructions(PredBB->begin(), PredBB->end(), NewBB, PredPredBB);
2349 
2350   // Copy the edge probabilities from PredBB to NewBB.
2351   if (BPI)
2352     BPI->copyEdgeProbabilities(PredBB, NewBB);
2353 
2354   // Update the terminator of PredPredBB to jump to NewBB instead of PredBB.
2355   // This eliminates predecessors from PredPredBB, which requires us to simplify
2356   // any PHI nodes in PredBB.
2357   Instruction *PredPredTerm = PredPredBB->getTerminator();
2358   for (unsigned i = 0, e = PredPredTerm->getNumSuccessors(); i != e; ++i)
2359     if (PredPredTerm->getSuccessor(i) == PredBB) {
2360       PredBB->removePredecessor(PredPredBB, true);
2361       PredPredTerm->setSuccessor(i, NewBB);
2362     }
2363 
2364   addPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(0), PredBB, NewBB,
2365                                   ValueMapping);
2366   addPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(1), PredBB, NewBB,
2367                                   ValueMapping);
2368 
2369   DTU->applyUpdatesPermissive(
2370       {{DominatorTree::Insert, NewBB, CondBr->getSuccessor(0)},
2371        {DominatorTree::Insert, NewBB, CondBr->getSuccessor(1)},
2372        {DominatorTree::Insert, PredPredBB, NewBB},
2373        {DominatorTree::Delete, PredPredBB, PredBB}});
2374 
2375   updateSSA(PredBB, NewBB, ValueMapping);
2376 
2377   // Clean up things like PHI nodes with single operands, dead instructions,
2378   // etc.
2379   SimplifyInstructionsInBlock(NewBB, TLI);
2380   SimplifyInstructionsInBlock(PredBB, TLI);
2381 
2382   SmallVector<BasicBlock *, 1> PredsToFactor;
2383   PredsToFactor.push_back(NewBB);
2384   threadEdge(BB, PredsToFactor, SuccBB);
2385 }
2386 
2387 /// tryThreadEdge - Thread an edge if it's safe and profitable to do so.
2388 bool JumpThreadingPass::tryThreadEdge(
2389     BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs,
2390     BasicBlock *SuccBB) {
2391   // If threading to the same block as we come from, we would infinite loop.
2392   if (SuccBB == BB) {
2393     LLVM_DEBUG(dbgs() << "  Not threading across BB '" << BB->getName()
2394                       << "' - would thread to self!\n");
2395     return false;
2396   }
2397 
2398   // If threading this would thread across a loop header, don't thread the edge.
2399   // See the comments above findLoopHeaders for justifications and caveats.
2400   if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) {
2401     LLVM_DEBUG({
2402       bool BBIsHeader = LoopHeaders.count(BB);
2403       bool SuccIsHeader = LoopHeaders.count(SuccBB);
2404       dbgs() << "  Not threading across "
2405           << (BBIsHeader ? "loop header BB '" : "block BB '") << BB->getName()
2406           << "' to dest " << (SuccIsHeader ? "loop header BB '" : "block BB '")
2407           << SuccBB->getName() << "' - it might create an irreducible loop!\n";
2408     });
2409     return false;
2410   }
2411 
2412   unsigned JumpThreadCost = getJumpThreadDuplicationCost(
2413       TTI, BB, BB->getTerminator(), BBDupThreshold);
2414   if (JumpThreadCost > BBDupThreshold) {
2415     LLVM_DEBUG(dbgs() << "  Not threading BB '" << BB->getName()
2416                       << "' - Cost is too high: " << JumpThreadCost << "\n");
2417     return false;
2418   }
2419 
2420   threadEdge(BB, PredBBs, SuccBB);
2421   return true;
2422 }
2423 
2424 /// threadEdge - We have decided that it is safe and profitable to factor the
2425 /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
2426 /// across BB.  Transform the IR to reflect this change.
2427 void JumpThreadingPass::threadEdge(BasicBlock *BB,
2428                                    const SmallVectorImpl<BasicBlock *> &PredBBs,
2429                                    BasicBlock *SuccBB) {
2430   assert(SuccBB != BB && "Don't create an infinite loop");
2431 
2432   assert(!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB) &&
2433          "Don't thread across loop headers");
2434 
2435   // Build BPI/BFI before any changes are made to IR.
2436   bool HasProfile = doesBlockHaveProfileData(BB);
2437   auto *BFI = getOrCreateBFI(HasProfile);
2438   auto *BPI = getOrCreateBPI(BFI != nullptr);
2439 
2440   // And finally, do it!  Start by factoring the predecessors if needed.
2441   BasicBlock *PredBB;
2442   if (PredBBs.size() == 1)
2443     PredBB = PredBBs[0];
2444   else {
2445     LLVM_DEBUG(dbgs() << "  Factoring out " << PredBBs.size()
2446                       << " common predecessors.\n");
2447     PredBB = splitBlockPreds(BB, PredBBs, ".thr_comm");
2448   }
2449 
2450   // And finally, do it!
2451   LLVM_DEBUG(dbgs() << "  Threading edge from '" << PredBB->getName()
2452                     << "' to '" << SuccBB->getName()
2453                     << ", across block:\n    " << *BB << "\n");
2454 
2455   LVI->threadEdge(PredBB, BB, SuccBB);
2456 
2457   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
2458                                          BB->getName()+".thread",
2459                                          BB->getParent(), BB);
2460   NewBB->moveAfter(PredBB);
2461 
2462   // Set the block frequency of NewBB.
2463   if (BFI) {
2464     assert(BPI && "It's expected BPI to exist along with BFI");
2465     auto NewBBFreq =
2466         BFI->getBlockFreq(PredBB) * BPI->getEdgeProbability(PredBB, BB);
2467     BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
2468   }
2469 
2470   // Copy all the instructions from BB to NewBB except the terminator.
2471   DenseMap<Instruction *, Value *> ValueMapping =
2472       cloneInstructions(BB->begin(), std::prev(BB->end()), NewBB, PredBB);
2473 
2474   // We didn't copy the terminator from BB over to NewBB, because there is now
2475   // an unconditional jump to SuccBB.  Insert the unconditional jump.
2476   BranchInst *NewBI = BranchInst::Create(SuccBB, NewBB);
2477   NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc());
2478 
2479   // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
2480   // PHI nodes for NewBB now.
2481   addPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
2482 
2483   // Update the terminator of PredBB to jump to NewBB instead of BB.  This
2484   // eliminates predecessors from BB, which requires us to simplify any PHI
2485   // nodes in BB.
2486   Instruction *PredTerm = PredBB->getTerminator();
2487   for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
2488     if (PredTerm->getSuccessor(i) == BB) {
2489       BB->removePredecessor(PredBB, true);
2490       PredTerm->setSuccessor(i, NewBB);
2491     }
2492 
2493   // Enqueue required DT updates.
2494   DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, SuccBB},
2495                                {DominatorTree::Insert, PredBB, NewBB},
2496                                {DominatorTree::Delete, PredBB, BB}});
2497 
2498   updateSSA(BB, NewBB, ValueMapping);
2499 
2500   // At this point, the IR is fully up to date and consistent.  Do a quick scan
2501   // over the new instructions and zap any that are constants or dead.  This
2502   // frequently happens because of phi translation.
2503   SimplifyInstructionsInBlock(NewBB, TLI);
2504 
2505   // Update the edge weight from BB to SuccBB, which should be less than before.
2506   updateBlockFreqAndEdgeWeight(PredBB, BB, NewBB, SuccBB, BFI, BPI, HasProfile);
2507 
2508   // Threaded an edge!
2509   ++NumThreads;
2510 }
2511 
2512 /// Create a new basic block that will be the predecessor of BB and successor of
2513 /// all blocks in Preds. When profile data is available, update the frequency of
2514 /// this new block.
2515 BasicBlock *JumpThreadingPass::splitBlockPreds(BasicBlock *BB,
2516                                                ArrayRef<BasicBlock *> Preds,
2517                                                const char *Suffix) {
2518   SmallVector<BasicBlock *, 2> NewBBs;
2519 
2520   // Collect the frequencies of all predecessors of BB, which will be used to
2521   // update the edge weight of the result of splitting predecessors.
2522   DenseMap<BasicBlock *, BlockFrequency> FreqMap;
2523   auto *BFI = getBFI();
2524   if (BFI) {
2525     auto *BPI = getOrCreateBPI(true);
2526     for (auto *Pred : Preds)
2527       FreqMap.insert(std::make_pair(
2528           Pred, BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, BB)));
2529   }
2530 
2531   // In the case when BB is a LandingPad block we create 2 new predecessors
2532   // instead of just one.
2533   if (BB->isLandingPad()) {
2534     std::string NewName = std::string(Suffix) + ".split-lp";
2535     SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs);
2536   } else {
2537     NewBBs.push_back(SplitBlockPredecessors(BB, Preds, Suffix));
2538   }
2539 
2540   std::vector<DominatorTree::UpdateType> Updates;
2541   Updates.reserve((2 * Preds.size()) + NewBBs.size());
2542   for (auto *NewBB : NewBBs) {
2543     BlockFrequency NewBBFreq(0);
2544     Updates.push_back({DominatorTree::Insert, NewBB, BB});
2545     for (auto *Pred : predecessors(NewBB)) {
2546       Updates.push_back({DominatorTree::Delete, Pred, BB});
2547       Updates.push_back({DominatorTree::Insert, Pred, NewBB});
2548       if (BFI) // Update frequencies between Pred -> NewBB.
2549         NewBBFreq += FreqMap.lookup(Pred);
2550     }
2551     if (BFI) // Apply the summed frequency to NewBB.
2552       BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
2553   }
2554 
2555   DTU->applyUpdatesPermissive(Updates);
2556   return NewBBs[0];
2557 }
2558 
2559 bool JumpThreadingPass::doesBlockHaveProfileData(BasicBlock *BB) {
2560   const Instruction *TI = BB->getTerminator();
2561   if (!TI || TI->getNumSuccessors() < 2)
2562     return false;
2563 
2564   return hasValidBranchWeightMD(*TI);
2565 }
2566 
2567 /// Update the block frequency of BB and branch weight and the metadata on the
2568 /// edge BB->SuccBB. This is done by scaling the weight of BB->SuccBB by 1 -
2569 /// Freq(PredBB->BB) / Freq(BB->SuccBB).
2570 void JumpThreadingPass::updateBlockFreqAndEdgeWeight(BasicBlock *PredBB,
2571                                                      BasicBlock *BB,
2572                                                      BasicBlock *NewBB,
2573                                                      BasicBlock *SuccBB,
2574                                                      BlockFrequencyInfo *BFI,
2575                                                      BranchProbabilityInfo *BPI,
2576                                                      bool HasProfile) {
2577   assert(((BFI && BPI) || (!BFI && !BFI)) &&
2578          "Both BFI & BPI should either be set or unset");
2579 
2580   if (!BFI) {
2581     assert(!HasProfile &&
2582            "It's expected to have BFI/BPI when profile info exists");
2583     return;
2584   }
2585 
2586   // As the edge from PredBB to BB is deleted, we have to update the block
2587   // frequency of BB.
2588   auto BBOrigFreq = BFI->getBlockFreq(BB);
2589   auto NewBBFreq = BFI->getBlockFreq(NewBB);
2590   auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(BB, SuccBB);
2591   auto BBNewFreq = BBOrigFreq - NewBBFreq;
2592   BFI->setBlockFreq(BB, BBNewFreq.getFrequency());
2593 
2594   // Collect updated outgoing edges' frequencies from BB and use them to update
2595   // edge probabilities.
2596   SmallVector<uint64_t, 4> BBSuccFreq;
2597   for (BasicBlock *Succ : successors(BB)) {
2598     auto SuccFreq = (Succ == SuccBB)
2599                         ? BB2SuccBBFreq - NewBBFreq
2600                         : BBOrigFreq * BPI->getEdgeProbability(BB, Succ);
2601     BBSuccFreq.push_back(SuccFreq.getFrequency());
2602   }
2603 
2604   uint64_t MaxBBSuccFreq =
2605       *std::max_element(BBSuccFreq.begin(), BBSuccFreq.end());
2606 
2607   SmallVector<BranchProbability, 4> BBSuccProbs;
2608   if (MaxBBSuccFreq == 0)
2609     BBSuccProbs.assign(BBSuccFreq.size(),
2610                        {1, static_cast<unsigned>(BBSuccFreq.size())});
2611   else {
2612     for (uint64_t Freq : BBSuccFreq)
2613       BBSuccProbs.push_back(
2614           BranchProbability::getBranchProbability(Freq, MaxBBSuccFreq));
2615     // Normalize edge probabilities so that they sum up to one.
2616     BranchProbability::normalizeProbabilities(BBSuccProbs.begin(),
2617                                               BBSuccProbs.end());
2618   }
2619 
2620   // Update edge probabilities in BPI.
2621   BPI->setEdgeProbability(BB, BBSuccProbs);
2622 
2623   // Update the profile metadata as well.
2624   //
2625   // Don't do this if the profile of the transformed blocks was statically
2626   // estimated.  (This could occur despite the function having an entry
2627   // frequency in completely cold parts of the CFG.)
2628   //
2629   // In this case we don't want to suggest to subsequent passes that the
2630   // calculated weights are fully consistent.  Consider this graph:
2631   //
2632   //                 check_1
2633   //             50% /  |
2634   //             eq_1   | 50%
2635   //                 \  |
2636   //                 check_2
2637   //             50% /  |
2638   //             eq_2   | 50%
2639   //                 \  |
2640   //                 check_3
2641   //             50% /  |
2642   //             eq_3   | 50%
2643   //                 \  |
2644   //
2645   // Assuming the blocks check_* all compare the same value against 1, 2 and 3,
2646   // the overall probabilities are inconsistent; the total probability that the
2647   // value is either 1, 2 or 3 is 150%.
2648   //
2649   // As a consequence if we thread eq_1 -> check_2 to check_3, check_2->check_3
2650   // becomes 0%.  This is even worse if the edge whose probability becomes 0% is
2651   // the loop exit edge.  Then based solely on static estimation we would assume
2652   // the loop was extremely hot.
2653   //
2654   // FIXME this locally as well so that BPI and BFI are consistent as well.  We
2655   // shouldn't make edges extremely likely or unlikely based solely on static
2656   // estimation.
2657   if (BBSuccProbs.size() >= 2 && HasProfile) {
2658     SmallVector<uint32_t, 4> Weights;
2659     for (auto Prob : BBSuccProbs)
2660       Weights.push_back(Prob.getNumerator());
2661 
2662     auto TI = BB->getTerminator();
2663     TI->setMetadata(
2664         LLVMContext::MD_prof,
2665         MDBuilder(TI->getParent()->getContext()).createBranchWeights(Weights));
2666   }
2667 }
2668 
2669 /// duplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
2670 /// to BB which contains an i1 PHI node and a conditional branch on that PHI.
2671 /// If we can duplicate the contents of BB up into PredBB do so now, this
2672 /// improves the odds that the branch will be on an analyzable instruction like
2673 /// a compare.
2674 bool JumpThreadingPass::duplicateCondBranchOnPHIIntoPred(
2675     BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs) {
2676   assert(!PredBBs.empty() && "Can't handle an empty set");
2677 
2678   // If BB is a loop header, then duplicating this block outside the loop would
2679   // cause us to transform this into an irreducible loop, don't do this.
2680   // See the comments above findLoopHeaders for justifications and caveats.
2681   if (LoopHeaders.count(BB)) {
2682     LLVM_DEBUG(dbgs() << "  Not duplicating loop header '" << BB->getName()
2683                       << "' into predecessor block '" << PredBBs[0]->getName()
2684                       << "' - it might create an irreducible loop!\n");
2685     return false;
2686   }
2687 
2688   unsigned DuplicationCost = getJumpThreadDuplicationCost(
2689       TTI, BB, BB->getTerminator(), BBDupThreshold);
2690   if (DuplicationCost > BBDupThreshold) {
2691     LLVM_DEBUG(dbgs() << "  Not duplicating BB '" << BB->getName()
2692                       << "' - Cost is too high: " << DuplicationCost << "\n");
2693     return false;
2694   }
2695 
2696   // And finally, do it!  Start by factoring the predecessors if needed.
2697   std::vector<DominatorTree::UpdateType> Updates;
2698   BasicBlock *PredBB;
2699   if (PredBBs.size() == 1)
2700     PredBB = PredBBs[0];
2701   else {
2702     LLVM_DEBUG(dbgs() << "  Factoring out " << PredBBs.size()
2703                       << " common predecessors.\n");
2704     PredBB = splitBlockPreds(BB, PredBBs, ".thr_comm");
2705   }
2706   Updates.push_back({DominatorTree::Delete, PredBB, BB});
2707 
2708   // Okay, we decided to do this!  Clone all the instructions in BB onto the end
2709   // of PredBB.
2710   LLVM_DEBUG(dbgs() << "  Duplicating block '" << BB->getName()
2711                     << "' into end of '" << PredBB->getName()
2712                     << "' to eliminate branch on phi.  Cost: "
2713                     << DuplicationCost << " block is:" << *BB << "\n");
2714 
2715   // Unless PredBB ends with an unconditional branch, split the edge so that we
2716   // can just clone the bits from BB into the end of the new PredBB.
2717   BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
2718 
2719   if (!OldPredBranch || !OldPredBranch->isUnconditional()) {
2720     BasicBlock *OldPredBB = PredBB;
2721     PredBB = SplitEdge(OldPredBB, BB);
2722     Updates.push_back({DominatorTree::Insert, OldPredBB, PredBB});
2723     Updates.push_back({DominatorTree::Insert, PredBB, BB});
2724     Updates.push_back({DominatorTree::Delete, OldPredBB, BB});
2725     OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
2726   }
2727 
2728   // We are going to have to map operands from the original BB block into the
2729   // PredBB block.  Evaluate PHI nodes in BB.
2730   DenseMap<Instruction*, Value*> ValueMapping;
2731 
2732   BasicBlock::iterator BI = BB->begin();
2733   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
2734     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
2735   // Clone the non-phi instructions of BB into PredBB, keeping track of the
2736   // mapping and using it to remap operands in the cloned instructions.
2737   for (; BI != BB->end(); ++BI) {
2738     Instruction *New = BI->clone();
2739 
2740     // Remap operands to patch up intra-block references.
2741     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2742       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
2743         DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
2744         if (I != ValueMapping.end())
2745           New->setOperand(i, I->second);
2746       }
2747 
2748     // If this instruction can be simplified after the operands are updated,
2749     // just use the simplified value instead.  This frequently happens due to
2750     // phi translation.
2751     if (Value *IV = simplifyInstruction(
2752             New,
2753             {BB->getModule()->getDataLayout(), TLI, nullptr, nullptr, New})) {
2754       ValueMapping[&*BI] = IV;
2755       if (!New->mayHaveSideEffects()) {
2756         New->deleteValue();
2757         New = nullptr;
2758       }
2759     } else {
2760       ValueMapping[&*BI] = New;
2761     }
2762     if (New) {
2763       // Otherwise, insert the new instruction into the block.
2764       New->setName(BI->getName());
2765       New->insertInto(PredBB, OldPredBranch->getIterator());
2766       // Update Dominance from simplified New instruction operands.
2767       for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2768         if (BasicBlock *SuccBB = dyn_cast<BasicBlock>(New->getOperand(i)))
2769           Updates.push_back({DominatorTree::Insert, PredBB, SuccBB});
2770     }
2771   }
2772 
2773   // Check to see if the targets of the branch had PHI nodes. If so, we need to
2774   // add entries to the PHI nodes for branch from PredBB now.
2775   BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
2776   addPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
2777                                   ValueMapping);
2778   addPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
2779                                   ValueMapping);
2780 
2781   updateSSA(BB, PredBB, ValueMapping);
2782 
2783   // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
2784   // that we nuked.
2785   BB->removePredecessor(PredBB, true);
2786 
2787   // Remove the unconditional branch at the end of the PredBB block.
2788   OldPredBranch->eraseFromParent();
2789   if (auto *BPI = getBPI())
2790     BPI->copyEdgeProbabilities(BB, PredBB);
2791   DTU->applyUpdatesPermissive(Updates);
2792 
2793   ++NumDupes;
2794   return true;
2795 }
2796 
2797 // Pred is a predecessor of BB with an unconditional branch to BB. SI is
2798 // a Select instruction in Pred. BB has other predecessors and SI is used in
2799 // a PHI node in BB. SI has no other use.
2800 // A new basic block, NewBB, is created and SI is converted to compare and
2801 // conditional branch. SI is erased from parent.
2802 void JumpThreadingPass::unfoldSelectInstr(BasicBlock *Pred, BasicBlock *BB,
2803                                           SelectInst *SI, PHINode *SIUse,
2804                                           unsigned Idx) {
2805   // Expand the select.
2806   //
2807   // Pred --
2808   //  |    v
2809   //  |  NewBB
2810   //  |    |
2811   //  |-----
2812   //  v
2813   // BB
2814   BranchInst *PredTerm = cast<BranchInst>(Pred->getTerminator());
2815   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold",
2816                                          BB->getParent(), BB);
2817   // Move the unconditional branch to NewBB.
2818   PredTerm->removeFromParent();
2819   PredTerm->insertInto(NewBB, NewBB->end());
2820   // Create a conditional branch and update PHI nodes.
2821   auto *BI = BranchInst::Create(NewBB, BB, SI->getCondition(), Pred);
2822   BI->applyMergedLocation(PredTerm->getDebugLoc(), SI->getDebugLoc());
2823   BI->copyMetadata(*SI, {LLVMContext::MD_prof});
2824   SIUse->setIncomingValue(Idx, SI->getFalseValue());
2825   SIUse->addIncoming(SI->getTrueValue(), NewBB);
2826 
2827   uint64_t TrueWeight = 1;
2828   uint64_t FalseWeight = 1;
2829   // Copy probabilities from 'SI' to created conditional branch in 'Pred'.
2830   if (extractBranchWeights(*SI, TrueWeight, FalseWeight) &&
2831       (TrueWeight + FalseWeight) != 0) {
2832     SmallVector<BranchProbability, 2> BP;
2833     BP.emplace_back(BranchProbability::getBranchProbability(
2834         TrueWeight, TrueWeight + FalseWeight));
2835     BP.emplace_back(BranchProbability::getBranchProbability(
2836         FalseWeight, TrueWeight + FalseWeight));
2837     // Update BPI if exists.
2838     if (auto *BPI = getBPI())
2839       BPI->setEdgeProbability(Pred, BP);
2840   }
2841   // Set the block frequency of NewBB.
2842   if (auto *BFI = getBFI()) {
2843     if ((TrueWeight + FalseWeight) == 0) {
2844       TrueWeight = 1;
2845       FalseWeight = 1;
2846     }
2847     BranchProbability PredToNewBBProb = BranchProbability::getBranchProbability(
2848         TrueWeight, TrueWeight + FalseWeight);
2849     auto NewBBFreq = BFI->getBlockFreq(Pred) * PredToNewBBProb;
2850     BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
2851   }
2852 
2853   // The select is now dead.
2854   SI->eraseFromParent();
2855   DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, BB},
2856                                {DominatorTree::Insert, Pred, NewBB}});
2857 
2858   // Update any other PHI nodes in BB.
2859   for (BasicBlock::iterator BI = BB->begin();
2860        PHINode *Phi = dyn_cast<PHINode>(BI); ++BI)
2861     if (Phi != SIUse)
2862       Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB);
2863 }
2864 
2865 bool JumpThreadingPass::tryToUnfoldSelect(SwitchInst *SI, BasicBlock *BB) {
2866   PHINode *CondPHI = dyn_cast<PHINode>(SI->getCondition());
2867 
2868   if (!CondPHI || CondPHI->getParent() != BB)
2869     return false;
2870 
2871   for (unsigned I = 0, E = CondPHI->getNumIncomingValues(); I != E; ++I) {
2872     BasicBlock *Pred = CondPHI->getIncomingBlock(I);
2873     SelectInst *PredSI = dyn_cast<SelectInst>(CondPHI->getIncomingValue(I));
2874 
2875     // The second and third condition can be potentially relaxed. Currently
2876     // the conditions help to simplify the code and allow us to reuse existing
2877     // code, developed for tryToUnfoldSelect(CmpInst *, BasicBlock *)
2878     if (!PredSI || PredSI->getParent() != Pred || !PredSI->hasOneUse())
2879       continue;
2880 
2881     BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
2882     if (!PredTerm || !PredTerm->isUnconditional())
2883       continue;
2884 
2885     unfoldSelectInstr(Pred, BB, PredSI, CondPHI, I);
2886     return true;
2887   }
2888   return false;
2889 }
2890 
2891 /// tryToUnfoldSelect - Look for blocks of the form
2892 /// bb1:
2893 ///   %a = select
2894 ///   br bb2
2895 ///
2896 /// bb2:
2897 ///   %p = phi [%a, %bb1] ...
2898 ///   %c = icmp %p
2899 ///   br i1 %c
2900 ///
2901 /// And expand the select into a branch structure if one of its arms allows %c
2902 /// to be folded. This later enables threading from bb1 over bb2.
2903 bool JumpThreadingPass::tryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) {
2904   BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
2905   PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0));
2906   Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1));
2907 
2908   if (!CondBr || !CondBr->isConditional() || !CondLHS ||
2909       CondLHS->getParent() != BB)
2910     return false;
2911 
2912   for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) {
2913     BasicBlock *Pred = CondLHS->getIncomingBlock(I);
2914     SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I));
2915 
2916     // Look if one of the incoming values is a select in the corresponding
2917     // predecessor.
2918     if (!SI || SI->getParent() != Pred || !SI->hasOneUse())
2919       continue;
2920 
2921     BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
2922     if (!PredTerm || !PredTerm->isUnconditional())
2923       continue;
2924 
2925     // Now check if one of the select values would allow us to constant fold the
2926     // terminator in BB. We don't do the transform if both sides fold, those
2927     // cases will be threaded in any case.
2928     LazyValueInfo::Tristate LHSFolds =
2929         LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1),
2930                                 CondRHS, Pred, BB, CondCmp);
2931     LazyValueInfo::Tristate RHSFolds =
2932         LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2),
2933                                 CondRHS, Pred, BB, CondCmp);
2934     if ((LHSFolds != LazyValueInfo::Unknown ||
2935          RHSFolds != LazyValueInfo::Unknown) &&
2936         LHSFolds != RHSFolds) {
2937       unfoldSelectInstr(Pred, BB, SI, CondLHS, I);
2938       return true;
2939     }
2940   }
2941   return false;
2942 }
2943 
2944 /// tryToUnfoldSelectInCurrBB - Look for PHI/Select or PHI/CMP/Select in the
2945 /// same BB in the form
2946 /// bb:
2947 ///   %p = phi [false, %bb1], [true, %bb2], [false, %bb3], [true, %bb4], ...
2948 ///   %s = select %p, trueval, falseval
2949 ///
2950 /// or
2951 ///
2952 /// bb:
2953 ///   %p = phi [0, %bb1], [1, %bb2], [0, %bb3], [1, %bb4], ...
2954 ///   %c = cmp %p, 0
2955 ///   %s = select %c, trueval, falseval
2956 ///
2957 /// And expand the select into a branch structure. This later enables
2958 /// jump-threading over bb in this pass.
2959 ///
2960 /// Using the similar approach of SimplifyCFG::FoldCondBranchOnPHI(), unfold
2961 /// select if the associated PHI has at least one constant.  If the unfolded
2962 /// select is not jump-threaded, it will be folded again in the later
2963 /// optimizations.
2964 bool JumpThreadingPass::tryToUnfoldSelectInCurrBB(BasicBlock *BB) {
2965   // This transform would reduce the quality of msan diagnostics.
2966   // Disable this transform under MemorySanitizer.
2967   if (BB->getParent()->hasFnAttribute(Attribute::SanitizeMemory))
2968     return false;
2969 
2970   // If threading this would thread across a loop header, don't thread the edge.
2971   // See the comments above findLoopHeaders for justifications and caveats.
2972   if (LoopHeaders.count(BB))
2973     return false;
2974 
2975   for (BasicBlock::iterator BI = BB->begin();
2976        PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
2977     // Look for a Phi having at least one constant incoming value.
2978     if (llvm::all_of(PN->incoming_values(),
2979                      [](Value *V) { return !isa<ConstantInt>(V); }))
2980       continue;
2981 
2982     auto isUnfoldCandidate = [BB](SelectInst *SI, Value *V) {
2983       using namespace PatternMatch;
2984 
2985       // Check if SI is in BB and use V as condition.
2986       if (SI->getParent() != BB)
2987         return false;
2988       Value *Cond = SI->getCondition();
2989       bool IsAndOr = match(SI, m_CombineOr(m_LogicalAnd(), m_LogicalOr()));
2990       return Cond && Cond == V && Cond->getType()->isIntegerTy(1) && !IsAndOr;
2991     };
2992 
2993     SelectInst *SI = nullptr;
2994     for (Use &U : PN->uses()) {
2995       if (ICmpInst *Cmp = dyn_cast<ICmpInst>(U.getUser())) {
2996         // Look for a ICmp in BB that compares PN with a constant and is the
2997         // condition of a Select.
2998         if (Cmp->getParent() == BB && Cmp->hasOneUse() &&
2999             isa<ConstantInt>(Cmp->getOperand(1 - U.getOperandNo())))
3000           if (SelectInst *SelectI = dyn_cast<SelectInst>(Cmp->user_back()))
3001             if (isUnfoldCandidate(SelectI, Cmp->use_begin()->get())) {
3002               SI = SelectI;
3003               break;
3004             }
3005       } else if (SelectInst *SelectI = dyn_cast<SelectInst>(U.getUser())) {
3006         // Look for a Select in BB that uses PN as condition.
3007         if (isUnfoldCandidate(SelectI, U.get())) {
3008           SI = SelectI;
3009           break;
3010         }
3011       }
3012     }
3013 
3014     if (!SI)
3015       continue;
3016     // Expand the select.
3017     Value *Cond = SI->getCondition();
3018     if (!isGuaranteedNotToBeUndefOrPoison(Cond, nullptr, SI))
3019       Cond = new FreezeInst(Cond, "cond.fr", SI);
3020     Instruction *Term = SplitBlockAndInsertIfThen(Cond, SI, false);
3021     BasicBlock *SplitBB = SI->getParent();
3022     BasicBlock *NewBB = Term->getParent();
3023     PHINode *NewPN = PHINode::Create(SI->getType(), 2, "", SI);
3024     NewPN->addIncoming(SI->getTrueValue(), Term->getParent());
3025     NewPN->addIncoming(SI->getFalseValue(), BB);
3026     SI->replaceAllUsesWith(NewPN);
3027     SI->eraseFromParent();
3028     // NewBB and SplitBB are newly created blocks which require insertion.
3029     std::vector<DominatorTree::UpdateType> Updates;
3030     Updates.reserve((2 * SplitBB->getTerminator()->getNumSuccessors()) + 3);
3031     Updates.push_back({DominatorTree::Insert, BB, SplitBB});
3032     Updates.push_back({DominatorTree::Insert, BB, NewBB});
3033     Updates.push_back({DominatorTree::Insert, NewBB, SplitBB});
3034     // BB's successors were moved to SplitBB, update DTU accordingly.
3035     for (auto *Succ : successors(SplitBB)) {
3036       Updates.push_back({DominatorTree::Delete, BB, Succ});
3037       Updates.push_back({DominatorTree::Insert, SplitBB, Succ});
3038     }
3039     DTU->applyUpdatesPermissive(Updates);
3040     return true;
3041   }
3042   return false;
3043 }
3044 
3045 /// Try to propagate a guard from the current BB into one of its predecessors
3046 /// in case if another branch of execution implies that the condition of this
3047 /// guard is always true. Currently we only process the simplest case that
3048 /// looks like:
3049 ///
3050 /// Start:
3051 ///   %cond = ...
3052 ///   br i1 %cond, label %T1, label %F1
3053 /// T1:
3054 ///   br label %Merge
3055 /// F1:
3056 ///   br label %Merge
3057 /// Merge:
3058 ///   %condGuard = ...
3059 ///   call void(i1, ...) @llvm.experimental.guard( i1 %condGuard )[ "deopt"() ]
3060 ///
3061 /// And cond either implies condGuard or !condGuard. In this case all the
3062 /// instructions before the guard can be duplicated in both branches, and the
3063 /// guard is then threaded to one of them.
3064 bool JumpThreadingPass::processGuards(BasicBlock *BB) {
3065   using namespace PatternMatch;
3066 
3067   // We only want to deal with two predecessors.
3068   BasicBlock *Pred1, *Pred2;
3069   auto PI = pred_begin(BB), PE = pred_end(BB);
3070   if (PI == PE)
3071     return false;
3072   Pred1 = *PI++;
3073   if (PI == PE)
3074     return false;
3075   Pred2 = *PI++;
3076   if (PI != PE)
3077     return false;
3078   if (Pred1 == Pred2)
3079     return false;
3080 
3081   // Try to thread one of the guards of the block.
3082   // TODO: Look up deeper than to immediate predecessor?
3083   auto *Parent = Pred1->getSinglePredecessor();
3084   if (!Parent || Parent != Pred2->getSinglePredecessor())
3085     return false;
3086 
3087   if (auto *BI = dyn_cast<BranchInst>(Parent->getTerminator()))
3088     for (auto &I : *BB)
3089       if (isGuard(&I) && threadGuard(BB, cast<IntrinsicInst>(&I), BI))
3090         return true;
3091 
3092   return false;
3093 }
3094 
3095 /// Try to propagate the guard from BB which is the lower block of a diamond
3096 /// to one of its branches, in case if diamond's condition implies guard's
3097 /// condition.
3098 bool JumpThreadingPass::threadGuard(BasicBlock *BB, IntrinsicInst *Guard,
3099                                     BranchInst *BI) {
3100   assert(BI->getNumSuccessors() == 2 && "Wrong number of successors?");
3101   assert(BI->isConditional() && "Unconditional branch has 2 successors?");
3102   Value *GuardCond = Guard->getArgOperand(0);
3103   Value *BranchCond = BI->getCondition();
3104   BasicBlock *TrueDest = BI->getSuccessor(0);
3105   BasicBlock *FalseDest = BI->getSuccessor(1);
3106 
3107   auto &DL = BB->getModule()->getDataLayout();
3108   bool TrueDestIsSafe = false;
3109   bool FalseDestIsSafe = false;
3110 
3111   // True dest is safe if BranchCond => GuardCond.
3112   auto Impl = isImpliedCondition(BranchCond, GuardCond, DL);
3113   if (Impl && *Impl)
3114     TrueDestIsSafe = true;
3115   else {
3116     // False dest is safe if !BranchCond => GuardCond.
3117     Impl = isImpliedCondition(BranchCond, GuardCond, DL, /* LHSIsTrue */ false);
3118     if (Impl && *Impl)
3119       FalseDestIsSafe = true;
3120   }
3121 
3122   if (!TrueDestIsSafe && !FalseDestIsSafe)
3123     return false;
3124 
3125   BasicBlock *PredUnguardedBlock = TrueDestIsSafe ? TrueDest : FalseDest;
3126   BasicBlock *PredGuardedBlock = FalseDestIsSafe ? TrueDest : FalseDest;
3127 
3128   ValueToValueMapTy UnguardedMapping, GuardedMapping;
3129   Instruction *AfterGuard = Guard->getNextNode();
3130   unsigned Cost =
3131       getJumpThreadDuplicationCost(TTI, BB, AfterGuard, BBDupThreshold);
3132   if (Cost > BBDupThreshold)
3133     return false;
3134   // Duplicate all instructions before the guard and the guard itself to the
3135   // branch where implication is not proved.
3136   BasicBlock *GuardedBlock = DuplicateInstructionsInSplitBetween(
3137       BB, PredGuardedBlock, AfterGuard, GuardedMapping, *DTU);
3138   assert(GuardedBlock && "Could not create the guarded block?");
3139   // Duplicate all instructions before the guard in the unguarded branch.
3140   // Since we have successfully duplicated the guarded block and this block
3141   // has fewer instructions, we expect it to succeed.
3142   BasicBlock *UnguardedBlock = DuplicateInstructionsInSplitBetween(
3143       BB, PredUnguardedBlock, Guard, UnguardedMapping, *DTU);
3144   assert(UnguardedBlock && "Could not create the unguarded block?");
3145   LLVM_DEBUG(dbgs() << "Moved guard " << *Guard << " to block "
3146                     << GuardedBlock->getName() << "\n");
3147   // Some instructions before the guard may still have uses. For them, we need
3148   // to create Phi nodes merging their copies in both guarded and unguarded
3149   // branches. Those instructions that have no uses can be just removed.
3150   SmallVector<Instruction *, 4> ToRemove;
3151   for (auto BI = BB->begin(); &*BI != AfterGuard; ++BI)
3152     if (!isa<PHINode>(&*BI))
3153       ToRemove.push_back(&*BI);
3154 
3155   Instruction *InsertionPoint = &*BB->getFirstInsertionPt();
3156   assert(InsertionPoint && "Empty block?");
3157   // Substitute with Phis & remove.
3158   for (auto *Inst : reverse(ToRemove)) {
3159     if (!Inst->use_empty()) {
3160       PHINode *NewPN = PHINode::Create(Inst->getType(), 2);
3161       NewPN->addIncoming(UnguardedMapping[Inst], UnguardedBlock);
3162       NewPN->addIncoming(GuardedMapping[Inst], GuardedBlock);
3163       NewPN->insertBefore(InsertionPoint);
3164       Inst->replaceAllUsesWith(NewPN);
3165     }
3166     Inst->eraseFromParent();
3167   }
3168   return true;
3169 }
3170 
3171 PreservedAnalyses JumpThreadingPass::getPreservedAnalysis() const {
3172   PreservedAnalyses PA;
3173   PA.preserve<LazyValueAnalysis>();
3174   PA.preserve<DominatorTreeAnalysis>();
3175 
3176   // TODO: We would like to preserve BPI/BFI. Enable once all paths update them.
3177   // TODO: Would be nice to verify BPI/BFI consistency as well.
3178   return PA;
3179 }
3180 
3181 template <typename AnalysisT>
3182 typename AnalysisT::Result *JumpThreadingPass::runExternalAnalysis() {
3183   assert(FAM && "Can't run external analysis without FunctionAnalysisManager");
3184 
3185   // If there were no changes since last call to 'runExternalAnalysis' then all
3186   // analysis is either up to date or explicitly invalidated. Just go ahead and
3187   // run the "external" analysis.
3188   if (!ChangedSinceLastAnalysisUpdate) {
3189     assert(!DTU->hasPendingUpdates() &&
3190            "Lost update of 'ChangedSinceLastAnalysisUpdate'?");
3191     // Run the "external" analysis.
3192     return &FAM->getResult<AnalysisT>(*F);
3193   }
3194   ChangedSinceLastAnalysisUpdate = false;
3195 
3196   auto PA = getPreservedAnalysis();
3197   // TODO: This shouldn't be needed once 'getPreservedAnalysis' reports BPI/BFI
3198   // as preserved.
3199   PA.preserve<BranchProbabilityAnalysis>();
3200   PA.preserve<BlockFrequencyAnalysis>();
3201   // Report everything except explicitly preserved as invalid.
3202   FAM->invalidate(*F, PA);
3203   // Update DT/PDT.
3204   DTU->flush();
3205   // Make sure DT/PDT are valid before running "external" analysis.
3206   assert(DTU->getDomTree().verify(DominatorTree::VerificationLevel::Fast));
3207   assert((!DTU->hasPostDomTree() ||
3208           DTU->getPostDomTree().verify(
3209               PostDominatorTree::VerificationLevel::Fast)));
3210   // Run the "external" analysis.
3211   auto *Result = &FAM->getResult<AnalysisT>(*F);
3212   // Update analysis JumpThreading depends on and not explicitly preserved.
3213   TTI = &FAM->getResult<TargetIRAnalysis>(*F);
3214   TLI = &FAM->getResult<TargetLibraryAnalysis>(*F);
3215   AA = &FAM->getResult<AAManager>(*F);
3216 
3217   return Result;
3218 }
3219 
3220 BranchProbabilityInfo *JumpThreadingPass::getBPI() {
3221   if (!BPI) {
3222     assert(FAM && "Can't create BPI without FunctionAnalysisManager");
3223     BPI = FAM->getCachedResult<BranchProbabilityAnalysis>(*F);
3224   }
3225   return *BPI;
3226 }
3227 
3228 BlockFrequencyInfo *JumpThreadingPass::getBFI() {
3229   if (!BFI) {
3230     assert(FAM && "Can't create BFI without FunctionAnalysisManager");
3231     BFI = FAM->getCachedResult<BlockFrequencyAnalysis>(*F);
3232   }
3233   return *BFI;
3234 }
3235 
3236 // Important note on validity of BPI/BFI. JumpThreading tries to preserve
3237 // BPI/BFI as it goes. Thus if cached instance exists it will be updated.
3238 // Otherwise, new instance of BPI/BFI is created (up to date by definition).
3239 BranchProbabilityInfo *JumpThreadingPass::getOrCreateBPI(bool Force) {
3240   auto *Res = getBPI();
3241   if (Res)
3242     return Res;
3243 
3244   if (Force)
3245     BPI = runExternalAnalysis<BranchProbabilityAnalysis>();
3246 
3247   return *BPI;
3248 }
3249 
3250 BlockFrequencyInfo *JumpThreadingPass::getOrCreateBFI(bool Force) {
3251   auto *Res = getBFI();
3252   if (Res)
3253     return Res;
3254 
3255   if (Force)
3256     BFI = runExternalAnalysis<BlockFrequencyAnalysis>();
3257 
3258   return *BFI;
3259 }
3260