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