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