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