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