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