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