xref: /aosp_15_r20/external/llvm/lib/Transforms/Scalar/JumpThreading.cpp (revision 9880d6810fe72a1726cb53787c6711e909410d58)
1*9880d681SAndroid Build Coastguard Worker //===- JumpThreading.cpp - Thread control through conditional blocks ------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker //                     The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This file implements the Jump Threading pass.
11*9880d681SAndroid Build Coastguard Worker //
12*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
13*9880d681SAndroid Build Coastguard Worker 
14*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar/JumpThreading.h"
15*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar.h"
16*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/DenseMap.h"
17*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/DenseSet.h"
18*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/STLExtras.h"
19*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
20*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/GlobalsModRef.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/CFG.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
23*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ConstantFolding.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/InstructionSimplify.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/Loads.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/LoopInfo.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ValueTracking.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/LLVMContext.h"
31*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/MDBuilder.h"
32*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Metadata.h"
33*9880d681SAndroid Build Coastguard Worker #include "llvm/Pass.h"
34*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/CommandLine.h"
35*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
36*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
37*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Local.h"
39*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/SSAUpdater.h"
40*9880d681SAndroid Build Coastguard Worker #include <algorithm>
41*9880d681SAndroid Build Coastguard Worker #include <memory>
42*9880d681SAndroid Build Coastguard Worker using namespace llvm;
43*9880d681SAndroid Build Coastguard Worker using namespace jumpthreading;
44*9880d681SAndroid Build Coastguard Worker 
45*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "jump-threading"
46*9880d681SAndroid Build Coastguard Worker 
47*9880d681SAndroid Build Coastguard Worker STATISTIC(NumThreads, "Number of jumps threaded");
48*9880d681SAndroid Build Coastguard Worker STATISTIC(NumFolds,   "Number of terminators folded");
49*9880d681SAndroid Build Coastguard Worker STATISTIC(NumDupes,   "Number of branch blocks duplicated to eliminate phi");
50*9880d681SAndroid Build Coastguard Worker 
51*9880d681SAndroid Build Coastguard Worker static cl::opt<unsigned>
52*9880d681SAndroid Build Coastguard Worker BBDuplicateThreshold("jump-threading-threshold",
53*9880d681SAndroid Build Coastguard Worker           cl::desc("Max block size to duplicate for jump threading"),
54*9880d681SAndroid Build Coastguard Worker           cl::init(6), cl::Hidden);
55*9880d681SAndroid Build Coastguard Worker 
56*9880d681SAndroid Build Coastguard Worker static cl::opt<unsigned>
57*9880d681SAndroid Build Coastguard Worker ImplicationSearchThreshold(
58*9880d681SAndroid Build Coastguard Worker   "jump-threading-implication-search-threshold",
59*9880d681SAndroid Build Coastguard Worker   cl::desc("The number of predecessors to search for a stronger "
60*9880d681SAndroid Build Coastguard Worker            "condition to use to thread over a weaker condition"),
61*9880d681SAndroid Build Coastguard Worker   cl::init(3), cl::Hidden);
62*9880d681SAndroid Build Coastguard Worker 
63*9880d681SAndroid Build Coastguard Worker namespace {
64*9880d681SAndroid Build Coastguard Worker   /// This pass performs 'jump threading', which looks at blocks that have
65*9880d681SAndroid Build Coastguard Worker   /// multiple predecessors and multiple successors.  If one or more of the
66*9880d681SAndroid Build Coastguard Worker   /// predecessors of the block can be proven to always jump to one of the
67*9880d681SAndroid Build Coastguard Worker   /// successors, we forward the edge from the predecessor to the successor by
68*9880d681SAndroid Build Coastguard Worker   /// duplicating the contents of this block.
69*9880d681SAndroid Build Coastguard Worker   ///
70*9880d681SAndroid Build Coastguard Worker   /// An example of when this can occur is code like this:
71*9880d681SAndroid Build Coastguard Worker   ///
72*9880d681SAndroid Build Coastguard Worker   ///   if () { ...
73*9880d681SAndroid Build Coastguard Worker   ///     X = 4;
74*9880d681SAndroid Build Coastguard Worker   ///   }
75*9880d681SAndroid Build Coastguard Worker   ///   if (X < 3) {
76*9880d681SAndroid Build Coastguard Worker   ///
77*9880d681SAndroid Build Coastguard Worker   /// In this case, the unconditional branch at the end of the first if can be
78*9880d681SAndroid Build Coastguard Worker   /// revectored to the false side of the second if.
79*9880d681SAndroid Build Coastguard Worker   ///
80*9880d681SAndroid Build Coastguard Worker   class JumpThreading : public FunctionPass {
81*9880d681SAndroid Build Coastguard Worker     JumpThreadingPass Impl;
82*9880d681SAndroid Build Coastguard Worker 
83*9880d681SAndroid Build Coastguard Worker   public:
84*9880d681SAndroid Build Coastguard Worker     static char ID; // Pass identification
JumpThreading(int T=-1)85*9880d681SAndroid Build Coastguard Worker     JumpThreading(int T = -1) : FunctionPass(ID), Impl(T) {
86*9880d681SAndroid Build Coastguard Worker       initializeJumpThreadingPass(*PassRegistry::getPassRegistry());
87*9880d681SAndroid Build Coastguard Worker     }
88*9880d681SAndroid Build Coastguard Worker 
89*9880d681SAndroid Build Coastguard Worker     bool runOnFunction(Function &F) override;
90*9880d681SAndroid Build Coastguard Worker 
getAnalysisUsage(AnalysisUsage & AU) const91*9880d681SAndroid Build Coastguard Worker     void getAnalysisUsage(AnalysisUsage &AU) const override {
92*9880d681SAndroid Build Coastguard Worker       AU.addRequired<LazyValueInfoWrapperPass>();
93*9880d681SAndroid Build Coastguard Worker       AU.addPreserved<LazyValueInfoWrapperPass>();
94*9880d681SAndroid Build Coastguard Worker       AU.addPreserved<GlobalsAAWrapperPass>();
95*9880d681SAndroid Build Coastguard Worker       AU.addRequired<TargetLibraryInfoWrapperPass>();
96*9880d681SAndroid Build Coastguard Worker     }
97*9880d681SAndroid Build Coastguard Worker 
releaseMemory()98*9880d681SAndroid Build Coastguard Worker     void releaseMemory() override { Impl.releaseMemory(); }
99*9880d681SAndroid Build Coastguard Worker   };
100*9880d681SAndroid Build Coastguard Worker }
101*9880d681SAndroid Build Coastguard Worker 
102*9880d681SAndroid Build Coastguard Worker char JumpThreading::ID = 0;
103*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading",
104*9880d681SAndroid Build Coastguard Worker                 "Jump Threading", false, false)
INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)105*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
106*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
107*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(JumpThreading, "jump-threading",
108*9880d681SAndroid Build Coastguard Worker                 "Jump Threading", false, false)
109*9880d681SAndroid Build Coastguard Worker 
110*9880d681SAndroid Build Coastguard Worker // Public interface to the Jump Threading pass
111*9880d681SAndroid Build Coastguard Worker FunctionPass *llvm::createJumpThreadingPass(int Threshold) { return new JumpThreading(Threshold); }
112*9880d681SAndroid Build Coastguard Worker 
JumpThreadingPass(int T)113*9880d681SAndroid Build Coastguard Worker JumpThreadingPass::JumpThreadingPass(int T) {
114*9880d681SAndroid Build Coastguard Worker   BBDupThreshold = (T == -1) ? BBDuplicateThreshold : unsigned(T);
115*9880d681SAndroid Build Coastguard Worker }
116*9880d681SAndroid Build Coastguard Worker 
117*9880d681SAndroid Build Coastguard Worker /// runOnFunction - Top level algorithm.
118*9880d681SAndroid Build Coastguard Worker ///
runOnFunction(Function & F)119*9880d681SAndroid Build Coastguard Worker bool JumpThreading::runOnFunction(Function &F) {
120*9880d681SAndroid Build Coastguard Worker   if (skipFunction(F))
121*9880d681SAndroid Build Coastguard Worker     return false;
122*9880d681SAndroid Build Coastguard Worker   auto TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
123*9880d681SAndroid Build Coastguard Worker   auto LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
124*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<BlockFrequencyInfo> BFI;
125*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<BranchProbabilityInfo> BPI;
126*9880d681SAndroid Build Coastguard Worker   bool HasProfileData = F.getEntryCount().hasValue();
127*9880d681SAndroid Build Coastguard Worker   if (HasProfileData) {
128*9880d681SAndroid Build Coastguard Worker     LoopInfo LI{DominatorTree(F)};
129*9880d681SAndroid Build Coastguard Worker     BPI.reset(new BranchProbabilityInfo(F, LI));
130*9880d681SAndroid Build Coastguard Worker     BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
131*9880d681SAndroid Build Coastguard Worker   }
132*9880d681SAndroid Build Coastguard Worker   return Impl.runImpl(F, TLI, LVI, HasProfileData, std::move(BFI),
133*9880d681SAndroid Build Coastguard Worker                       std::move(BPI));
134*9880d681SAndroid Build Coastguard Worker }
135*9880d681SAndroid Build Coastguard Worker 
run(Function & F,AnalysisManager<Function> & AM)136*9880d681SAndroid Build Coastguard Worker PreservedAnalyses JumpThreadingPass::run(Function &F,
137*9880d681SAndroid Build Coastguard Worker                                          AnalysisManager<Function> &AM) {
138*9880d681SAndroid Build Coastguard Worker 
139*9880d681SAndroid Build Coastguard Worker   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
140*9880d681SAndroid Build Coastguard Worker   auto &LVI = AM.getResult<LazyValueAnalysis>(F);
141*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<BlockFrequencyInfo> BFI;
142*9880d681SAndroid Build Coastguard Worker   std::unique_ptr<BranchProbabilityInfo> BPI;
143*9880d681SAndroid Build Coastguard Worker   bool HasProfileData = F.getEntryCount().hasValue();
144*9880d681SAndroid Build Coastguard Worker   if (HasProfileData) {
145*9880d681SAndroid Build Coastguard Worker     LoopInfo LI{DominatorTree(F)};
146*9880d681SAndroid Build Coastguard Worker     BPI.reset(new BranchProbabilityInfo(F, LI));
147*9880d681SAndroid Build Coastguard Worker     BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
148*9880d681SAndroid Build Coastguard Worker   }
149*9880d681SAndroid Build Coastguard Worker   bool Changed =
150*9880d681SAndroid Build Coastguard Worker       runImpl(F, &TLI, &LVI, HasProfileData, std::move(BFI), std::move(BPI));
151*9880d681SAndroid Build Coastguard Worker 
152*9880d681SAndroid Build Coastguard Worker   // FIXME: We need to invalidate LVI to avoid PR28400. Is there a better
153*9880d681SAndroid Build Coastguard Worker   // solution?
154*9880d681SAndroid Build Coastguard Worker   AM.invalidate<LazyValueAnalysis>(F);
155*9880d681SAndroid Build Coastguard Worker 
156*9880d681SAndroid Build Coastguard Worker   if (!Changed)
157*9880d681SAndroid Build Coastguard Worker     return PreservedAnalyses::all();
158*9880d681SAndroid Build Coastguard Worker   PreservedAnalyses PA;
159*9880d681SAndroid Build Coastguard Worker   PA.preserve<GlobalsAA>();
160*9880d681SAndroid Build Coastguard Worker   return PA;
161*9880d681SAndroid Build Coastguard Worker }
162*9880d681SAndroid Build Coastguard Worker 
runImpl(Function & F,TargetLibraryInfo * TLI_,LazyValueInfo * LVI_,bool HasProfileData_,std::unique_ptr<BlockFrequencyInfo> BFI_,std::unique_ptr<BranchProbabilityInfo> BPI_)163*9880d681SAndroid Build Coastguard Worker bool JumpThreadingPass::runImpl(Function &F, TargetLibraryInfo *TLI_,
164*9880d681SAndroid Build Coastguard Worker                                 LazyValueInfo *LVI_, bool HasProfileData_,
165*9880d681SAndroid Build Coastguard Worker                                 std::unique_ptr<BlockFrequencyInfo> BFI_,
166*9880d681SAndroid Build Coastguard Worker                                 std::unique_ptr<BranchProbabilityInfo> BPI_) {
167*9880d681SAndroid Build Coastguard Worker 
168*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n");
169*9880d681SAndroid Build Coastguard Worker   TLI = TLI_;
170*9880d681SAndroid Build Coastguard Worker   LVI = LVI_;
171*9880d681SAndroid Build Coastguard Worker   BFI.reset();
172*9880d681SAndroid Build Coastguard Worker   BPI.reset();
173*9880d681SAndroid Build Coastguard Worker   // When profile data is available, we need to update edge weights after
174*9880d681SAndroid Build Coastguard Worker   // successful jump threading, which requires both BPI and BFI being available.
175*9880d681SAndroid Build Coastguard Worker   HasProfileData = HasProfileData_;
176*9880d681SAndroid Build Coastguard Worker   if (HasProfileData) {
177*9880d681SAndroid Build Coastguard Worker     BPI = std::move(BPI_);
178*9880d681SAndroid Build Coastguard Worker     BFI = std::move(BFI_);
179*9880d681SAndroid Build Coastguard Worker   }
180*9880d681SAndroid Build Coastguard Worker 
181*9880d681SAndroid Build Coastguard Worker   // Remove unreachable blocks from function as they may result in infinite
182*9880d681SAndroid Build Coastguard Worker   // loop. We do threading if we found something profitable. Jump threading a
183*9880d681SAndroid Build Coastguard Worker   // branch can create other opportunities. If these opportunities form a cycle
184*9880d681SAndroid Build Coastguard Worker   // i.e. if any jump threading is undoing previous threading in the path, then
185*9880d681SAndroid Build Coastguard Worker   // we will loop forever. We take care of this issue by not jump threading for
186*9880d681SAndroid Build Coastguard Worker   // back edges. This works for normal cases but not for unreachable blocks as
187*9880d681SAndroid Build Coastguard Worker   // they may have cycle with no back edge.
188*9880d681SAndroid Build Coastguard Worker   bool EverChanged = false;
189*9880d681SAndroid Build Coastguard Worker   EverChanged |= removeUnreachableBlocks(F, LVI);
190*9880d681SAndroid Build Coastguard Worker 
191*9880d681SAndroid Build Coastguard Worker   FindLoopHeaders(F);
192*9880d681SAndroid Build Coastguard Worker 
193*9880d681SAndroid Build Coastguard Worker   bool Changed;
194*9880d681SAndroid Build Coastguard Worker   do {
195*9880d681SAndroid Build Coastguard Worker     Changed = false;
196*9880d681SAndroid Build Coastguard Worker     for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
197*9880d681SAndroid Build Coastguard Worker       BasicBlock *BB = &*I;
198*9880d681SAndroid Build Coastguard Worker       // Thread all of the branches we can over this block.
199*9880d681SAndroid Build Coastguard Worker       while (ProcessBlock(BB))
200*9880d681SAndroid Build Coastguard Worker         Changed = true;
201*9880d681SAndroid Build Coastguard Worker 
202*9880d681SAndroid Build Coastguard Worker       ++I;
203*9880d681SAndroid Build Coastguard Worker 
204*9880d681SAndroid Build Coastguard Worker       // If the block is trivially dead, zap it.  This eliminates the successor
205*9880d681SAndroid Build Coastguard Worker       // edges which simplifies the CFG.
206*9880d681SAndroid Build Coastguard Worker       if (pred_empty(BB) &&
207*9880d681SAndroid Build Coastguard Worker           BB != &BB->getParent()->getEntryBlock()) {
208*9880d681SAndroid Build Coastguard Worker         DEBUG(dbgs() << "  JT: Deleting dead block '" << BB->getName()
209*9880d681SAndroid Build Coastguard Worker               << "' with terminator: " << *BB->getTerminator() << '\n');
210*9880d681SAndroid Build Coastguard Worker         LoopHeaders.erase(BB);
211*9880d681SAndroid Build Coastguard Worker         LVI->eraseBlock(BB);
212*9880d681SAndroid Build Coastguard Worker         DeleteDeadBlock(BB);
213*9880d681SAndroid Build Coastguard Worker         Changed = true;
214*9880d681SAndroid Build Coastguard Worker         continue;
215*9880d681SAndroid Build Coastguard Worker       }
216*9880d681SAndroid Build Coastguard Worker 
217*9880d681SAndroid Build Coastguard Worker       BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
218*9880d681SAndroid Build Coastguard Worker 
219*9880d681SAndroid Build Coastguard Worker       // Can't thread an unconditional jump, but if the block is "almost
220*9880d681SAndroid Build Coastguard Worker       // empty", we can replace uses of it with uses of the successor and make
221*9880d681SAndroid Build Coastguard Worker       // this dead.
222*9880d681SAndroid Build Coastguard Worker       // We should not eliminate the loop header either, because eliminating
223*9880d681SAndroid Build Coastguard Worker       // a loop header might later prevent LoopSimplify from transforming nested
224*9880d681SAndroid Build Coastguard Worker       // loops into simplified form.
225*9880d681SAndroid Build Coastguard Worker       if (BI && BI->isUnconditional() &&
226*9880d681SAndroid Build Coastguard Worker           BB != &BB->getParent()->getEntryBlock() &&
227*9880d681SAndroid Build Coastguard Worker           // If the terminator is the only non-phi instruction, try to nuke it.
228*9880d681SAndroid Build Coastguard Worker           BB->getFirstNonPHIOrDbg()->isTerminator() && !LoopHeaders.count(BB)) {
229*9880d681SAndroid Build Coastguard Worker         // Since TryToSimplifyUncondBranchFromEmptyBlock may delete the
230*9880d681SAndroid Build Coastguard Worker         // block, we have to make sure it isn't in the LoopHeaders set.  We
231*9880d681SAndroid Build Coastguard Worker         // reinsert afterward if needed.
232*9880d681SAndroid Build Coastguard Worker         bool ErasedFromLoopHeaders = LoopHeaders.erase(BB);
233*9880d681SAndroid Build Coastguard Worker         BasicBlock *Succ = BI->getSuccessor(0);
234*9880d681SAndroid Build Coastguard Worker 
235*9880d681SAndroid Build Coastguard Worker         // FIXME: It is always conservatively correct to drop the info
236*9880d681SAndroid Build Coastguard Worker         // for a block even if it doesn't get erased.  This isn't totally
237*9880d681SAndroid Build Coastguard Worker         // awesome, but it allows us to use AssertingVH to prevent nasty
238*9880d681SAndroid Build Coastguard Worker         // dangling pointer issues within LazyValueInfo.
239*9880d681SAndroid Build Coastguard Worker         LVI->eraseBlock(BB);
240*9880d681SAndroid Build Coastguard Worker         if (TryToSimplifyUncondBranchFromEmptyBlock(BB)) {
241*9880d681SAndroid Build Coastguard Worker           Changed = true;
242*9880d681SAndroid Build Coastguard Worker           // If we deleted BB and BB was the header of a loop, then the
243*9880d681SAndroid Build Coastguard Worker           // successor is now the header of the loop.
244*9880d681SAndroid Build Coastguard Worker           BB = Succ;
245*9880d681SAndroid Build Coastguard Worker         }
246*9880d681SAndroid Build Coastguard Worker 
247*9880d681SAndroid Build Coastguard Worker         if (ErasedFromLoopHeaders)
248*9880d681SAndroid Build Coastguard Worker           LoopHeaders.insert(BB);
249*9880d681SAndroid Build Coastguard Worker       }
250*9880d681SAndroid Build Coastguard Worker     }
251*9880d681SAndroid Build Coastguard Worker     EverChanged |= Changed;
252*9880d681SAndroid Build Coastguard Worker   } while (Changed);
253*9880d681SAndroid Build Coastguard Worker 
254*9880d681SAndroid Build Coastguard Worker   LoopHeaders.clear();
255*9880d681SAndroid Build Coastguard Worker   return EverChanged;
256*9880d681SAndroid Build Coastguard Worker }
257*9880d681SAndroid Build Coastguard Worker 
258*9880d681SAndroid Build Coastguard Worker /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
259*9880d681SAndroid Build Coastguard Worker /// thread across it. Stop scanning the block when passing the threshold.
getJumpThreadDuplicationCost(const BasicBlock * BB,unsigned Threshold)260*9880d681SAndroid Build Coastguard Worker static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB,
261*9880d681SAndroid Build Coastguard Worker                                              unsigned Threshold) {
262*9880d681SAndroid Build Coastguard Worker   /// Ignore PHI nodes, these will be flattened when duplication happens.
263*9880d681SAndroid Build Coastguard Worker   BasicBlock::const_iterator I(BB->getFirstNonPHI());
264*9880d681SAndroid Build Coastguard Worker 
265*9880d681SAndroid Build Coastguard Worker   // FIXME: THREADING will delete values that are just used to compute the
266*9880d681SAndroid Build Coastguard Worker   // branch, so they shouldn't count against the duplication cost.
267*9880d681SAndroid Build Coastguard Worker 
268*9880d681SAndroid Build Coastguard Worker   unsigned Bonus = 0;
269*9880d681SAndroid Build Coastguard Worker   const TerminatorInst *BBTerm = BB->getTerminator();
270*9880d681SAndroid Build Coastguard Worker   // Threading through a switch statement is particularly profitable.  If this
271*9880d681SAndroid Build Coastguard Worker   // block ends in a switch, decrease its cost to make it more likely to happen.
272*9880d681SAndroid Build Coastguard Worker   if (isa<SwitchInst>(BBTerm))
273*9880d681SAndroid Build Coastguard Worker     Bonus = 6;
274*9880d681SAndroid Build Coastguard Worker 
275*9880d681SAndroid Build Coastguard Worker   // The same holds for indirect branches, but slightly more so.
276*9880d681SAndroid Build Coastguard Worker   if (isa<IndirectBrInst>(BBTerm))
277*9880d681SAndroid Build Coastguard Worker     Bonus = 8;
278*9880d681SAndroid Build Coastguard Worker 
279*9880d681SAndroid Build Coastguard Worker   // Bump the threshold up so the early exit from the loop doesn't skip the
280*9880d681SAndroid Build Coastguard Worker   // terminator-based Size adjustment at the end.
281*9880d681SAndroid Build Coastguard Worker   Threshold += Bonus;
282*9880d681SAndroid Build Coastguard Worker 
283*9880d681SAndroid Build Coastguard Worker   // Sum up the cost of each instruction until we get to the terminator.  Don't
284*9880d681SAndroid Build Coastguard Worker   // include the terminator because the copy won't include it.
285*9880d681SAndroid Build Coastguard Worker   unsigned Size = 0;
286*9880d681SAndroid Build Coastguard Worker   for (; !isa<TerminatorInst>(I); ++I) {
287*9880d681SAndroid Build Coastguard Worker 
288*9880d681SAndroid Build Coastguard Worker     // Stop scanning the block if we've reached the threshold.
289*9880d681SAndroid Build Coastguard Worker     if (Size > Threshold)
290*9880d681SAndroid Build Coastguard Worker       return Size;
291*9880d681SAndroid Build Coastguard Worker 
292*9880d681SAndroid Build Coastguard Worker     // Debugger intrinsics don't incur code size.
293*9880d681SAndroid Build Coastguard Worker     if (isa<DbgInfoIntrinsic>(I)) continue;
294*9880d681SAndroid Build Coastguard Worker 
295*9880d681SAndroid Build Coastguard Worker     // If this is a pointer->pointer bitcast, it is free.
296*9880d681SAndroid Build Coastguard Worker     if (isa<BitCastInst>(I) && I->getType()->isPointerTy())
297*9880d681SAndroid Build Coastguard Worker       continue;
298*9880d681SAndroid Build Coastguard Worker 
299*9880d681SAndroid Build Coastguard Worker     // Bail out if this instruction gives back a token type, it is not possible
300*9880d681SAndroid Build Coastguard Worker     // to duplicate it if it is used outside this BB.
301*9880d681SAndroid Build Coastguard Worker     if (I->getType()->isTokenTy() && I->isUsedOutsideOfBlock(BB))
302*9880d681SAndroid Build Coastguard Worker       return ~0U;
303*9880d681SAndroid Build Coastguard Worker 
304*9880d681SAndroid Build Coastguard Worker     // All other instructions count for at least one unit.
305*9880d681SAndroid Build Coastguard Worker     ++Size;
306*9880d681SAndroid Build Coastguard Worker 
307*9880d681SAndroid Build Coastguard Worker     // Calls are more expensive.  If they are non-intrinsic calls, we model them
308*9880d681SAndroid Build Coastguard Worker     // as having cost of 4.  If they are a non-vector intrinsic, we model them
309*9880d681SAndroid Build Coastguard Worker     // as having cost of 2 total, and if they are a vector intrinsic, we model
310*9880d681SAndroid Build Coastguard Worker     // them as having cost 1.
311*9880d681SAndroid Build Coastguard Worker     if (const CallInst *CI = dyn_cast<CallInst>(I)) {
312*9880d681SAndroid Build Coastguard Worker       if (CI->cannotDuplicate() || CI->isConvergent())
313*9880d681SAndroid Build Coastguard Worker         // Blocks with NoDuplicate are modelled as having infinite cost, so they
314*9880d681SAndroid Build Coastguard Worker         // are never duplicated.
315*9880d681SAndroid Build Coastguard Worker         return ~0U;
316*9880d681SAndroid Build Coastguard Worker       else if (!isa<IntrinsicInst>(CI))
317*9880d681SAndroid Build Coastguard Worker         Size += 3;
318*9880d681SAndroid Build Coastguard Worker       else if (!CI->getType()->isVectorTy())
319*9880d681SAndroid Build Coastguard Worker         Size += 1;
320*9880d681SAndroid Build Coastguard Worker     }
321*9880d681SAndroid Build Coastguard Worker   }
322*9880d681SAndroid Build Coastguard Worker 
323*9880d681SAndroid Build Coastguard Worker   return Size > Bonus ? Size - Bonus : 0;
324*9880d681SAndroid Build Coastguard Worker }
325*9880d681SAndroid Build Coastguard Worker 
326*9880d681SAndroid Build Coastguard Worker /// FindLoopHeaders - We do not want jump threading to turn proper loop
327*9880d681SAndroid Build Coastguard Worker /// structures into irreducible loops.  Doing this breaks up the loop nesting
328*9880d681SAndroid Build Coastguard Worker /// hierarchy and pessimizes later transformations.  To prevent this from
329*9880d681SAndroid Build Coastguard Worker /// happening, we first have to find the loop headers.  Here we approximate this
330*9880d681SAndroid Build Coastguard Worker /// by finding targets of backedges in the CFG.
331*9880d681SAndroid Build Coastguard Worker ///
332*9880d681SAndroid Build Coastguard Worker /// Note that there definitely are cases when we want to allow threading of
333*9880d681SAndroid Build Coastguard Worker /// edges across a loop header.  For example, threading a jump from outside the
334*9880d681SAndroid Build Coastguard Worker /// loop (the preheader) to an exit block of the loop is definitely profitable.
335*9880d681SAndroid Build Coastguard Worker /// It is also almost always profitable to thread backedges from within the loop
336*9880d681SAndroid Build Coastguard Worker /// to exit blocks, and is often profitable to thread backedges to other blocks
337*9880d681SAndroid Build Coastguard Worker /// within the loop (forming a nested loop).  This simple analysis is not rich
338*9880d681SAndroid Build Coastguard Worker /// enough to track all of these properties and keep it up-to-date as the CFG
339*9880d681SAndroid Build Coastguard Worker /// mutates, so we don't allow any of these transformations.
340*9880d681SAndroid Build Coastguard Worker ///
FindLoopHeaders(Function & F)341*9880d681SAndroid Build Coastguard Worker void JumpThreadingPass::FindLoopHeaders(Function &F) {
342*9880d681SAndroid Build Coastguard Worker   SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
343*9880d681SAndroid Build Coastguard Worker   FindFunctionBackedges(F, Edges);
344*9880d681SAndroid Build Coastguard Worker 
345*9880d681SAndroid Build Coastguard Worker   for (const auto &Edge : Edges)
346*9880d681SAndroid Build Coastguard Worker     LoopHeaders.insert(Edge.second);
347*9880d681SAndroid Build Coastguard Worker }
348*9880d681SAndroid Build Coastguard Worker 
349*9880d681SAndroid Build Coastguard Worker /// getKnownConstant - Helper method to determine if we can thread over a
350*9880d681SAndroid Build Coastguard Worker /// terminator with the given value as its condition, and if so what value to
351*9880d681SAndroid Build Coastguard Worker /// use for that. What kind of value this is depends on whether we want an
352*9880d681SAndroid Build Coastguard Worker /// integer or a block address, but an undef is always accepted.
353*9880d681SAndroid Build Coastguard Worker /// Returns null if Val is null or not an appropriate constant.
getKnownConstant(Value * Val,ConstantPreference Preference)354*9880d681SAndroid Build Coastguard Worker static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) {
355*9880d681SAndroid Build Coastguard Worker   if (!Val)
356*9880d681SAndroid Build Coastguard Worker     return nullptr;
357*9880d681SAndroid Build Coastguard Worker 
358*9880d681SAndroid Build Coastguard Worker   // Undef is "known" enough.
359*9880d681SAndroid Build Coastguard Worker   if (UndefValue *U = dyn_cast<UndefValue>(Val))
360*9880d681SAndroid Build Coastguard Worker     return U;
361*9880d681SAndroid Build Coastguard Worker 
362*9880d681SAndroid Build Coastguard Worker   if (Preference == WantBlockAddress)
363*9880d681SAndroid Build Coastguard Worker     return dyn_cast<BlockAddress>(Val->stripPointerCasts());
364*9880d681SAndroid Build Coastguard Worker 
365*9880d681SAndroid Build Coastguard Worker   return dyn_cast<ConstantInt>(Val);
366*9880d681SAndroid Build Coastguard Worker }
367*9880d681SAndroid Build Coastguard Worker 
368*9880d681SAndroid Build Coastguard Worker /// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
369*9880d681SAndroid Build Coastguard Worker /// if we can infer that the value is a known ConstantInt/BlockAddress or undef
370*9880d681SAndroid Build Coastguard Worker /// in any of our predecessors.  If so, return the known list of value and pred
371*9880d681SAndroid Build Coastguard Worker /// BB in the result vector.
372*9880d681SAndroid Build Coastguard Worker ///
373*9880d681SAndroid Build Coastguard Worker /// This returns true if there were any known values.
374*9880d681SAndroid Build Coastguard Worker ///
ComputeValueKnownInPredecessors(Value * V,BasicBlock * BB,PredValueInfo & Result,ConstantPreference Preference,Instruction * CxtI)375*9880d681SAndroid Build Coastguard Worker bool JumpThreadingPass::ComputeValueKnownInPredecessors(
376*9880d681SAndroid Build Coastguard Worker     Value *V, BasicBlock *BB, PredValueInfo &Result,
377*9880d681SAndroid Build Coastguard Worker     ConstantPreference Preference, Instruction *CxtI) {
378*9880d681SAndroid Build Coastguard Worker   // This method walks up use-def chains recursively.  Because of this, we could
379*9880d681SAndroid Build Coastguard Worker   // get into an infinite loop going around loops in the use-def chain.  To
380*9880d681SAndroid Build Coastguard Worker   // prevent this, keep track of what (value, block) pairs we've already visited
381*9880d681SAndroid Build Coastguard Worker   // and terminate the search if we loop back to them
382*9880d681SAndroid Build Coastguard Worker   if (!RecursionSet.insert(std::make_pair(V, BB)).second)
383*9880d681SAndroid Build Coastguard Worker     return false;
384*9880d681SAndroid Build Coastguard Worker 
385*9880d681SAndroid Build Coastguard Worker   // An RAII help to remove this pair from the recursion set once the recursion
386*9880d681SAndroid Build Coastguard Worker   // stack pops back out again.
387*9880d681SAndroid Build Coastguard Worker   RecursionSetRemover remover(RecursionSet, std::make_pair(V, BB));
388*9880d681SAndroid Build Coastguard Worker 
389*9880d681SAndroid Build Coastguard Worker   // If V is a constant, then it is known in all predecessors.
390*9880d681SAndroid Build Coastguard Worker   if (Constant *KC = getKnownConstant(V, Preference)) {
391*9880d681SAndroid Build Coastguard Worker     for (BasicBlock *Pred : predecessors(BB))
392*9880d681SAndroid Build Coastguard Worker       Result.push_back(std::make_pair(KC, Pred));
393*9880d681SAndroid Build Coastguard Worker 
394*9880d681SAndroid Build Coastguard Worker     return !Result.empty();
395*9880d681SAndroid Build Coastguard Worker   }
396*9880d681SAndroid Build Coastguard Worker 
397*9880d681SAndroid Build Coastguard Worker   // If V is a non-instruction value, or an instruction in a different block,
398*9880d681SAndroid Build Coastguard Worker   // then it can't be derived from a PHI.
399*9880d681SAndroid Build Coastguard Worker   Instruction *I = dyn_cast<Instruction>(V);
400*9880d681SAndroid Build Coastguard Worker   if (!I || I->getParent() != BB) {
401*9880d681SAndroid Build Coastguard Worker 
402*9880d681SAndroid Build Coastguard Worker     // Okay, if this is a live-in value, see if it has a known value at the end
403*9880d681SAndroid Build Coastguard Worker     // of any of our predecessors.
404*9880d681SAndroid Build Coastguard Worker     //
405*9880d681SAndroid Build Coastguard Worker     // FIXME: This should be an edge property, not a block end property.
406*9880d681SAndroid Build Coastguard Worker     /// TODO: Per PR2563, we could infer value range information about a
407*9880d681SAndroid Build Coastguard Worker     /// predecessor based on its terminator.
408*9880d681SAndroid Build Coastguard Worker     //
409*9880d681SAndroid Build Coastguard Worker     // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if
410*9880d681SAndroid Build Coastguard Worker     // "I" is a non-local compare-with-a-constant instruction.  This would be
411*9880d681SAndroid Build Coastguard Worker     // able to handle value inequalities better, for example if the compare is
412*9880d681SAndroid Build Coastguard Worker     // "X < 4" and "X < 3" is known true but "X < 4" itself is not available.
413*9880d681SAndroid Build Coastguard Worker     // Perhaps getConstantOnEdge should be smart enough to do this?
414*9880d681SAndroid Build Coastguard Worker 
415*9880d681SAndroid Build Coastguard Worker     for (BasicBlock *P : predecessors(BB)) {
416*9880d681SAndroid Build Coastguard Worker       // If the value is known by LazyValueInfo to be a constant in a
417*9880d681SAndroid Build Coastguard Worker       // predecessor, use that information to try to thread this block.
418*9880d681SAndroid Build Coastguard Worker       Constant *PredCst = LVI->getConstantOnEdge(V, P, BB, CxtI);
419*9880d681SAndroid Build Coastguard Worker       if (Constant *KC = getKnownConstant(PredCst, Preference))
420*9880d681SAndroid Build Coastguard Worker         Result.push_back(std::make_pair(KC, P));
421*9880d681SAndroid Build Coastguard Worker     }
422*9880d681SAndroid Build Coastguard Worker 
423*9880d681SAndroid Build Coastguard Worker     return !Result.empty();
424*9880d681SAndroid Build Coastguard Worker   }
425*9880d681SAndroid Build Coastguard Worker 
426*9880d681SAndroid Build Coastguard Worker   /// If I is a PHI node, then we know the incoming values for any constants.
427*9880d681SAndroid Build Coastguard Worker   if (PHINode *PN = dyn_cast<PHINode>(I)) {
428*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
429*9880d681SAndroid Build Coastguard Worker       Value *InVal = PN->getIncomingValue(i);
430*9880d681SAndroid Build Coastguard Worker       if (Constant *KC = getKnownConstant(InVal, Preference)) {
431*9880d681SAndroid Build Coastguard Worker         Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
432*9880d681SAndroid Build Coastguard Worker       } else {
433*9880d681SAndroid Build Coastguard Worker         Constant *CI = LVI->getConstantOnEdge(InVal,
434*9880d681SAndroid Build Coastguard Worker                                               PN->getIncomingBlock(i),
435*9880d681SAndroid Build Coastguard Worker                                               BB, CxtI);
436*9880d681SAndroid Build Coastguard Worker         if (Constant *KC = getKnownConstant(CI, Preference))
437*9880d681SAndroid Build Coastguard Worker           Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
438*9880d681SAndroid Build Coastguard Worker       }
439*9880d681SAndroid Build Coastguard Worker     }
440*9880d681SAndroid Build Coastguard Worker 
441*9880d681SAndroid Build Coastguard Worker     return !Result.empty();
442*9880d681SAndroid Build Coastguard Worker   }
443*9880d681SAndroid Build Coastguard Worker 
444*9880d681SAndroid Build Coastguard Worker   // Handle Cast instructions.  Only see through Cast when the source operand is
445*9880d681SAndroid Build Coastguard Worker   // PHI or Cmp and the source type is i1 to save the compilation time.
446*9880d681SAndroid Build Coastguard Worker   if (CastInst *CI = dyn_cast<CastInst>(I)) {
447*9880d681SAndroid Build Coastguard Worker     Value *Source = CI->getOperand(0);
448*9880d681SAndroid Build Coastguard Worker     if (!Source->getType()->isIntegerTy(1))
449*9880d681SAndroid Build Coastguard Worker       return false;
450*9880d681SAndroid Build Coastguard Worker     if (!isa<PHINode>(Source) && !isa<CmpInst>(Source))
451*9880d681SAndroid Build Coastguard Worker       return false;
452*9880d681SAndroid Build Coastguard Worker     ComputeValueKnownInPredecessors(Source, BB, Result, Preference, CxtI);
453*9880d681SAndroid Build Coastguard Worker     if (Result.empty())
454*9880d681SAndroid Build Coastguard Worker       return false;
455*9880d681SAndroid Build Coastguard Worker 
456*9880d681SAndroid Build Coastguard Worker     // Convert the known values.
457*9880d681SAndroid Build Coastguard Worker     for (auto &R : Result)
458*9880d681SAndroid Build Coastguard Worker       R.first = ConstantExpr::getCast(CI->getOpcode(), R.first, CI->getType());
459*9880d681SAndroid Build Coastguard Worker 
460*9880d681SAndroid Build Coastguard Worker     return true;
461*9880d681SAndroid Build Coastguard Worker   }
462*9880d681SAndroid Build Coastguard Worker 
463*9880d681SAndroid Build Coastguard Worker   PredValueInfoTy LHSVals, RHSVals;
464*9880d681SAndroid Build Coastguard Worker 
465*9880d681SAndroid Build Coastguard Worker   // Handle some boolean conditions.
466*9880d681SAndroid Build Coastguard Worker   if (I->getType()->getPrimitiveSizeInBits() == 1) {
467*9880d681SAndroid Build Coastguard Worker     assert(Preference == WantInteger && "One-bit non-integer type?");
468*9880d681SAndroid Build Coastguard Worker     // X | true -> true
469*9880d681SAndroid Build Coastguard Worker     // X & false -> false
470*9880d681SAndroid Build Coastguard Worker     if (I->getOpcode() == Instruction::Or ||
471*9880d681SAndroid Build Coastguard Worker         I->getOpcode() == Instruction::And) {
472*9880d681SAndroid Build Coastguard Worker       ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals,
473*9880d681SAndroid Build Coastguard Worker                                       WantInteger, CxtI);
474*9880d681SAndroid Build Coastguard Worker       ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals,
475*9880d681SAndroid Build Coastguard Worker                                       WantInteger, CxtI);
476*9880d681SAndroid Build Coastguard Worker 
477*9880d681SAndroid Build Coastguard Worker       if (LHSVals.empty() && RHSVals.empty())
478*9880d681SAndroid Build Coastguard Worker         return false;
479*9880d681SAndroid Build Coastguard Worker 
480*9880d681SAndroid Build Coastguard Worker       ConstantInt *InterestingVal;
481*9880d681SAndroid Build Coastguard Worker       if (I->getOpcode() == Instruction::Or)
482*9880d681SAndroid Build Coastguard Worker         InterestingVal = ConstantInt::getTrue(I->getContext());
483*9880d681SAndroid Build Coastguard Worker       else
484*9880d681SAndroid Build Coastguard Worker         InterestingVal = ConstantInt::getFalse(I->getContext());
485*9880d681SAndroid Build Coastguard Worker 
486*9880d681SAndroid Build Coastguard Worker       SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
487*9880d681SAndroid Build Coastguard Worker 
488*9880d681SAndroid Build Coastguard Worker       // Scan for the sentinel.  If we find an undef, force it to the
489*9880d681SAndroid Build Coastguard Worker       // interesting value: x|undef -> true and x&undef -> false.
490*9880d681SAndroid Build Coastguard Worker       for (const auto &LHSVal : LHSVals)
491*9880d681SAndroid Build Coastguard Worker         if (LHSVal.first == InterestingVal || isa<UndefValue>(LHSVal.first)) {
492*9880d681SAndroid Build Coastguard Worker           Result.emplace_back(InterestingVal, LHSVal.second);
493*9880d681SAndroid Build Coastguard Worker           LHSKnownBBs.insert(LHSVal.second);
494*9880d681SAndroid Build Coastguard Worker         }
495*9880d681SAndroid Build Coastguard Worker       for (const auto &RHSVal : RHSVals)
496*9880d681SAndroid Build Coastguard Worker         if (RHSVal.first == InterestingVal || isa<UndefValue>(RHSVal.first)) {
497*9880d681SAndroid Build Coastguard Worker           // If we already inferred a value for this block on the LHS, don't
498*9880d681SAndroid Build Coastguard Worker           // re-add it.
499*9880d681SAndroid Build Coastguard Worker           if (!LHSKnownBBs.count(RHSVal.second))
500*9880d681SAndroid Build Coastguard Worker             Result.emplace_back(InterestingVal, RHSVal.second);
501*9880d681SAndroid Build Coastguard Worker         }
502*9880d681SAndroid Build Coastguard Worker 
503*9880d681SAndroid Build Coastguard Worker       return !Result.empty();
504*9880d681SAndroid Build Coastguard Worker     }
505*9880d681SAndroid Build Coastguard Worker 
506*9880d681SAndroid Build Coastguard Worker     // Handle the NOT form of XOR.
507*9880d681SAndroid Build Coastguard Worker     if (I->getOpcode() == Instruction::Xor &&
508*9880d681SAndroid Build Coastguard Worker         isa<ConstantInt>(I->getOperand(1)) &&
509*9880d681SAndroid Build Coastguard Worker         cast<ConstantInt>(I->getOperand(1))->isOne()) {
510*9880d681SAndroid Build Coastguard Worker       ComputeValueKnownInPredecessors(I->getOperand(0), BB, Result,
511*9880d681SAndroid Build Coastguard Worker                                       WantInteger, CxtI);
512*9880d681SAndroid Build Coastguard Worker       if (Result.empty())
513*9880d681SAndroid Build Coastguard Worker         return false;
514*9880d681SAndroid Build Coastguard Worker 
515*9880d681SAndroid Build Coastguard Worker       // Invert the known values.
516*9880d681SAndroid Build Coastguard Worker       for (auto &R : Result)
517*9880d681SAndroid Build Coastguard Worker         R.first = ConstantExpr::getNot(R.first);
518*9880d681SAndroid Build Coastguard Worker 
519*9880d681SAndroid Build Coastguard Worker       return true;
520*9880d681SAndroid Build Coastguard Worker     }
521*9880d681SAndroid Build Coastguard Worker 
522*9880d681SAndroid Build Coastguard Worker   // Try to simplify some other binary operator values.
523*9880d681SAndroid Build Coastguard Worker   } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
524*9880d681SAndroid Build Coastguard Worker     assert(Preference != WantBlockAddress
525*9880d681SAndroid Build Coastguard Worker             && "A binary operator creating a block address?");
526*9880d681SAndroid Build Coastguard Worker     if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
527*9880d681SAndroid Build Coastguard Worker       PredValueInfoTy LHSVals;
528*9880d681SAndroid Build Coastguard Worker       ComputeValueKnownInPredecessors(BO->getOperand(0), BB, LHSVals,
529*9880d681SAndroid Build Coastguard Worker                                       WantInteger, CxtI);
530*9880d681SAndroid Build Coastguard Worker 
531*9880d681SAndroid Build Coastguard Worker       // Try to use constant folding to simplify the binary operator.
532*9880d681SAndroid Build Coastguard Worker       for (const auto &LHSVal : LHSVals) {
533*9880d681SAndroid Build Coastguard Worker         Constant *V = LHSVal.first;
534*9880d681SAndroid Build Coastguard Worker         Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI);
535*9880d681SAndroid Build Coastguard Worker 
536*9880d681SAndroid Build Coastguard Worker         if (Constant *KC = getKnownConstant(Folded, WantInteger))
537*9880d681SAndroid Build Coastguard Worker           Result.push_back(std::make_pair(KC, LHSVal.second));
538*9880d681SAndroid Build Coastguard Worker       }
539*9880d681SAndroid Build Coastguard Worker     }
540*9880d681SAndroid Build Coastguard Worker 
541*9880d681SAndroid Build Coastguard Worker     return !Result.empty();
542*9880d681SAndroid Build Coastguard Worker   }
543*9880d681SAndroid Build Coastguard Worker 
544*9880d681SAndroid Build Coastguard Worker   // Handle compare with phi operand, where the PHI is defined in this block.
545*9880d681SAndroid Build Coastguard Worker   if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
546*9880d681SAndroid Build Coastguard Worker     assert(Preference == WantInteger && "Compares only produce integers");
547*9880d681SAndroid Build Coastguard Worker     PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
548*9880d681SAndroid Build Coastguard Worker     if (PN && PN->getParent() == BB) {
549*9880d681SAndroid Build Coastguard Worker       const DataLayout &DL = PN->getModule()->getDataLayout();
550*9880d681SAndroid Build Coastguard Worker       // We can do this simplification if any comparisons fold to true or false.
551*9880d681SAndroid Build Coastguard Worker       // See if any do.
552*9880d681SAndroid Build Coastguard Worker       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
553*9880d681SAndroid Build Coastguard Worker         BasicBlock *PredBB = PN->getIncomingBlock(i);
554*9880d681SAndroid Build Coastguard Worker         Value *LHS = PN->getIncomingValue(i);
555*9880d681SAndroid Build Coastguard Worker         Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
556*9880d681SAndroid Build Coastguard Worker 
557*9880d681SAndroid Build Coastguard Worker         Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS, DL);
558*9880d681SAndroid Build Coastguard Worker         if (!Res) {
559*9880d681SAndroid Build Coastguard Worker           if (!isa<Constant>(RHS))
560*9880d681SAndroid Build Coastguard Worker             continue;
561*9880d681SAndroid Build Coastguard Worker 
562*9880d681SAndroid Build Coastguard Worker           LazyValueInfo::Tristate
563*9880d681SAndroid Build Coastguard Worker             ResT = LVI->getPredicateOnEdge(Cmp->getPredicate(), LHS,
564*9880d681SAndroid Build Coastguard Worker                                            cast<Constant>(RHS), PredBB, BB,
565*9880d681SAndroid Build Coastguard Worker                                            CxtI ? CxtI : Cmp);
566*9880d681SAndroid Build Coastguard Worker           if (ResT == LazyValueInfo::Unknown)
567*9880d681SAndroid Build Coastguard Worker             continue;
568*9880d681SAndroid Build Coastguard Worker           Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
569*9880d681SAndroid Build Coastguard Worker         }
570*9880d681SAndroid Build Coastguard Worker 
571*9880d681SAndroid Build Coastguard Worker         if (Constant *KC = getKnownConstant(Res, WantInteger))
572*9880d681SAndroid Build Coastguard Worker           Result.push_back(std::make_pair(KC, PredBB));
573*9880d681SAndroid Build Coastguard Worker       }
574*9880d681SAndroid Build Coastguard Worker 
575*9880d681SAndroid Build Coastguard Worker       return !Result.empty();
576*9880d681SAndroid Build Coastguard Worker     }
577*9880d681SAndroid Build Coastguard Worker 
578*9880d681SAndroid Build Coastguard Worker     // If comparing a live-in value against a constant, see if we know the
579*9880d681SAndroid Build Coastguard Worker     // live-in value on any predecessors.
580*9880d681SAndroid Build Coastguard Worker     if (isa<Constant>(Cmp->getOperand(1)) && Cmp->getType()->isIntegerTy()) {
581*9880d681SAndroid Build Coastguard Worker       if (!isa<Instruction>(Cmp->getOperand(0)) ||
582*9880d681SAndroid Build Coastguard Worker           cast<Instruction>(Cmp->getOperand(0))->getParent() != BB) {
583*9880d681SAndroid Build Coastguard Worker         Constant *RHSCst = cast<Constant>(Cmp->getOperand(1));
584*9880d681SAndroid Build Coastguard Worker 
585*9880d681SAndroid Build Coastguard Worker         for (BasicBlock *P : predecessors(BB)) {
586*9880d681SAndroid Build Coastguard Worker           // If the value is known by LazyValueInfo to be a constant in a
587*9880d681SAndroid Build Coastguard Worker           // predecessor, use that information to try to thread this block.
588*9880d681SAndroid Build Coastguard Worker           LazyValueInfo::Tristate Res =
589*9880d681SAndroid Build Coastguard Worker             LVI->getPredicateOnEdge(Cmp->getPredicate(), Cmp->getOperand(0),
590*9880d681SAndroid Build Coastguard Worker                                     RHSCst, P, BB, CxtI ? CxtI : Cmp);
591*9880d681SAndroid Build Coastguard Worker           if (Res == LazyValueInfo::Unknown)
592*9880d681SAndroid Build Coastguard Worker             continue;
593*9880d681SAndroid Build Coastguard Worker 
594*9880d681SAndroid Build Coastguard Worker           Constant *ResC = ConstantInt::get(Cmp->getType(), Res);
595*9880d681SAndroid Build Coastguard Worker           Result.push_back(std::make_pair(ResC, P));
596*9880d681SAndroid Build Coastguard Worker         }
597*9880d681SAndroid Build Coastguard Worker 
598*9880d681SAndroid Build Coastguard Worker         return !Result.empty();
599*9880d681SAndroid Build Coastguard Worker       }
600*9880d681SAndroid Build Coastguard Worker 
601*9880d681SAndroid Build Coastguard Worker       // Try to find a constant value for the LHS of a comparison,
602*9880d681SAndroid Build Coastguard Worker       // and evaluate it statically if we can.
603*9880d681SAndroid Build Coastguard Worker       if (Constant *CmpConst = dyn_cast<Constant>(Cmp->getOperand(1))) {
604*9880d681SAndroid Build Coastguard Worker         PredValueInfoTy LHSVals;
605*9880d681SAndroid Build Coastguard Worker         ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals,
606*9880d681SAndroid Build Coastguard Worker                                         WantInteger, CxtI);
607*9880d681SAndroid Build Coastguard Worker 
608*9880d681SAndroid Build Coastguard Worker         for (const auto &LHSVal : LHSVals) {
609*9880d681SAndroid Build Coastguard Worker           Constant *V = LHSVal.first;
610*9880d681SAndroid Build Coastguard Worker           Constant *Folded = ConstantExpr::getCompare(Cmp->getPredicate(),
611*9880d681SAndroid Build Coastguard Worker                                                       V, CmpConst);
612*9880d681SAndroid Build Coastguard Worker           if (Constant *KC = getKnownConstant(Folded, WantInteger))
613*9880d681SAndroid Build Coastguard Worker             Result.push_back(std::make_pair(KC, LHSVal.second));
614*9880d681SAndroid Build Coastguard Worker         }
615*9880d681SAndroid Build Coastguard Worker 
616*9880d681SAndroid Build Coastguard Worker         return !Result.empty();
617*9880d681SAndroid Build Coastguard Worker       }
618*9880d681SAndroid Build Coastguard Worker     }
619*9880d681SAndroid Build Coastguard Worker   }
620*9880d681SAndroid Build Coastguard Worker 
621*9880d681SAndroid Build Coastguard Worker   if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
622*9880d681SAndroid Build Coastguard Worker     // Handle select instructions where at least one operand is a known constant
623*9880d681SAndroid Build Coastguard Worker     // and we can figure out the condition value for any predecessor block.
624*9880d681SAndroid Build Coastguard Worker     Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference);
625*9880d681SAndroid Build Coastguard Worker     Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference);
626*9880d681SAndroid Build Coastguard Worker     PredValueInfoTy Conds;
627*9880d681SAndroid Build Coastguard Worker     if ((TrueVal || FalseVal) &&
628*9880d681SAndroid Build Coastguard Worker         ComputeValueKnownInPredecessors(SI->getCondition(), BB, Conds,
629*9880d681SAndroid Build Coastguard Worker                                         WantInteger, CxtI)) {
630*9880d681SAndroid Build Coastguard Worker       for (auto &C : Conds) {
631*9880d681SAndroid Build Coastguard Worker         Constant *Cond = C.first;
632*9880d681SAndroid Build Coastguard Worker 
633*9880d681SAndroid Build Coastguard Worker         // Figure out what value to use for the condition.
634*9880d681SAndroid Build Coastguard Worker         bool KnownCond;
635*9880d681SAndroid Build Coastguard Worker         if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
636*9880d681SAndroid Build Coastguard Worker           // A known boolean.
637*9880d681SAndroid Build Coastguard Worker           KnownCond = CI->isOne();
638*9880d681SAndroid Build Coastguard Worker         } else {
639*9880d681SAndroid Build Coastguard Worker           assert(isa<UndefValue>(Cond) && "Unexpected condition value");
640*9880d681SAndroid Build Coastguard Worker           // Either operand will do, so be sure to pick the one that's a known
641*9880d681SAndroid Build Coastguard Worker           // constant.
642*9880d681SAndroid Build Coastguard Worker           // FIXME: Do this more cleverly if both values are known constants?
643*9880d681SAndroid Build Coastguard Worker           KnownCond = (TrueVal != nullptr);
644*9880d681SAndroid Build Coastguard Worker         }
645*9880d681SAndroid Build Coastguard Worker 
646*9880d681SAndroid Build Coastguard Worker         // See if the select has a known constant value for this predecessor.
647*9880d681SAndroid Build Coastguard Worker         if (Constant *Val = KnownCond ? TrueVal : FalseVal)
648*9880d681SAndroid Build Coastguard Worker           Result.push_back(std::make_pair(Val, C.second));
649*9880d681SAndroid Build Coastguard Worker       }
650*9880d681SAndroid Build Coastguard Worker 
651*9880d681SAndroid Build Coastguard Worker       return !Result.empty();
652*9880d681SAndroid Build Coastguard Worker     }
653*9880d681SAndroid Build Coastguard Worker   }
654*9880d681SAndroid Build Coastguard Worker 
655*9880d681SAndroid Build Coastguard Worker   // If all else fails, see if LVI can figure out a constant value for us.
656*9880d681SAndroid Build Coastguard Worker   Constant *CI = LVI->getConstant(V, BB, CxtI);
657*9880d681SAndroid Build Coastguard Worker   if (Constant *KC = getKnownConstant(CI, Preference)) {
658*9880d681SAndroid Build Coastguard Worker     for (BasicBlock *Pred : predecessors(BB))
659*9880d681SAndroid Build Coastguard Worker       Result.push_back(std::make_pair(KC, Pred));
660*9880d681SAndroid Build Coastguard Worker   }
661*9880d681SAndroid Build Coastguard Worker 
662*9880d681SAndroid Build Coastguard Worker   return !Result.empty();
663*9880d681SAndroid Build Coastguard Worker }
664*9880d681SAndroid Build Coastguard Worker 
665*9880d681SAndroid Build Coastguard Worker 
666*9880d681SAndroid Build Coastguard Worker 
667*9880d681SAndroid Build Coastguard Worker /// GetBestDestForBranchOnUndef - If we determine that the specified block ends
668*9880d681SAndroid Build Coastguard Worker /// in an undefined jump, decide which block is best to revector to.
669*9880d681SAndroid Build Coastguard Worker ///
670*9880d681SAndroid Build Coastguard Worker /// Since we can pick an arbitrary destination, we pick the successor with the
671*9880d681SAndroid Build Coastguard Worker /// fewest predecessors.  This should reduce the in-degree of the others.
672*9880d681SAndroid Build Coastguard Worker ///
GetBestDestForJumpOnUndef(BasicBlock * BB)673*9880d681SAndroid Build Coastguard Worker static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
674*9880d681SAndroid Build Coastguard Worker   TerminatorInst *BBTerm = BB->getTerminator();
675*9880d681SAndroid Build Coastguard Worker   unsigned MinSucc = 0;
676*9880d681SAndroid Build Coastguard Worker   BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
677*9880d681SAndroid Build Coastguard Worker   // Compute the successor with the minimum number of predecessors.
678*9880d681SAndroid Build Coastguard Worker   unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
679*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
680*9880d681SAndroid Build Coastguard Worker     TestBB = BBTerm->getSuccessor(i);
681*9880d681SAndroid Build Coastguard Worker     unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
682*9880d681SAndroid Build Coastguard Worker     if (NumPreds < MinNumPreds) {
683*9880d681SAndroid Build Coastguard Worker       MinSucc = i;
684*9880d681SAndroid Build Coastguard Worker       MinNumPreds = NumPreds;
685*9880d681SAndroid Build Coastguard Worker     }
686*9880d681SAndroid Build Coastguard Worker   }
687*9880d681SAndroid Build Coastguard Worker 
688*9880d681SAndroid Build Coastguard Worker   return MinSucc;
689*9880d681SAndroid Build Coastguard Worker }
690*9880d681SAndroid Build Coastguard Worker 
hasAddressTakenAndUsed(BasicBlock * BB)691*9880d681SAndroid Build Coastguard Worker static bool hasAddressTakenAndUsed(BasicBlock *BB) {
692*9880d681SAndroid Build Coastguard Worker   if (!BB->hasAddressTaken()) return false;
693*9880d681SAndroid Build Coastguard Worker 
694*9880d681SAndroid Build Coastguard Worker   // If the block has its address taken, it may be a tree of dead constants
695*9880d681SAndroid Build Coastguard Worker   // hanging off of it.  These shouldn't keep the block alive.
696*9880d681SAndroid Build Coastguard Worker   BlockAddress *BA = BlockAddress::get(BB);
697*9880d681SAndroid Build Coastguard Worker   BA->removeDeadConstantUsers();
698*9880d681SAndroid Build Coastguard Worker   return !BA->use_empty();
699*9880d681SAndroid Build Coastguard Worker }
700*9880d681SAndroid Build Coastguard Worker 
701*9880d681SAndroid Build Coastguard Worker /// ProcessBlock - If there are any predecessors whose control can be threaded
702*9880d681SAndroid Build Coastguard Worker /// through to a successor, transform them now.
ProcessBlock(BasicBlock * BB)703*9880d681SAndroid Build Coastguard Worker bool JumpThreadingPass::ProcessBlock(BasicBlock *BB) {
704*9880d681SAndroid Build Coastguard Worker   // If the block is trivially dead, just return and let the caller nuke it.
705*9880d681SAndroid Build Coastguard Worker   // This simplifies other transformations.
706*9880d681SAndroid Build Coastguard Worker   if (pred_empty(BB) &&
707*9880d681SAndroid Build Coastguard Worker       BB != &BB->getParent()->getEntryBlock())
708*9880d681SAndroid Build Coastguard Worker     return false;
709*9880d681SAndroid Build Coastguard Worker 
710*9880d681SAndroid Build Coastguard Worker   // If this block has a single predecessor, and if that pred has a single
711*9880d681SAndroid Build Coastguard Worker   // successor, merge the blocks.  This encourages recursive jump threading
712*9880d681SAndroid Build Coastguard Worker   // because now the condition in this block can be threaded through
713*9880d681SAndroid Build Coastguard Worker   // predecessors of our predecessor block.
714*9880d681SAndroid Build Coastguard Worker   if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
715*9880d681SAndroid Build Coastguard Worker     const TerminatorInst *TI = SinglePred->getTerminator();
716*9880d681SAndroid Build Coastguard Worker     if (!TI->isExceptional() && TI->getNumSuccessors() == 1 &&
717*9880d681SAndroid Build Coastguard Worker         SinglePred != BB && !hasAddressTakenAndUsed(BB)) {
718*9880d681SAndroid Build Coastguard Worker       // If SinglePred was a loop header, BB becomes one.
719*9880d681SAndroid Build Coastguard Worker       if (LoopHeaders.erase(SinglePred))
720*9880d681SAndroid Build Coastguard Worker         LoopHeaders.insert(BB);
721*9880d681SAndroid Build Coastguard Worker 
722*9880d681SAndroid Build Coastguard Worker       LVI->eraseBlock(SinglePred);
723*9880d681SAndroid Build Coastguard Worker       MergeBasicBlockIntoOnlyPred(BB);
724*9880d681SAndroid Build Coastguard Worker 
725*9880d681SAndroid Build Coastguard Worker       return true;
726*9880d681SAndroid Build Coastguard Worker     }
727*9880d681SAndroid Build Coastguard Worker   }
728*9880d681SAndroid Build Coastguard Worker 
729*9880d681SAndroid Build Coastguard Worker   if (TryToUnfoldSelectInCurrBB(BB))
730*9880d681SAndroid Build Coastguard Worker     return true;
731*9880d681SAndroid Build Coastguard Worker 
732*9880d681SAndroid Build Coastguard Worker   // What kind of constant we're looking for.
733*9880d681SAndroid Build Coastguard Worker   ConstantPreference Preference = WantInteger;
734*9880d681SAndroid Build Coastguard Worker 
735*9880d681SAndroid Build Coastguard Worker   // Look to see if the terminator is a conditional branch, switch or indirect
736*9880d681SAndroid Build Coastguard Worker   // branch, if not we can't thread it.
737*9880d681SAndroid Build Coastguard Worker   Value *Condition;
738*9880d681SAndroid Build Coastguard Worker   Instruction *Terminator = BB->getTerminator();
739*9880d681SAndroid Build Coastguard Worker   if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) {
740*9880d681SAndroid Build Coastguard Worker     // Can't thread an unconditional jump.
741*9880d681SAndroid Build Coastguard Worker     if (BI->isUnconditional()) return false;
742*9880d681SAndroid Build Coastguard Worker     Condition = BI->getCondition();
743*9880d681SAndroid Build Coastguard Worker   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) {
744*9880d681SAndroid Build Coastguard Worker     Condition = SI->getCondition();
745*9880d681SAndroid Build Coastguard Worker   } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) {
746*9880d681SAndroid Build Coastguard Worker     // Can't thread indirect branch with no successors.
747*9880d681SAndroid Build Coastguard Worker     if (IB->getNumSuccessors() == 0) return false;
748*9880d681SAndroid Build Coastguard Worker     Condition = IB->getAddress()->stripPointerCasts();
749*9880d681SAndroid Build Coastguard Worker     Preference = WantBlockAddress;
750*9880d681SAndroid Build Coastguard Worker   } else {
751*9880d681SAndroid Build Coastguard Worker     return false; // Must be an invoke.
752*9880d681SAndroid Build Coastguard Worker   }
753*9880d681SAndroid Build Coastguard Worker 
754*9880d681SAndroid Build Coastguard Worker   // Run constant folding to see if we can reduce the condition to a simple
755*9880d681SAndroid Build Coastguard Worker   // constant.
756*9880d681SAndroid Build Coastguard Worker   if (Instruction *I = dyn_cast<Instruction>(Condition)) {
757*9880d681SAndroid Build Coastguard Worker     Value *SimpleVal =
758*9880d681SAndroid Build Coastguard Worker         ConstantFoldInstruction(I, BB->getModule()->getDataLayout(), TLI);
759*9880d681SAndroid Build Coastguard Worker     if (SimpleVal) {
760*9880d681SAndroid Build Coastguard Worker       I->replaceAllUsesWith(SimpleVal);
761*9880d681SAndroid Build Coastguard Worker       I->eraseFromParent();
762*9880d681SAndroid Build Coastguard Worker       Condition = SimpleVal;
763*9880d681SAndroid Build Coastguard Worker     }
764*9880d681SAndroid Build Coastguard Worker   }
765*9880d681SAndroid Build Coastguard Worker 
766*9880d681SAndroid Build Coastguard Worker   // If the terminator is branching on an undef, we can pick any of the
767*9880d681SAndroid Build Coastguard Worker   // successors to branch to.  Let GetBestDestForJumpOnUndef decide.
768*9880d681SAndroid Build Coastguard Worker   if (isa<UndefValue>(Condition)) {
769*9880d681SAndroid Build Coastguard Worker     unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
770*9880d681SAndroid Build Coastguard Worker 
771*9880d681SAndroid Build Coastguard Worker     // Fold the branch/switch.
772*9880d681SAndroid Build Coastguard Worker     TerminatorInst *BBTerm = BB->getTerminator();
773*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
774*9880d681SAndroid Build Coastguard Worker       if (i == BestSucc) continue;
775*9880d681SAndroid Build Coastguard Worker       BBTerm->getSuccessor(i)->removePredecessor(BB, true);
776*9880d681SAndroid Build Coastguard Worker     }
777*9880d681SAndroid Build Coastguard Worker 
778*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "  In block '" << BB->getName()
779*9880d681SAndroid Build Coastguard Worker           << "' folding undef terminator: " << *BBTerm << '\n');
780*9880d681SAndroid Build Coastguard Worker     BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
781*9880d681SAndroid Build Coastguard Worker     BBTerm->eraseFromParent();
782*9880d681SAndroid Build Coastguard Worker     return true;
783*9880d681SAndroid Build Coastguard Worker   }
784*9880d681SAndroid Build Coastguard Worker 
785*9880d681SAndroid Build Coastguard Worker   // If the terminator of this block is branching on a constant, simplify the
786*9880d681SAndroid Build Coastguard Worker   // terminator to an unconditional branch.  This can occur due to threading in
787*9880d681SAndroid Build Coastguard Worker   // other blocks.
788*9880d681SAndroid Build Coastguard Worker   if (getKnownConstant(Condition, Preference)) {
789*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "  In block '" << BB->getName()
790*9880d681SAndroid Build Coastguard Worker           << "' folding terminator: " << *BB->getTerminator() << '\n');
791*9880d681SAndroid Build Coastguard Worker     ++NumFolds;
792*9880d681SAndroid Build Coastguard Worker     ConstantFoldTerminator(BB, true);
793*9880d681SAndroid Build Coastguard Worker     return true;
794*9880d681SAndroid Build Coastguard Worker   }
795*9880d681SAndroid Build Coastguard Worker 
796*9880d681SAndroid Build Coastguard Worker   Instruction *CondInst = dyn_cast<Instruction>(Condition);
797*9880d681SAndroid Build Coastguard Worker 
798*9880d681SAndroid Build Coastguard Worker   // All the rest of our checks depend on the condition being an instruction.
799*9880d681SAndroid Build Coastguard Worker   if (!CondInst) {
800*9880d681SAndroid Build Coastguard Worker     // FIXME: Unify this with code below.
801*9880d681SAndroid Build Coastguard Worker     if (ProcessThreadableEdges(Condition, BB, Preference, Terminator))
802*9880d681SAndroid Build Coastguard Worker       return true;
803*9880d681SAndroid Build Coastguard Worker     return false;
804*9880d681SAndroid Build Coastguard Worker   }
805*9880d681SAndroid Build Coastguard Worker 
806*9880d681SAndroid Build Coastguard Worker 
807*9880d681SAndroid Build Coastguard Worker   if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
808*9880d681SAndroid Build Coastguard Worker     // If we're branching on a conditional, LVI might be able to determine
809*9880d681SAndroid Build Coastguard Worker     // it's value at the branch instruction.  We only handle comparisons
810*9880d681SAndroid Build Coastguard Worker     // against a constant at this time.
811*9880d681SAndroid Build Coastguard Worker     // TODO: This should be extended to handle switches as well.
812*9880d681SAndroid Build Coastguard Worker     BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
813*9880d681SAndroid Build Coastguard Worker     Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1));
814*9880d681SAndroid Build Coastguard Worker     if (CondBr && CondConst && CondBr->isConditional()) {
815*9880d681SAndroid Build Coastguard Worker       LazyValueInfo::Tristate Ret =
816*9880d681SAndroid Build Coastguard Worker         LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0),
817*9880d681SAndroid Build Coastguard Worker                             CondConst, CondBr);
818*9880d681SAndroid Build Coastguard Worker       if (Ret != LazyValueInfo::Unknown) {
819*9880d681SAndroid Build Coastguard Worker         unsigned ToRemove = Ret == LazyValueInfo::True ? 1 : 0;
820*9880d681SAndroid Build Coastguard Worker         unsigned ToKeep = Ret == LazyValueInfo::True ? 0 : 1;
821*9880d681SAndroid Build Coastguard Worker         CondBr->getSuccessor(ToRemove)->removePredecessor(BB, true);
822*9880d681SAndroid Build Coastguard Worker         BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr);
823*9880d681SAndroid Build Coastguard Worker         CondBr->eraseFromParent();
824*9880d681SAndroid Build Coastguard Worker         if (CondCmp->use_empty())
825*9880d681SAndroid Build Coastguard Worker           CondCmp->eraseFromParent();
826*9880d681SAndroid Build Coastguard Worker         else if (CondCmp->getParent() == BB) {
827*9880d681SAndroid Build Coastguard Worker           // If the fact we just learned is true for all uses of the
828*9880d681SAndroid Build Coastguard Worker           // condition, replace it with a constant value
829*9880d681SAndroid Build Coastguard Worker           auto *CI = Ret == LazyValueInfo::True ?
830*9880d681SAndroid Build Coastguard Worker             ConstantInt::getTrue(CondCmp->getType()) :
831*9880d681SAndroid Build Coastguard Worker             ConstantInt::getFalse(CondCmp->getType());
832*9880d681SAndroid Build Coastguard Worker           CondCmp->replaceAllUsesWith(CI);
833*9880d681SAndroid Build Coastguard Worker           CondCmp->eraseFromParent();
834*9880d681SAndroid Build Coastguard Worker         }
835*9880d681SAndroid Build Coastguard Worker         return true;
836*9880d681SAndroid Build Coastguard Worker       }
837*9880d681SAndroid Build Coastguard Worker     }
838*9880d681SAndroid Build Coastguard Worker 
839*9880d681SAndroid Build Coastguard Worker     if (CondBr && CondConst && TryToUnfoldSelect(CondCmp, BB))
840*9880d681SAndroid Build Coastguard Worker       return true;
841*9880d681SAndroid Build Coastguard Worker   }
842*9880d681SAndroid Build Coastguard Worker 
843*9880d681SAndroid Build Coastguard Worker   // Check for some cases that are worth simplifying.  Right now we want to look
844*9880d681SAndroid Build Coastguard Worker   // for loads that are used by a switch or by the condition for the branch.  If
845*9880d681SAndroid Build Coastguard Worker   // we see one, check to see if it's partially redundant.  If so, insert a PHI
846*9880d681SAndroid Build Coastguard Worker   // which can then be used to thread the values.
847*9880d681SAndroid Build Coastguard Worker   //
848*9880d681SAndroid Build Coastguard Worker   Value *SimplifyValue = CondInst;
849*9880d681SAndroid Build Coastguard Worker   if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
850*9880d681SAndroid Build Coastguard Worker     if (isa<Constant>(CondCmp->getOperand(1)))
851*9880d681SAndroid Build Coastguard Worker       SimplifyValue = CondCmp->getOperand(0);
852*9880d681SAndroid Build Coastguard Worker 
853*9880d681SAndroid Build Coastguard Worker   // TODO: There are other places where load PRE would be profitable, such as
854*9880d681SAndroid Build Coastguard Worker   // more complex comparisons.
855*9880d681SAndroid Build Coastguard Worker   if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
856*9880d681SAndroid Build Coastguard Worker     if (SimplifyPartiallyRedundantLoad(LI))
857*9880d681SAndroid Build Coastguard Worker       return true;
858*9880d681SAndroid Build Coastguard Worker 
859*9880d681SAndroid Build Coastguard Worker 
860*9880d681SAndroid Build Coastguard Worker   // Handle a variety of cases where we are branching on something derived from
861*9880d681SAndroid Build Coastguard Worker   // a PHI node in the current block.  If we can prove that any predecessors
862*9880d681SAndroid Build Coastguard Worker   // compute a predictable value based on a PHI node, thread those predecessors.
863*9880d681SAndroid Build Coastguard Worker   //
864*9880d681SAndroid Build Coastguard Worker   if (ProcessThreadableEdges(CondInst, BB, Preference, Terminator))
865*9880d681SAndroid Build Coastguard Worker     return true;
866*9880d681SAndroid Build Coastguard Worker 
867*9880d681SAndroid Build Coastguard Worker   // If this is an otherwise-unfoldable branch on a phi node in the current
868*9880d681SAndroid Build Coastguard Worker   // block, see if we can simplify.
869*9880d681SAndroid Build Coastguard Worker   if (PHINode *PN = dyn_cast<PHINode>(CondInst))
870*9880d681SAndroid Build Coastguard Worker     if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
871*9880d681SAndroid Build Coastguard Worker       return ProcessBranchOnPHI(PN);
872*9880d681SAndroid Build Coastguard Worker 
873*9880d681SAndroid Build Coastguard Worker 
874*9880d681SAndroid Build Coastguard Worker   // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
875*9880d681SAndroid Build Coastguard Worker   if (CondInst->getOpcode() == Instruction::Xor &&
876*9880d681SAndroid Build Coastguard Worker       CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
877*9880d681SAndroid Build Coastguard Worker     return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst));
878*9880d681SAndroid Build Coastguard Worker 
879*9880d681SAndroid Build Coastguard Worker   // Search for a stronger dominating condition that can be used to simplify a
880*9880d681SAndroid Build Coastguard Worker   // conditional branch leaving BB.
881*9880d681SAndroid Build Coastguard Worker   if (ProcessImpliedCondition(BB))
882*9880d681SAndroid Build Coastguard Worker     return true;
883*9880d681SAndroid Build Coastguard Worker 
884*9880d681SAndroid Build Coastguard Worker   return false;
885*9880d681SAndroid Build Coastguard Worker }
886*9880d681SAndroid Build Coastguard Worker 
ProcessImpliedCondition(BasicBlock * BB)887*9880d681SAndroid Build Coastguard Worker bool JumpThreadingPass::ProcessImpliedCondition(BasicBlock *BB) {
888*9880d681SAndroid Build Coastguard Worker   auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
889*9880d681SAndroid Build Coastguard Worker   if (!BI || !BI->isConditional())
890*9880d681SAndroid Build Coastguard Worker     return false;
891*9880d681SAndroid Build Coastguard Worker 
892*9880d681SAndroid Build Coastguard Worker   Value *Cond = BI->getCondition();
893*9880d681SAndroid Build Coastguard Worker   BasicBlock *CurrentBB = BB;
894*9880d681SAndroid Build Coastguard Worker   BasicBlock *CurrentPred = BB->getSinglePredecessor();
895*9880d681SAndroid Build Coastguard Worker   unsigned Iter = 0;
896*9880d681SAndroid Build Coastguard Worker 
897*9880d681SAndroid Build Coastguard Worker   auto &DL = BB->getModule()->getDataLayout();
898*9880d681SAndroid Build Coastguard Worker 
899*9880d681SAndroid Build Coastguard Worker   while (CurrentPred && Iter++ < ImplicationSearchThreshold) {
900*9880d681SAndroid Build Coastguard Worker     auto *PBI = dyn_cast<BranchInst>(CurrentPred->getTerminator());
901*9880d681SAndroid Build Coastguard Worker     if (!PBI || !PBI->isConditional())
902*9880d681SAndroid Build Coastguard Worker       return false;
903*9880d681SAndroid Build Coastguard Worker     if (PBI->getSuccessor(0) != CurrentBB && PBI->getSuccessor(1) != CurrentBB)
904*9880d681SAndroid Build Coastguard Worker       return false;
905*9880d681SAndroid Build Coastguard Worker 
906*9880d681SAndroid Build Coastguard Worker     bool FalseDest = PBI->getSuccessor(1) == CurrentBB;
907*9880d681SAndroid Build Coastguard Worker     Optional<bool> Implication =
908*9880d681SAndroid Build Coastguard Worker       isImpliedCondition(PBI->getCondition(), Cond, DL, FalseDest);
909*9880d681SAndroid Build Coastguard Worker     if (Implication) {
910*9880d681SAndroid Build Coastguard Worker       BI->getSuccessor(*Implication ? 1 : 0)->removePredecessor(BB);
911*9880d681SAndroid Build Coastguard Worker       BranchInst::Create(BI->getSuccessor(*Implication ? 0 : 1), BI);
912*9880d681SAndroid Build Coastguard Worker       BI->eraseFromParent();
913*9880d681SAndroid Build Coastguard Worker       return true;
914*9880d681SAndroid Build Coastguard Worker     }
915*9880d681SAndroid Build Coastguard Worker     CurrentBB = CurrentPred;
916*9880d681SAndroid Build Coastguard Worker     CurrentPred = CurrentBB->getSinglePredecessor();
917*9880d681SAndroid Build Coastguard Worker   }
918*9880d681SAndroid Build Coastguard Worker 
919*9880d681SAndroid Build Coastguard Worker   return false;
920*9880d681SAndroid Build Coastguard Worker }
921*9880d681SAndroid Build Coastguard Worker 
922*9880d681SAndroid Build Coastguard Worker /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
923*9880d681SAndroid Build Coastguard Worker /// load instruction, eliminate it by replacing it with a PHI node.  This is an
924*9880d681SAndroid Build Coastguard Worker /// important optimization that encourages jump threading, and needs to be run
925*9880d681SAndroid Build Coastguard Worker /// interlaced with other jump threading tasks.
SimplifyPartiallyRedundantLoad(LoadInst * LI)926*9880d681SAndroid Build Coastguard Worker bool JumpThreadingPass::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
927*9880d681SAndroid Build Coastguard Worker   // Don't hack volatile and ordered loads.
928*9880d681SAndroid Build Coastguard Worker   if (!LI->isUnordered()) return false;
929*9880d681SAndroid Build Coastguard Worker 
930*9880d681SAndroid Build Coastguard Worker   // If the load is defined in a block with exactly one predecessor, it can't be
931*9880d681SAndroid Build Coastguard Worker   // partially redundant.
932*9880d681SAndroid Build Coastguard Worker   BasicBlock *LoadBB = LI->getParent();
933*9880d681SAndroid Build Coastguard Worker   if (LoadBB->getSinglePredecessor())
934*9880d681SAndroid Build Coastguard Worker     return false;
935*9880d681SAndroid Build Coastguard Worker 
936*9880d681SAndroid Build Coastguard Worker   // If the load is defined in an EH pad, it can't be partially redundant,
937*9880d681SAndroid Build Coastguard Worker   // because the edges between the invoke and the EH pad cannot have other
938*9880d681SAndroid Build Coastguard Worker   // instructions between them.
939*9880d681SAndroid Build Coastguard Worker   if (LoadBB->isEHPad())
940*9880d681SAndroid Build Coastguard Worker     return false;
941*9880d681SAndroid Build Coastguard Worker 
942*9880d681SAndroid Build Coastguard Worker   Value *LoadedPtr = LI->getOperand(0);
943*9880d681SAndroid Build Coastguard Worker 
944*9880d681SAndroid Build Coastguard Worker   // If the loaded operand is defined in the LoadBB, it can't be available.
945*9880d681SAndroid Build Coastguard Worker   // TODO: Could do simple PHI translation, that would be fun :)
946*9880d681SAndroid Build Coastguard Worker   if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
947*9880d681SAndroid Build Coastguard Worker     if (PtrOp->getParent() == LoadBB)
948*9880d681SAndroid Build Coastguard Worker       return false;
949*9880d681SAndroid Build Coastguard Worker 
950*9880d681SAndroid Build Coastguard Worker   // Scan a few instructions up from the load, to see if it is obviously live at
951*9880d681SAndroid Build Coastguard Worker   // the entry to its block.
952*9880d681SAndroid Build Coastguard Worker   BasicBlock::iterator BBIt(LI);
953*9880d681SAndroid Build Coastguard Worker 
954*9880d681SAndroid Build Coastguard Worker   if (Value *AvailableVal =
955*9880d681SAndroid Build Coastguard Worker         FindAvailableLoadedValue(LI, LoadBB, BBIt, DefMaxInstsToScan)) {
956*9880d681SAndroid Build Coastguard Worker     // If the value of the load is locally available within the block, just use
957*9880d681SAndroid Build Coastguard Worker     // it.  This frequently occurs for reg2mem'd allocas.
958*9880d681SAndroid Build Coastguard Worker 
959*9880d681SAndroid Build Coastguard Worker     // If the returned value is the load itself, replace with an undef. This can
960*9880d681SAndroid Build Coastguard Worker     // only happen in dead loops.
961*9880d681SAndroid Build Coastguard Worker     if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
962*9880d681SAndroid Build Coastguard Worker     if (AvailableVal->getType() != LI->getType())
963*9880d681SAndroid Build Coastguard Worker       AvailableVal =
964*9880d681SAndroid Build Coastguard Worker           CastInst::CreateBitOrPointerCast(AvailableVal, LI->getType(), "", LI);
965*9880d681SAndroid Build Coastguard Worker     LI->replaceAllUsesWith(AvailableVal);
966*9880d681SAndroid Build Coastguard Worker     LI->eraseFromParent();
967*9880d681SAndroid Build Coastguard Worker     return true;
968*9880d681SAndroid Build Coastguard Worker   }
969*9880d681SAndroid Build Coastguard Worker 
970*9880d681SAndroid Build Coastguard Worker   // Otherwise, if we scanned the whole block and got to the top of the block,
971*9880d681SAndroid Build Coastguard Worker   // we know the block is locally transparent to the load.  If not, something
972*9880d681SAndroid Build Coastguard Worker   // might clobber its value.
973*9880d681SAndroid Build Coastguard Worker   if (BBIt != LoadBB->begin())
974*9880d681SAndroid Build Coastguard Worker     return false;
975*9880d681SAndroid Build Coastguard Worker 
976*9880d681SAndroid Build Coastguard Worker   // If all of the loads and stores that feed the value have the same AA tags,
977*9880d681SAndroid Build Coastguard Worker   // then we can propagate them onto any newly inserted loads.
978*9880d681SAndroid Build Coastguard Worker   AAMDNodes AATags;
979*9880d681SAndroid Build Coastguard Worker   LI->getAAMetadata(AATags);
980*9880d681SAndroid Build Coastguard Worker 
981*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<BasicBlock*, 8> PredsScanned;
982*9880d681SAndroid Build Coastguard Worker   typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
983*9880d681SAndroid Build Coastguard Worker   AvailablePredsTy AvailablePreds;
984*9880d681SAndroid Build Coastguard Worker   BasicBlock *OneUnavailablePred = nullptr;
985*9880d681SAndroid Build Coastguard Worker 
986*9880d681SAndroid Build Coastguard Worker   // If we got here, the loaded value is transparent through to the start of the
987*9880d681SAndroid Build Coastguard Worker   // block.  Check to see if it is available in any of the predecessor blocks.
988*9880d681SAndroid Build Coastguard Worker   for (BasicBlock *PredBB : predecessors(LoadBB)) {
989*9880d681SAndroid Build Coastguard Worker     // If we already scanned this predecessor, skip it.
990*9880d681SAndroid Build Coastguard Worker     if (!PredsScanned.insert(PredBB).second)
991*9880d681SAndroid Build Coastguard Worker       continue;
992*9880d681SAndroid Build Coastguard Worker 
993*9880d681SAndroid Build Coastguard Worker     // Scan the predecessor to see if the value is available in the pred.
994*9880d681SAndroid Build Coastguard Worker     BBIt = PredBB->end();
995*9880d681SAndroid Build Coastguard Worker     AAMDNodes ThisAATags;
996*9880d681SAndroid Build Coastguard Worker     Value *PredAvailable = FindAvailableLoadedValue(LI, PredBB, BBIt,
997*9880d681SAndroid Build Coastguard Worker                                                     DefMaxInstsToScan,
998*9880d681SAndroid Build Coastguard Worker                                                     nullptr, &ThisAATags);
999*9880d681SAndroid Build Coastguard Worker     if (!PredAvailable) {
1000*9880d681SAndroid Build Coastguard Worker       OneUnavailablePred = PredBB;
1001*9880d681SAndroid Build Coastguard Worker       continue;
1002*9880d681SAndroid Build Coastguard Worker     }
1003*9880d681SAndroid Build Coastguard Worker 
1004*9880d681SAndroid Build Coastguard Worker     // If AA tags disagree or are not present, forget about them.
1005*9880d681SAndroid Build Coastguard Worker     if (AATags != ThisAATags) AATags = AAMDNodes();
1006*9880d681SAndroid Build Coastguard Worker 
1007*9880d681SAndroid Build Coastguard Worker     // If so, this load is partially redundant.  Remember this info so that we
1008*9880d681SAndroid Build Coastguard Worker     // can create a PHI node.
1009*9880d681SAndroid Build Coastguard Worker     AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
1010*9880d681SAndroid Build Coastguard Worker   }
1011*9880d681SAndroid Build Coastguard Worker 
1012*9880d681SAndroid Build Coastguard Worker   // If the loaded value isn't available in any predecessor, it isn't partially
1013*9880d681SAndroid Build Coastguard Worker   // redundant.
1014*9880d681SAndroid Build Coastguard Worker   if (AvailablePreds.empty()) return false;
1015*9880d681SAndroid Build Coastguard Worker 
1016*9880d681SAndroid Build Coastguard Worker   // Okay, the loaded value is available in at least one (and maybe all!)
1017*9880d681SAndroid Build Coastguard Worker   // predecessors.  If the value is unavailable in more than one unique
1018*9880d681SAndroid Build Coastguard Worker   // predecessor, we want to insert a merge block for those common predecessors.
1019*9880d681SAndroid Build Coastguard Worker   // This ensures that we only have to insert one reload, thus not increasing
1020*9880d681SAndroid Build Coastguard Worker   // code size.
1021*9880d681SAndroid Build Coastguard Worker   BasicBlock *UnavailablePred = nullptr;
1022*9880d681SAndroid Build Coastguard Worker 
1023*9880d681SAndroid Build Coastguard Worker   // If there is exactly one predecessor where the value is unavailable, the
1024*9880d681SAndroid Build Coastguard Worker   // already computed 'OneUnavailablePred' block is it.  If it ends in an
1025*9880d681SAndroid Build Coastguard Worker   // unconditional branch, we know that it isn't a critical edge.
1026*9880d681SAndroid Build Coastguard Worker   if (PredsScanned.size() == AvailablePreds.size()+1 &&
1027*9880d681SAndroid Build Coastguard Worker       OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
1028*9880d681SAndroid Build Coastguard Worker     UnavailablePred = OneUnavailablePred;
1029*9880d681SAndroid Build Coastguard Worker   } else if (PredsScanned.size() != AvailablePreds.size()) {
1030*9880d681SAndroid Build Coastguard Worker     // Otherwise, we had multiple unavailable predecessors or we had a critical
1031*9880d681SAndroid Build Coastguard Worker     // edge from the one.
1032*9880d681SAndroid Build Coastguard Worker     SmallVector<BasicBlock*, 8> PredsToSplit;
1033*9880d681SAndroid Build Coastguard Worker     SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
1034*9880d681SAndroid Build Coastguard Worker 
1035*9880d681SAndroid Build Coastguard Worker     for (const auto &AvailablePred : AvailablePreds)
1036*9880d681SAndroid Build Coastguard Worker       AvailablePredSet.insert(AvailablePred.first);
1037*9880d681SAndroid Build Coastguard Worker 
1038*9880d681SAndroid Build Coastguard Worker     // Add all the unavailable predecessors to the PredsToSplit list.
1039*9880d681SAndroid Build Coastguard Worker     for (BasicBlock *P : predecessors(LoadBB)) {
1040*9880d681SAndroid Build Coastguard Worker       // If the predecessor is an indirect goto, we can't split the edge.
1041*9880d681SAndroid Build Coastguard Worker       if (isa<IndirectBrInst>(P->getTerminator()))
1042*9880d681SAndroid Build Coastguard Worker         return false;
1043*9880d681SAndroid Build Coastguard Worker 
1044*9880d681SAndroid Build Coastguard Worker       if (!AvailablePredSet.count(P))
1045*9880d681SAndroid Build Coastguard Worker         PredsToSplit.push_back(P);
1046*9880d681SAndroid Build Coastguard Worker     }
1047*9880d681SAndroid Build Coastguard Worker 
1048*9880d681SAndroid Build Coastguard Worker     // Split them out to their own block.
1049*9880d681SAndroid Build Coastguard Worker     UnavailablePred = SplitBlockPreds(LoadBB, PredsToSplit, "thread-pre-split");
1050*9880d681SAndroid Build Coastguard Worker   }
1051*9880d681SAndroid Build Coastguard Worker 
1052*9880d681SAndroid Build Coastguard Worker   // If the value isn't available in all predecessors, then there will be
1053*9880d681SAndroid Build Coastguard Worker   // exactly one where it isn't available.  Insert a load on that edge and add
1054*9880d681SAndroid Build Coastguard Worker   // it to the AvailablePreds list.
1055*9880d681SAndroid Build Coastguard Worker   if (UnavailablePred) {
1056*9880d681SAndroid Build Coastguard Worker     assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
1057*9880d681SAndroid Build Coastguard Worker            "Can't handle critical edge here!");
1058*9880d681SAndroid Build Coastguard Worker     LoadInst *NewVal =
1059*9880d681SAndroid Build Coastguard Worker         new LoadInst(LoadedPtr, LI->getName() + ".pr", false,
1060*9880d681SAndroid Build Coastguard Worker                      LI->getAlignment(), LI->getOrdering(), LI->getSynchScope(),
1061*9880d681SAndroid Build Coastguard Worker                      UnavailablePred->getTerminator());
1062*9880d681SAndroid Build Coastguard Worker     NewVal->setDebugLoc(LI->getDebugLoc());
1063*9880d681SAndroid Build Coastguard Worker     if (AATags)
1064*9880d681SAndroid Build Coastguard Worker       NewVal->setAAMetadata(AATags);
1065*9880d681SAndroid Build Coastguard Worker 
1066*9880d681SAndroid Build Coastguard Worker     AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
1067*9880d681SAndroid Build Coastguard Worker   }
1068*9880d681SAndroid Build Coastguard Worker 
1069*9880d681SAndroid Build Coastguard Worker   // Now we know that each predecessor of this block has a value in
1070*9880d681SAndroid Build Coastguard Worker   // AvailablePreds, sort them for efficient access as we're walking the preds.
1071*9880d681SAndroid Build Coastguard Worker   array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
1072*9880d681SAndroid Build Coastguard Worker 
1073*9880d681SAndroid Build Coastguard Worker   // Create a PHI node at the start of the block for the PRE'd load value.
1074*9880d681SAndroid Build Coastguard Worker   pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
1075*9880d681SAndroid Build Coastguard Worker   PHINode *PN = PHINode::Create(LI->getType(), std::distance(PB, PE), "",
1076*9880d681SAndroid Build Coastguard Worker                                 &LoadBB->front());
1077*9880d681SAndroid Build Coastguard Worker   PN->takeName(LI);
1078*9880d681SAndroid Build Coastguard Worker   PN->setDebugLoc(LI->getDebugLoc());
1079*9880d681SAndroid Build Coastguard Worker 
1080*9880d681SAndroid Build Coastguard Worker   // Insert new entries into the PHI for each predecessor.  A single block may
1081*9880d681SAndroid Build Coastguard Worker   // have multiple entries here.
1082*9880d681SAndroid Build Coastguard Worker   for (pred_iterator PI = PB; PI != PE; ++PI) {
1083*9880d681SAndroid Build Coastguard Worker     BasicBlock *P = *PI;
1084*9880d681SAndroid Build Coastguard Worker     AvailablePredsTy::iterator I =
1085*9880d681SAndroid Build Coastguard Worker       std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
1086*9880d681SAndroid Build Coastguard Worker                        std::make_pair(P, (Value*)nullptr));
1087*9880d681SAndroid Build Coastguard Worker 
1088*9880d681SAndroid Build Coastguard Worker     assert(I != AvailablePreds.end() && I->first == P &&
1089*9880d681SAndroid Build Coastguard Worker            "Didn't find entry for predecessor!");
1090*9880d681SAndroid Build Coastguard Worker 
1091*9880d681SAndroid Build Coastguard Worker     // If we have an available predecessor but it requires casting, insert the
1092*9880d681SAndroid Build Coastguard Worker     // cast in the predecessor and use the cast. Note that we have to update the
1093*9880d681SAndroid Build Coastguard Worker     // AvailablePreds vector as we go so that all of the PHI entries for this
1094*9880d681SAndroid Build Coastguard Worker     // predecessor use the same bitcast.
1095*9880d681SAndroid Build Coastguard Worker     Value *&PredV = I->second;
1096*9880d681SAndroid Build Coastguard Worker     if (PredV->getType() != LI->getType())
1097*9880d681SAndroid Build Coastguard Worker       PredV = CastInst::CreateBitOrPointerCast(PredV, LI->getType(), "",
1098*9880d681SAndroid Build Coastguard Worker                                                P->getTerminator());
1099*9880d681SAndroid Build Coastguard Worker 
1100*9880d681SAndroid Build Coastguard Worker     PN->addIncoming(PredV, I->first);
1101*9880d681SAndroid Build Coastguard Worker   }
1102*9880d681SAndroid Build Coastguard Worker 
1103*9880d681SAndroid Build Coastguard Worker   LI->replaceAllUsesWith(PN);
1104*9880d681SAndroid Build Coastguard Worker   LI->eraseFromParent();
1105*9880d681SAndroid Build Coastguard Worker 
1106*9880d681SAndroid Build Coastguard Worker   return true;
1107*9880d681SAndroid Build Coastguard Worker }
1108*9880d681SAndroid Build Coastguard Worker 
1109*9880d681SAndroid Build Coastguard Worker /// FindMostPopularDest - The specified list contains multiple possible
1110*9880d681SAndroid Build Coastguard Worker /// threadable destinations.  Pick the one that occurs the most frequently in
1111*9880d681SAndroid Build Coastguard Worker /// the list.
1112*9880d681SAndroid Build Coastguard Worker static BasicBlock *
FindMostPopularDest(BasicBlock * BB,const SmallVectorImpl<std::pair<BasicBlock *,BasicBlock * >> & PredToDestList)1113*9880d681SAndroid Build Coastguard Worker FindMostPopularDest(BasicBlock *BB,
1114*9880d681SAndroid Build Coastguard Worker                     const SmallVectorImpl<std::pair<BasicBlock*,
1115*9880d681SAndroid Build Coastguard Worker                                   BasicBlock*> > &PredToDestList) {
1116*9880d681SAndroid Build Coastguard Worker   assert(!PredToDestList.empty());
1117*9880d681SAndroid Build Coastguard Worker 
1118*9880d681SAndroid Build Coastguard Worker   // Determine popularity.  If there are multiple possible destinations, we
1119*9880d681SAndroid Build Coastguard Worker   // explicitly choose to ignore 'undef' destinations.  We prefer to thread
1120*9880d681SAndroid Build Coastguard Worker   // blocks with known and real destinations to threading undef.  We'll handle
1121*9880d681SAndroid Build Coastguard Worker   // them later if interesting.
1122*9880d681SAndroid Build Coastguard Worker   DenseMap<BasicBlock*, unsigned> DestPopularity;
1123*9880d681SAndroid Build Coastguard Worker   for (const auto &PredToDest : PredToDestList)
1124*9880d681SAndroid Build Coastguard Worker     if (PredToDest.second)
1125*9880d681SAndroid Build Coastguard Worker       DestPopularity[PredToDest.second]++;
1126*9880d681SAndroid Build Coastguard Worker 
1127*9880d681SAndroid Build Coastguard Worker   // Find the most popular dest.
1128*9880d681SAndroid Build Coastguard Worker   DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
1129*9880d681SAndroid Build Coastguard Worker   BasicBlock *MostPopularDest = DPI->first;
1130*9880d681SAndroid Build Coastguard Worker   unsigned Popularity = DPI->second;
1131*9880d681SAndroid Build Coastguard Worker   SmallVector<BasicBlock*, 4> SamePopularity;
1132*9880d681SAndroid Build Coastguard Worker 
1133*9880d681SAndroid Build Coastguard Worker   for (++DPI; DPI != DestPopularity.end(); ++DPI) {
1134*9880d681SAndroid Build Coastguard Worker     // If the popularity of this entry isn't higher than the popularity we've
1135*9880d681SAndroid Build Coastguard Worker     // seen so far, ignore it.
1136*9880d681SAndroid Build Coastguard Worker     if (DPI->second < Popularity)
1137*9880d681SAndroid Build Coastguard Worker       ; // ignore.
1138*9880d681SAndroid Build Coastguard Worker     else if (DPI->second == Popularity) {
1139*9880d681SAndroid Build Coastguard Worker       // If it is the same as what we've seen so far, keep track of it.
1140*9880d681SAndroid Build Coastguard Worker       SamePopularity.push_back(DPI->first);
1141*9880d681SAndroid Build Coastguard Worker     } else {
1142*9880d681SAndroid Build Coastguard Worker       // If it is more popular, remember it.
1143*9880d681SAndroid Build Coastguard Worker       SamePopularity.clear();
1144*9880d681SAndroid Build Coastguard Worker       MostPopularDest = DPI->first;
1145*9880d681SAndroid Build Coastguard Worker       Popularity = DPI->second;
1146*9880d681SAndroid Build Coastguard Worker     }
1147*9880d681SAndroid Build Coastguard Worker   }
1148*9880d681SAndroid Build Coastguard Worker 
1149*9880d681SAndroid Build Coastguard Worker   // Okay, now we know the most popular destination.  If there is more than one
1150*9880d681SAndroid Build Coastguard Worker   // destination, we need to determine one.  This is arbitrary, but we need
1151*9880d681SAndroid Build Coastguard Worker   // to make a deterministic decision.  Pick the first one that appears in the
1152*9880d681SAndroid Build Coastguard Worker   // successor list.
1153*9880d681SAndroid Build Coastguard Worker   if (!SamePopularity.empty()) {
1154*9880d681SAndroid Build Coastguard Worker     SamePopularity.push_back(MostPopularDest);
1155*9880d681SAndroid Build Coastguard Worker     TerminatorInst *TI = BB->getTerminator();
1156*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0; ; ++i) {
1157*9880d681SAndroid Build Coastguard Worker       assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
1158*9880d681SAndroid Build Coastguard Worker 
1159*9880d681SAndroid Build Coastguard Worker       if (std::find(SamePopularity.begin(), SamePopularity.end(),
1160*9880d681SAndroid Build Coastguard Worker                     TI->getSuccessor(i)) == SamePopularity.end())
1161*9880d681SAndroid Build Coastguard Worker         continue;
1162*9880d681SAndroid Build Coastguard Worker 
1163*9880d681SAndroid Build Coastguard Worker       MostPopularDest = TI->getSuccessor(i);
1164*9880d681SAndroid Build Coastguard Worker       break;
1165*9880d681SAndroid Build Coastguard Worker     }
1166*9880d681SAndroid Build Coastguard Worker   }
1167*9880d681SAndroid Build Coastguard Worker 
1168*9880d681SAndroid Build Coastguard Worker   // Okay, we have finally picked the most popular destination.
1169*9880d681SAndroid Build Coastguard Worker   return MostPopularDest;
1170*9880d681SAndroid Build Coastguard Worker }
1171*9880d681SAndroid Build Coastguard Worker 
ProcessThreadableEdges(Value * Cond,BasicBlock * BB,ConstantPreference Preference,Instruction * CxtI)1172*9880d681SAndroid Build Coastguard Worker bool JumpThreadingPass::ProcessThreadableEdges(Value *Cond, BasicBlock *BB,
1173*9880d681SAndroid Build Coastguard Worker                                                ConstantPreference Preference,
1174*9880d681SAndroid Build Coastguard Worker                                                Instruction *CxtI) {
1175*9880d681SAndroid Build Coastguard Worker   // If threading this would thread across a loop header, don't even try to
1176*9880d681SAndroid Build Coastguard Worker   // thread the edge.
1177*9880d681SAndroid Build Coastguard Worker   if (LoopHeaders.count(BB))
1178*9880d681SAndroid Build Coastguard Worker     return false;
1179*9880d681SAndroid Build Coastguard Worker 
1180*9880d681SAndroid Build Coastguard Worker   PredValueInfoTy PredValues;
1181*9880d681SAndroid Build Coastguard Worker   if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues, Preference, CxtI))
1182*9880d681SAndroid Build Coastguard Worker     return false;
1183*9880d681SAndroid Build Coastguard Worker 
1184*9880d681SAndroid Build Coastguard Worker   assert(!PredValues.empty() &&
1185*9880d681SAndroid Build Coastguard Worker          "ComputeValueKnownInPredecessors returned true with no values");
1186*9880d681SAndroid Build Coastguard Worker 
1187*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "IN BB: " << *BB;
1188*9880d681SAndroid Build Coastguard Worker         for (const auto &PredValue : PredValues) {
1189*9880d681SAndroid Build Coastguard Worker           dbgs() << "  BB '" << BB->getName() << "': FOUND condition = "
1190*9880d681SAndroid Build Coastguard Worker             << *PredValue.first
1191*9880d681SAndroid Build Coastguard Worker             << " for pred '" << PredValue.second->getName() << "'.\n";
1192*9880d681SAndroid Build Coastguard Worker         });
1193*9880d681SAndroid Build Coastguard Worker 
1194*9880d681SAndroid Build Coastguard Worker   // Decide what we want to thread through.  Convert our list of known values to
1195*9880d681SAndroid Build Coastguard Worker   // a list of known destinations for each pred.  This also discards duplicate
1196*9880d681SAndroid Build Coastguard Worker   // predecessors and keeps track of the undefined inputs (which are represented
1197*9880d681SAndroid Build Coastguard Worker   // as a null dest in the PredToDestList).
1198*9880d681SAndroid Build Coastguard Worker   SmallPtrSet<BasicBlock*, 16> SeenPreds;
1199*9880d681SAndroid Build Coastguard Worker   SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
1200*9880d681SAndroid Build Coastguard Worker 
1201*9880d681SAndroid Build Coastguard Worker   BasicBlock *OnlyDest = nullptr;
1202*9880d681SAndroid Build Coastguard Worker   BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
1203*9880d681SAndroid Build Coastguard Worker 
1204*9880d681SAndroid Build Coastguard Worker   for (const auto &PredValue : PredValues) {
1205*9880d681SAndroid Build Coastguard Worker     BasicBlock *Pred = PredValue.second;
1206*9880d681SAndroid Build Coastguard Worker     if (!SeenPreds.insert(Pred).second)
1207*9880d681SAndroid Build Coastguard Worker       continue;  // Duplicate predecessor entry.
1208*9880d681SAndroid Build Coastguard Worker 
1209*9880d681SAndroid Build Coastguard Worker     // If the predecessor ends with an indirect goto, we can't change its
1210*9880d681SAndroid Build Coastguard Worker     // destination.
1211*9880d681SAndroid Build Coastguard Worker     if (isa<IndirectBrInst>(Pred->getTerminator()))
1212*9880d681SAndroid Build Coastguard Worker       continue;
1213*9880d681SAndroid Build Coastguard Worker 
1214*9880d681SAndroid Build Coastguard Worker     Constant *Val = PredValue.first;
1215*9880d681SAndroid Build Coastguard Worker 
1216*9880d681SAndroid Build Coastguard Worker     BasicBlock *DestBB;
1217*9880d681SAndroid Build Coastguard Worker     if (isa<UndefValue>(Val))
1218*9880d681SAndroid Build Coastguard Worker       DestBB = nullptr;
1219*9880d681SAndroid Build Coastguard Worker     else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
1220*9880d681SAndroid Build Coastguard Worker       DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
1221*9880d681SAndroid Build Coastguard Worker     else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1222*9880d681SAndroid Build Coastguard Worker       DestBB = SI->findCaseValue(cast<ConstantInt>(Val)).getCaseSuccessor();
1223*9880d681SAndroid Build Coastguard Worker     } else {
1224*9880d681SAndroid Build Coastguard Worker       assert(isa<IndirectBrInst>(BB->getTerminator())
1225*9880d681SAndroid Build Coastguard Worker               && "Unexpected terminator");
1226*9880d681SAndroid Build Coastguard Worker       DestBB = cast<BlockAddress>(Val)->getBasicBlock();
1227*9880d681SAndroid Build Coastguard Worker     }
1228*9880d681SAndroid Build Coastguard Worker 
1229*9880d681SAndroid Build Coastguard Worker     // If we have exactly one destination, remember it for efficiency below.
1230*9880d681SAndroid Build Coastguard Worker     if (PredToDestList.empty())
1231*9880d681SAndroid Build Coastguard Worker       OnlyDest = DestBB;
1232*9880d681SAndroid Build Coastguard Worker     else if (OnlyDest != DestBB)
1233*9880d681SAndroid Build Coastguard Worker       OnlyDest = MultipleDestSentinel;
1234*9880d681SAndroid Build Coastguard Worker 
1235*9880d681SAndroid Build Coastguard Worker     PredToDestList.push_back(std::make_pair(Pred, DestBB));
1236*9880d681SAndroid Build Coastguard Worker   }
1237*9880d681SAndroid Build Coastguard Worker 
1238*9880d681SAndroid Build Coastguard Worker   // If all edges were unthreadable, we fail.
1239*9880d681SAndroid Build Coastguard Worker   if (PredToDestList.empty())
1240*9880d681SAndroid Build Coastguard Worker     return false;
1241*9880d681SAndroid Build Coastguard Worker 
1242*9880d681SAndroid Build Coastguard Worker   // Determine which is the most common successor.  If we have many inputs and
1243*9880d681SAndroid Build Coastguard Worker   // this block is a switch, we want to start by threading the batch that goes
1244*9880d681SAndroid Build Coastguard Worker   // to the most popular destination first.  If we only know about one
1245*9880d681SAndroid Build Coastguard Worker   // threadable destination (the common case) we can avoid this.
1246*9880d681SAndroid Build Coastguard Worker   BasicBlock *MostPopularDest = OnlyDest;
1247*9880d681SAndroid Build Coastguard Worker 
1248*9880d681SAndroid Build Coastguard Worker   if (MostPopularDest == MultipleDestSentinel)
1249*9880d681SAndroid Build Coastguard Worker     MostPopularDest = FindMostPopularDest(BB, PredToDestList);
1250*9880d681SAndroid Build Coastguard Worker 
1251*9880d681SAndroid Build Coastguard Worker   // Now that we know what the most popular destination is, factor all
1252*9880d681SAndroid Build Coastguard Worker   // predecessors that will jump to it into a single predecessor.
1253*9880d681SAndroid Build Coastguard Worker   SmallVector<BasicBlock*, 16> PredsToFactor;
1254*9880d681SAndroid Build Coastguard Worker   for (const auto &PredToDest : PredToDestList)
1255*9880d681SAndroid Build Coastguard Worker     if (PredToDest.second == MostPopularDest) {
1256*9880d681SAndroid Build Coastguard Worker       BasicBlock *Pred = PredToDest.first;
1257*9880d681SAndroid Build Coastguard Worker 
1258*9880d681SAndroid Build Coastguard Worker       // This predecessor may be a switch or something else that has multiple
1259*9880d681SAndroid Build Coastguard Worker       // edges to the block.  Factor each of these edges by listing them
1260*9880d681SAndroid Build Coastguard Worker       // according to # occurrences in PredsToFactor.
1261*9880d681SAndroid Build Coastguard Worker       for (BasicBlock *Succ : successors(Pred))
1262*9880d681SAndroid Build Coastguard Worker         if (Succ == BB)
1263*9880d681SAndroid Build Coastguard Worker           PredsToFactor.push_back(Pred);
1264*9880d681SAndroid Build Coastguard Worker     }
1265*9880d681SAndroid Build Coastguard Worker 
1266*9880d681SAndroid Build Coastguard Worker   // If the threadable edges are branching on an undefined value, we get to pick
1267*9880d681SAndroid Build Coastguard Worker   // the destination that these predecessors should get to.
1268*9880d681SAndroid Build Coastguard Worker   if (!MostPopularDest)
1269*9880d681SAndroid Build Coastguard Worker     MostPopularDest = BB->getTerminator()->
1270*9880d681SAndroid Build Coastguard Worker                             getSuccessor(GetBestDestForJumpOnUndef(BB));
1271*9880d681SAndroid Build Coastguard Worker 
1272*9880d681SAndroid Build Coastguard Worker   // Ok, try to thread it!
1273*9880d681SAndroid Build Coastguard Worker   return ThreadEdge(BB, PredsToFactor, MostPopularDest);
1274*9880d681SAndroid Build Coastguard Worker }
1275*9880d681SAndroid Build Coastguard Worker 
1276*9880d681SAndroid Build Coastguard Worker /// ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on
1277*9880d681SAndroid Build Coastguard Worker /// a PHI node in the current block.  See if there are any simplifications we
1278*9880d681SAndroid Build Coastguard Worker /// can do based on inputs to the phi node.
1279*9880d681SAndroid Build Coastguard Worker ///
ProcessBranchOnPHI(PHINode * PN)1280*9880d681SAndroid Build Coastguard Worker bool JumpThreadingPass::ProcessBranchOnPHI(PHINode *PN) {
1281*9880d681SAndroid Build Coastguard Worker   BasicBlock *BB = PN->getParent();
1282*9880d681SAndroid Build Coastguard Worker 
1283*9880d681SAndroid Build Coastguard Worker   // TODO: We could make use of this to do it once for blocks with common PHI
1284*9880d681SAndroid Build Coastguard Worker   // values.
1285*9880d681SAndroid Build Coastguard Worker   SmallVector<BasicBlock*, 1> PredBBs;
1286*9880d681SAndroid Build Coastguard Worker   PredBBs.resize(1);
1287*9880d681SAndroid Build Coastguard Worker 
1288*9880d681SAndroid Build Coastguard Worker   // If any of the predecessor blocks end in an unconditional branch, we can
1289*9880d681SAndroid Build Coastguard Worker   // *duplicate* the conditional branch into that block in order to further
1290*9880d681SAndroid Build Coastguard Worker   // encourage jump threading and to eliminate cases where we have branch on a
1291*9880d681SAndroid Build Coastguard Worker   // phi of an icmp (branch on icmp is much better).
1292*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1293*9880d681SAndroid Build Coastguard Worker     BasicBlock *PredBB = PN->getIncomingBlock(i);
1294*9880d681SAndroid Build Coastguard Worker     if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
1295*9880d681SAndroid Build Coastguard Worker       if (PredBr->isUnconditional()) {
1296*9880d681SAndroid Build Coastguard Worker         PredBBs[0] = PredBB;
1297*9880d681SAndroid Build Coastguard Worker         // Try to duplicate BB into PredBB.
1298*9880d681SAndroid Build Coastguard Worker         if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs))
1299*9880d681SAndroid Build Coastguard Worker           return true;
1300*9880d681SAndroid Build Coastguard Worker       }
1301*9880d681SAndroid Build Coastguard Worker   }
1302*9880d681SAndroid Build Coastguard Worker 
1303*9880d681SAndroid Build Coastguard Worker   return false;
1304*9880d681SAndroid Build Coastguard Worker }
1305*9880d681SAndroid Build Coastguard Worker 
1306*9880d681SAndroid Build Coastguard Worker /// ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on
1307*9880d681SAndroid Build Coastguard Worker /// a xor instruction in the current block.  See if there are any
1308*9880d681SAndroid Build Coastguard Worker /// simplifications we can do based on inputs to the xor.
1309*9880d681SAndroid Build Coastguard Worker ///
ProcessBranchOnXOR(BinaryOperator * BO)1310*9880d681SAndroid Build Coastguard Worker bool JumpThreadingPass::ProcessBranchOnXOR(BinaryOperator *BO) {
1311*9880d681SAndroid Build Coastguard Worker   BasicBlock *BB = BO->getParent();
1312*9880d681SAndroid Build Coastguard Worker 
1313*9880d681SAndroid Build Coastguard Worker   // If either the LHS or RHS of the xor is a constant, don't do this
1314*9880d681SAndroid Build Coastguard Worker   // optimization.
1315*9880d681SAndroid Build Coastguard Worker   if (isa<ConstantInt>(BO->getOperand(0)) ||
1316*9880d681SAndroid Build Coastguard Worker       isa<ConstantInt>(BO->getOperand(1)))
1317*9880d681SAndroid Build Coastguard Worker     return false;
1318*9880d681SAndroid Build Coastguard Worker 
1319*9880d681SAndroid Build Coastguard Worker   // If the first instruction in BB isn't a phi, we won't be able to infer
1320*9880d681SAndroid Build Coastguard Worker   // anything special about any particular predecessor.
1321*9880d681SAndroid Build Coastguard Worker   if (!isa<PHINode>(BB->front()))
1322*9880d681SAndroid Build Coastguard Worker     return false;
1323*9880d681SAndroid Build Coastguard Worker 
1324*9880d681SAndroid Build Coastguard Worker   // If we have a xor as the branch input to this block, and we know that the
1325*9880d681SAndroid Build Coastguard Worker   // LHS or RHS of the xor in any predecessor is true/false, then we can clone
1326*9880d681SAndroid Build Coastguard Worker   // the condition into the predecessor and fix that value to true, saving some
1327*9880d681SAndroid Build Coastguard Worker   // logical ops on that path and encouraging other paths to simplify.
1328*9880d681SAndroid Build Coastguard Worker   //
1329*9880d681SAndroid Build Coastguard Worker   // This copies something like this:
1330*9880d681SAndroid Build Coastguard Worker   //
1331*9880d681SAndroid Build Coastguard Worker   //  BB:
1332*9880d681SAndroid Build Coastguard Worker   //    %X = phi i1 [1],  [%X']
1333*9880d681SAndroid Build Coastguard Worker   //    %Y = icmp eq i32 %A, %B
1334*9880d681SAndroid Build Coastguard Worker   //    %Z = xor i1 %X, %Y
1335*9880d681SAndroid Build Coastguard Worker   //    br i1 %Z, ...
1336*9880d681SAndroid Build Coastguard Worker   //
1337*9880d681SAndroid Build Coastguard Worker   // Into:
1338*9880d681SAndroid Build Coastguard Worker   //  BB':
1339*9880d681SAndroid Build Coastguard Worker   //    %Y = icmp ne i32 %A, %B
1340*9880d681SAndroid Build Coastguard Worker   //    br i1 %Y, ...
1341*9880d681SAndroid Build Coastguard Worker 
1342*9880d681SAndroid Build Coastguard Worker   PredValueInfoTy XorOpValues;
1343*9880d681SAndroid Build Coastguard Worker   bool isLHS = true;
1344*9880d681SAndroid Build Coastguard Worker   if (!ComputeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues,
1345*9880d681SAndroid Build Coastguard Worker                                        WantInteger, BO)) {
1346*9880d681SAndroid Build Coastguard Worker     assert(XorOpValues.empty());
1347*9880d681SAndroid Build Coastguard Worker     if (!ComputeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues,
1348*9880d681SAndroid Build Coastguard Worker                                          WantInteger, BO))
1349*9880d681SAndroid Build Coastguard Worker       return false;
1350*9880d681SAndroid Build Coastguard Worker     isLHS = false;
1351*9880d681SAndroid Build Coastguard Worker   }
1352*9880d681SAndroid Build Coastguard Worker 
1353*9880d681SAndroid Build Coastguard Worker   assert(!XorOpValues.empty() &&
1354*9880d681SAndroid Build Coastguard Worker          "ComputeValueKnownInPredecessors returned true with no values");
1355*9880d681SAndroid Build Coastguard Worker 
1356*9880d681SAndroid Build Coastguard Worker   // Scan the information to see which is most popular: true or false.  The
1357*9880d681SAndroid Build Coastguard Worker   // predecessors can be of the set true, false, or undef.
1358*9880d681SAndroid Build Coastguard Worker   unsigned NumTrue = 0, NumFalse = 0;
1359*9880d681SAndroid Build Coastguard Worker   for (const auto &XorOpValue : XorOpValues) {
1360*9880d681SAndroid Build Coastguard Worker     if (isa<UndefValue>(XorOpValue.first))
1361*9880d681SAndroid Build Coastguard Worker       // Ignore undefs for the count.
1362*9880d681SAndroid Build Coastguard Worker       continue;
1363*9880d681SAndroid Build Coastguard Worker     if (cast<ConstantInt>(XorOpValue.first)->isZero())
1364*9880d681SAndroid Build Coastguard Worker       ++NumFalse;
1365*9880d681SAndroid Build Coastguard Worker     else
1366*9880d681SAndroid Build Coastguard Worker       ++NumTrue;
1367*9880d681SAndroid Build Coastguard Worker   }
1368*9880d681SAndroid Build Coastguard Worker 
1369*9880d681SAndroid Build Coastguard Worker   // Determine which value to split on, true, false, or undef if neither.
1370*9880d681SAndroid Build Coastguard Worker   ConstantInt *SplitVal = nullptr;
1371*9880d681SAndroid Build Coastguard Worker   if (NumTrue > NumFalse)
1372*9880d681SAndroid Build Coastguard Worker     SplitVal = ConstantInt::getTrue(BB->getContext());
1373*9880d681SAndroid Build Coastguard Worker   else if (NumTrue != 0 || NumFalse != 0)
1374*9880d681SAndroid Build Coastguard Worker     SplitVal = ConstantInt::getFalse(BB->getContext());
1375*9880d681SAndroid Build Coastguard Worker 
1376*9880d681SAndroid Build Coastguard Worker   // Collect all of the blocks that this can be folded into so that we can
1377*9880d681SAndroid Build Coastguard Worker   // factor this once and clone it once.
1378*9880d681SAndroid Build Coastguard Worker   SmallVector<BasicBlock*, 8> BlocksToFoldInto;
1379*9880d681SAndroid Build Coastguard Worker   for (const auto &XorOpValue : XorOpValues) {
1380*9880d681SAndroid Build Coastguard Worker     if (XorOpValue.first != SplitVal && !isa<UndefValue>(XorOpValue.first))
1381*9880d681SAndroid Build Coastguard Worker       continue;
1382*9880d681SAndroid Build Coastguard Worker 
1383*9880d681SAndroid Build Coastguard Worker     BlocksToFoldInto.push_back(XorOpValue.second);
1384*9880d681SAndroid Build Coastguard Worker   }
1385*9880d681SAndroid Build Coastguard Worker 
1386*9880d681SAndroid Build Coastguard Worker   // If we inferred a value for all of the predecessors, then duplication won't
1387*9880d681SAndroid Build Coastguard Worker   // help us.  However, we can just replace the LHS or RHS with the constant.
1388*9880d681SAndroid Build Coastguard Worker   if (BlocksToFoldInto.size() ==
1389*9880d681SAndroid Build Coastguard Worker       cast<PHINode>(BB->front()).getNumIncomingValues()) {
1390*9880d681SAndroid Build Coastguard Worker     if (!SplitVal) {
1391*9880d681SAndroid Build Coastguard Worker       // If all preds provide undef, just nuke the xor, because it is undef too.
1392*9880d681SAndroid Build Coastguard Worker       BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
1393*9880d681SAndroid Build Coastguard Worker       BO->eraseFromParent();
1394*9880d681SAndroid Build Coastguard Worker     } else if (SplitVal->isZero()) {
1395*9880d681SAndroid Build Coastguard Worker       // If all preds provide 0, replace the xor with the other input.
1396*9880d681SAndroid Build Coastguard Worker       BO->replaceAllUsesWith(BO->getOperand(isLHS));
1397*9880d681SAndroid Build Coastguard Worker       BO->eraseFromParent();
1398*9880d681SAndroid Build Coastguard Worker     } else {
1399*9880d681SAndroid Build Coastguard Worker       // If all preds provide 1, set the computed value to 1.
1400*9880d681SAndroid Build Coastguard Worker       BO->setOperand(!isLHS, SplitVal);
1401*9880d681SAndroid Build Coastguard Worker     }
1402*9880d681SAndroid Build Coastguard Worker 
1403*9880d681SAndroid Build Coastguard Worker     return true;
1404*9880d681SAndroid Build Coastguard Worker   }
1405*9880d681SAndroid Build Coastguard Worker 
1406*9880d681SAndroid Build Coastguard Worker   // Try to duplicate BB into PredBB.
1407*9880d681SAndroid Build Coastguard Worker   return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
1408*9880d681SAndroid Build Coastguard Worker }
1409*9880d681SAndroid Build Coastguard Worker 
1410*9880d681SAndroid Build Coastguard Worker 
1411*9880d681SAndroid Build Coastguard Worker /// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
1412*9880d681SAndroid Build Coastguard Worker /// predecessor to the PHIBB block.  If it has PHI nodes, add entries for
1413*9880d681SAndroid Build Coastguard Worker /// NewPred using the entries from OldPred (suitably mapped).
AddPHINodeEntriesForMappedBlock(BasicBlock * PHIBB,BasicBlock * OldPred,BasicBlock * NewPred,DenseMap<Instruction *,Value * > & ValueMap)1414*9880d681SAndroid Build Coastguard Worker static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
1415*9880d681SAndroid Build Coastguard Worker                                             BasicBlock *OldPred,
1416*9880d681SAndroid Build Coastguard Worker                                             BasicBlock *NewPred,
1417*9880d681SAndroid Build Coastguard Worker                                      DenseMap<Instruction*, Value*> &ValueMap) {
1418*9880d681SAndroid Build Coastguard Worker   for (BasicBlock::iterator PNI = PHIBB->begin();
1419*9880d681SAndroid Build Coastguard Worker        PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
1420*9880d681SAndroid Build Coastguard Worker     // Ok, we have a PHI node.  Figure out what the incoming value was for the
1421*9880d681SAndroid Build Coastguard Worker     // DestBlock.
1422*9880d681SAndroid Build Coastguard Worker     Value *IV = PN->getIncomingValueForBlock(OldPred);
1423*9880d681SAndroid Build Coastguard Worker 
1424*9880d681SAndroid Build Coastguard Worker     // Remap the value if necessary.
1425*9880d681SAndroid Build Coastguard Worker     if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
1426*9880d681SAndroid Build Coastguard Worker       DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
1427*9880d681SAndroid Build Coastguard Worker       if (I != ValueMap.end())
1428*9880d681SAndroid Build Coastguard Worker         IV = I->second;
1429*9880d681SAndroid Build Coastguard Worker     }
1430*9880d681SAndroid Build Coastguard Worker 
1431*9880d681SAndroid Build Coastguard Worker     PN->addIncoming(IV, NewPred);
1432*9880d681SAndroid Build Coastguard Worker   }
1433*9880d681SAndroid Build Coastguard Worker }
1434*9880d681SAndroid Build Coastguard Worker 
1435*9880d681SAndroid Build Coastguard Worker /// ThreadEdge - We have decided that it is safe and profitable to factor the
1436*9880d681SAndroid Build Coastguard Worker /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
1437*9880d681SAndroid Build Coastguard Worker /// across BB.  Transform the IR to reflect this change.
ThreadEdge(BasicBlock * BB,const SmallVectorImpl<BasicBlock * > & PredBBs,BasicBlock * SuccBB)1438*9880d681SAndroid Build Coastguard Worker bool JumpThreadingPass::ThreadEdge(BasicBlock *BB,
1439*9880d681SAndroid Build Coastguard Worker                                    const SmallVectorImpl<BasicBlock *> &PredBBs,
1440*9880d681SAndroid Build Coastguard Worker                                    BasicBlock *SuccBB) {
1441*9880d681SAndroid Build Coastguard Worker   // If threading to the same block as we come from, we would infinite loop.
1442*9880d681SAndroid Build Coastguard Worker   if (SuccBB == BB) {
1443*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "  Not threading across BB '" << BB->getName()
1444*9880d681SAndroid Build Coastguard Worker           << "' - would thread to self!\n");
1445*9880d681SAndroid Build Coastguard Worker     return false;
1446*9880d681SAndroid Build Coastguard Worker   }
1447*9880d681SAndroid Build Coastguard Worker 
1448*9880d681SAndroid Build Coastguard Worker   // If threading this would thread across a loop header, don't thread the edge.
1449*9880d681SAndroid Build Coastguard Worker   // See the comments above FindLoopHeaders for justifications and caveats.
1450*9880d681SAndroid Build Coastguard Worker   if (LoopHeaders.count(BB)) {
1451*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "  Not threading across loop header BB '" << BB->getName()
1452*9880d681SAndroid Build Coastguard Worker           << "' to dest BB '" << SuccBB->getName()
1453*9880d681SAndroid Build Coastguard Worker           << "' - it might create an irreducible loop!\n");
1454*9880d681SAndroid Build Coastguard Worker     return false;
1455*9880d681SAndroid Build Coastguard Worker   }
1456*9880d681SAndroid Build Coastguard Worker 
1457*9880d681SAndroid Build Coastguard Worker   unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB, BBDupThreshold);
1458*9880d681SAndroid Build Coastguard Worker   if (JumpThreadCost > BBDupThreshold) {
1459*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "  Not threading BB '" << BB->getName()
1460*9880d681SAndroid Build Coastguard Worker           << "' - Cost is too high: " << JumpThreadCost << "\n");
1461*9880d681SAndroid Build Coastguard Worker     return false;
1462*9880d681SAndroid Build Coastguard Worker   }
1463*9880d681SAndroid Build Coastguard Worker 
1464*9880d681SAndroid Build Coastguard Worker   // And finally, do it!  Start by factoring the predecessors if needed.
1465*9880d681SAndroid Build Coastguard Worker   BasicBlock *PredBB;
1466*9880d681SAndroid Build Coastguard Worker   if (PredBBs.size() == 1)
1467*9880d681SAndroid Build Coastguard Worker     PredBB = PredBBs[0];
1468*9880d681SAndroid Build Coastguard Worker   else {
1469*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "  Factoring out " << PredBBs.size()
1470*9880d681SAndroid Build Coastguard Worker           << " common predecessors.\n");
1471*9880d681SAndroid Build Coastguard Worker     PredBB = SplitBlockPreds(BB, PredBBs, ".thr_comm");
1472*9880d681SAndroid Build Coastguard Worker   }
1473*9880d681SAndroid Build Coastguard Worker 
1474*9880d681SAndroid Build Coastguard Worker   // And finally, do it!
1475*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "  Threading edge from '" << PredBB->getName() << "' to '"
1476*9880d681SAndroid Build Coastguard Worker         << SuccBB->getName() << "' with cost: " << JumpThreadCost
1477*9880d681SAndroid Build Coastguard Worker         << ", across block:\n    "
1478*9880d681SAndroid Build Coastguard Worker         << *BB << "\n");
1479*9880d681SAndroid Build Coastguard Worker 
1480*9880d681SAndroid Build Coastguard Worker   LVI->threadEdge(PredBB, BB, SuccBB);
1481*9880d681SAndroid Build Coastguard Worker 
1482*9880d681SAndroid Build Coastguard Worker   // We are going to have to map operands from the original BB block to the new
1483*9880d681SAndroid Build Coastguard Worker   // copy of the block 'NewBB'.  If there are PHI nodes in BB, evaluate them to
1484*9880d681SAndroid Build Coastguard Worker   // account for entry from PredBB.
1485*9880d681SAndroid Build Coastguard Worker   DenseMap<Instruction*, Value*> ValueMapping;
1486*9880d681SAndroid Build Coastguard Worker 
1487*9880d681SAndroid Build Coastguard Worker   BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
1488*9880d681SAndroid Build Coastguard Worker                                          BB->getName()+".thread",
1489*9880d681SAndroid Build Coastguard Worker                                          BB->getParent(), BB);
1490*9880d681SAndroid Build Coastguard Worker   NewBB->moveAfter(PredBB);
1491*9880d681SAndroid Build Coastguard Worker 
1492*9880d681SAndroid Build Coastguard Worker   // Set the block frequency of NewBB.
1493*9880d681SAndroid Build Coastguard Worker   if (HasProfileData) {
1494*9880d681SAndroid Build Coastguard Worker     auto NewBBFreq =
1495*9880d681SAndroid Build Coastguard Worker         BFI->getBlockFreq(PredBB) * BPI->getEdgeProbability(PredBB, BB);
1496*9880d681SAndroid Build Coastguard Worker     BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
1497*9880d681SAndroid Build Coastguard Worker   }
1498*9880d681SAndroid Build Coastguard Worker 
1499*9880d681SAndroid Build Coastguard Worker   BasicBlock::iterator BI = BB->begin();
1500*9880d681SAndroid Build Coastguard Worker   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1501*9880d681SAndroid Build Coastguard Worker     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1502*9880d681SAndroid Build Coastguard Worker 
1503*9880d681SAndroid Build Coastguard Worker   // Clone the non-phi instructions of BB into NewBB, keeping track of the
1504*9880d681SAndroid Build Coastguard Worker   // mapping and using it to remap operands in the cloned instructions.
1505*9880d681SAndroid Build Coastguard Worker   for (; !isa<TerminatorInst>(BI); ++BI) {
1506*9880d681SAndroid Build Coastguard Worker     Instruction *New = BI->clone();
1507*9880d681SAndroid Build Coastguard Worker     New->setName(BI->getName());
1508*9880d681SAndroid Build Coastguard Worker     NewBB->getInstList().push_back(New);
1509*9880d681SAndroid Build Coastguard Worker     ValueMapping[&*BI] = New;
1510*9880d681SAndroid Build Coastguard Worker 
1511*9880d681SAndroid Build Coastguard Worker     // Remap operands to patch up intra-block references.
1512*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1513*9880d681SAndroid Build Coastguard Worker       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1514*9880d681SAndroid Build Coastguard Worker         DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1515*9880d681SAndroid Build Coastguard Worker         if (I != ValueMapping.end())
1516*9880d681SAndroid Build Coastguard Worker           New->setOperand(i, I->second);
1517*9880d681SAndroid Build Coastguard Worker       }
1518*9880d681SAndroid Build Coastguard Worker   }
1519*9880d681SAndroid Build Coastguard Worker 
1520*9880d681SAndroid Build Coastguard Worker   // We didn't copy the terminator from BB over to NewBB, because there is now
1521*9880d681SAndroid Build Coastguard Worker   // an unconditional jump to SuccBB.  Insert the unconditional jump.
1522*9880d681SAndroid Build Coastguard Worker   BranchInst *NewBI = BranchInst::Create(SuccBB, NewBB);
1523*9880d681SAndroid Build Coastguard Worker   NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc());
1524*9880d681SAndroid Build Coastguard Worker 
1525*9880d681SAndroid Build Coastguard Worker   // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
1526*9880d681SAndroid Build Coastguard Worker   // PHI nodes for NewBB now.
1527*9880d681SAndroid Build Coastguard Worker   AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
1528*9880d681SAndroid Build Coastguard Worker 
1529*9880d681SAndroid Build Coastguard Worker   // If there were values defined in BB that are used outside the block, then we
1530*9880d681SAndroid Build Coastguard Worker   // now have to update all uses of the value to use either the original value,
1531*9880d681SAndroid Build Coastguard Worker   // the cloned value, or some PHI derived value.  This can require arbitrary
1532*9880d681SAndroid Build Coastguard Worker   // PHI insertion, of which we are prepared to do, clean these up now.
1533*9880d681SAndroid Build Coastguard Worker   SSAUpdater SSAUpdate;
1534*9880d681SAndroid Build Coastguard Worker   SmallVector<Use*, 16> UsesToRename;
1535*9880d681SAndroid Build Coastguard Worker   for (Instruction &I : *BB) {
1536*9880d681SAndroid Build Coastguard Worker     // Scan all uses of this instruction to see if it is used outside of its
1537*9880d681SAndroid Build Coastguard Worker     // block, and if so, record them in UsesToRename.
1538*9880d681SAndroid Build Coastguard Worker     for (Use &U : I.uses()) {
1539*9880d681SAndroid Build Coastguard Worker       Instruction *User = cast<Instruction>(U.getUser());
1540*9880d681SAndroid Build Coastguard Worker       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1541*9880d681SAndroid Build Coastguard Worker         if (UserPN->getIncomingBlock(U) == BB)
1542*9880d681SAndroid Build Coastguard Worker           continue;
1543*9880d681SAndroid Build Coastguard Worker       } else if (User->getParent() == BB)
1544*9880d681SAndroid Build Coastguard Worker         continue;
1545*9880d681SAndroid Build Coastguard Worker 
1546*9880d681SAndroid Build Coastguard Worker       UsesToRename.push_back(&U);
1547*9880d681SAndroid Build Coastguard Worker     }
1548*9880d681SAndroid Build Coastguard Worker 
1549*9880d681SAndroid Build Coastguard Worker     // If there are no uses outside the block, we're done with this instruction.
1550*9880d681SAndroid Build Coastguard Worker     if (UsesToRename.empty())
1551*9880d681SAndroid Build Coastguard Worker       continue;
1552*9880d681SAndroid Build Coastguard Worker 
1553*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n");
1554*9880d681SAndroid Build Coastguard Worker 
1555*9880d681SAndroid Build Coastguard Worker     // We found a use of I outside of BB.  Rename all uses of I that are outside
1556*9880d681SAndroid Build Coastguard Worker     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
1557*9880d681SAndroid Build Coastguard Worker     // with the two values we know.
1558*9880d681SAndroid Build Coastguard Worker     SSAUpdate.Initialize(I.getType(), I.getName());
1559*9880d681SAndroid Build Coastguard Worker     SSAUpdate.AddAvailableValue(BB, &I);
1560*9880d681SAndroid Build Coastguard Worker     SSAUpdate.AddAvailableValue(NewBB, ValueMapping[&I]);
1561*9880d681SAndroid Build Coastguard Worker 
1562*9880d681SAndroid Build Coastguard Worker     while (!UsesToRename.empty())
1563*9880d681SAndroid Build Coastguard Worker       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1564*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "\n");
1565*9880d681SAndroid Build Coastguard Worker   }
1566*9880d681SAndroid Build Coastguard Worker 
1567*9880d681SAndroid Build Coastguard Worker 
1568*9880d681SAndroid Build Coastguard Worker   // Ok, NewBB is good to go.  Update the terminator of PredBB to jump to
1569*9880d681SAndroid Build Coastguard Worker   // NewBB instead of BB.  This eliminates predecessors from BB, which requires
1570*9880d681SAndroid Build Coastguard Worker   // us to simplify any PHI nodes in BB.
1571*9880d681SAndroid Build Coastguard Worker   TerminatorInst *PredTerm = PredBB->getTerminator();
1572*9880d681SAndroid Build Coastguard Worker   for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
1573*9880d681SAndroid Build Coastguard Worker     if (PredTerm->getSuccessor(i) == BB) {
1574*9880d681SAndroid Build Coastguard Worker       BB->removePredecessor(PredBB, true);
1575*9880d681SAndroid Build Coastguard Worker       PredTerm->setSuccessor(i, NewBB);
1576*9880d681SAndroid Build Coastguard Worker     }
1577*9880d681SAndroid Build Coastguard Worker 
1578*9880d681SAndroid Build Coastguard Worker   // At this point, the IR is fully up to date and consistent.  Do a quick scan
1579*9880d681SAndroid Build Coastguard Worker   // over the new instructions and zap any that are constants or dead.  This
1580*9880d681SAndroid Build Coastguard Worker   // frequently happens because of phi translation.
1581*9880d681SAndroid Build Coastguard Worker   SimplifyInstructionsInBlock(NewBB, TLI);
1582*9880d681SAndroid Build Coastguard Worker 
1583*9880d681SAndroid Build Coastguard Worker   // Update the edge weight from BB to SuccBB, which should be less than before.
1584*9880d681SAndroid Build Coastguard Worker   UpdateBlockFreqAndEdgeWeight(PredBB, BB, NewBB, SuccBB);
1585*9880d681SAndroid Build Coastguard Worker 
1586*9880d681SAndroid Build Coastguard Worker   // Threaded an edge!
1587*9880d681SAndroid Build Coastguard Worker   ++NumThreads;
1588*9880d681SAndroid Build Coastguard Worker   return true;
1589*9880d681SAndroid Build Coastguard Worker }
1590*9880d681SAndroid Build Coastguard Worker 
1591*9880d681SAndroid Build Coastguard Worker /// Create a new basic block that will be the predecessor of BB and successor of
1592*9880d681SAndroid Build Coastguard Worker /// all blocks in Preds. When profile data is availble, update the frequency of
1593*9880d681SAndroid Build Coastguard Worker /// this new block.
SplitBlockPreds(BasicBlock * BB,ArrayRef<BasicBlock * > Preds,const char * Suffix)1594*9880d681SAndroid Build Coastguard Worker BasicBlock *JumpThreadingPass::SplitBlockPreds(BasicBlock *BB,
1595*9880d681SAndroid Build Coastguard Worker                                                ArrayRef<BasicBlock *> Preds,
1596*9880d681SAndroid Build Coastguard Worker                                                const char *Suffix) {
1597*9880d681SAndroid Build Coastguard Worker   // Collect the frequencies of all predecessors of BB, which will be used to
1598*9880d681SAndroid Build Coastguard Worker   // update the edge weight on BB->SuccBB.
1599*9880d681SAndroid Build Coastguard Worker   BlockFrequency PredBBFreq(0);
1600*9880d681SAndroid Build Coastguard Worker   if (HasProfileData)
1601*9880d681SAndroid Build Coastguard Worker     for (auto Pred : Preds)
1602*9880d681SAndroid Build Coastguard Worker       PredBBFreq += BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, BB);
1603*9880d681SAndroid Build Coastguard Worker 
1604*9880d681SAndroid Build Coastguard Worker   BasicBlock *PredBB = SplitBlockPredecessors(BB, Preds, Suffix);
1605*9880d681SAndroid Build Coastguard Worker 
1606*9880d681SAndroid Build Coastguard Worker   // Set the block frequency of the newly created PredBB, which is the sum of
1607*9880d681SAndroid Build Coastguard Worker   // frequencies of Preds.
1608*9880d681SAndroid Build Coastguard Worker   if (HasProfileData)
1609*9880d681SAndroid Build Coastguard Worker     BFI->setBlockFreq(PredBB, PredBBFreq.getFrequency());
1610*9880d681SAndroid Build Coastguard Worker   return PredBB;
1611*9880d681SAndroid Build Coastguard Worker }
1612*9880d681SAndroid Build Coastguard Worker 
1613*9880d681SAndroid Build Coastguard Worker /// Update the block frequency of BB and branch weight and the metadata on the
1614*9880d681SAndroid Build Coastguard Worker /// edge BB->SuccBB. This is done by scaling the weight of BB->SuccBB by 1 -
1615*9880d681SAndroid Build Coastguard Worker /// Freq(PredBB->BB) / Freq(BB->SuccBB).
UpdateBlockFreqAndEdgeWeight(BasicBlock * PredBB,BasicBlock * BB,BasicBlock * NewBB,BasicBlock * SuccBB)1616*9880d681SAndroid Build Coastguard Worker void JumpThreadingPass::UpdateBlockFreqAndEdgeWeight(BasicBlock *PredBB,
1617*9880d681SAndroid Build Coastguard Worker                                                      BasicBlock *BB,
1618*9880d681SAndroid Build Coastguard Worker                                                      BasicBlock *NewBB,
1619*9880d681SAndroid Build Coastguard Worker                                                      BasicBlock *SuccBB) {
1620*9880d681SAndroid Build Coastguard Worker   if (!HasProfileData)
1621*9880d681SAndroid Build Coastguard Worker     return;
1622*9880d681SAndroid Build Coastguard Worker 
1623*9880d681SAndroid Build Coastguard Worker   assert(BFI && BPI && "BFI & BPI should have been created here");
1624*9880d681SAndroid Build Coastguard Worker 
1625*9880d681SAndroid Build Coastguard Worker   // As the edge from PredBB to BB is deleted, we have to update the block
1626*9880d681SAndroid Build Coastguard Worker   // frequency of BB.
1627*9880d681SAndroid Build Coastguard Worker   auto BBOrigFreq = BFI->getBlockFreq(BB);
1628*9880d681SAndroid Build Coastguard Worker   auto NewBBFreq = BFI->getBlockFreq(NewBB);
1629*9880d681SAndroid Build Coastguard Worker   auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(BB, SuccBB);
1630*9880d681SAndroid Build Coastguard Worker   auto BBNewFreq = BBOrigFreq - NewBBFreq;
1631*9880d681SAndroid Build Coastguard Worker   BFI->setBlockFreq(BB, BBNewFreq.getFrequency());
1632*9880d681SAndroid Build Coastguard Worker 
1633*9880d681SAndroid Build Coastguard Worker   // Collect updated outgoing edges' frequencies from BB and use them to update
1634*9880d681SAndroid Build Coastguard Worker   // edge probabilities.
1635*9880d681SAndroid Build Coastguard Worker   SmallVector<uint64_t, 4> BBSuccFreq;
1636*9880d681SAndroid Build Coastguard Worker   for (BasicBlock *Succ : successors(BB)) {
1637*9880d681SAndroid Build Coastguard Worker     auto SuccFreq = (Succ == SuccBB)
1638*9880d681SAndroid Build Coastguard Worker                         ? BB2SuccBBFreq - NewBBFreq
1639*9880d681SAndroid Build Coastguard Worker                         : BBOrigFreq * BPI->getEdgeProbability(BB, Succ);
1640*9880d681SAndroid Build Coastguard Worker     BBSuccFreq.push_back(SuccFreq.getFrequency());
1641*9880d681SAndroid Build Coastguard Worker   }
1642*9880d681SAndroid Build Coastguard Worker 
1643*9880d681SAndroid Build Coastguard Worker   uint64_t MaxBBSuccFreq =
1644*9880d681SAndroid Build Coastguard Worker       *std::max_element(BBSuccFreq.begin(), BBSuccFreq.end());
1645*9880d681SAndroid Build Coastguard Worker 
1646*9880d681SAndroid Build Coastguard Worker   SmallVector<BranchProbability, 4> BBSuccProbs;
1647*9880d681SAndroid Build Coastguard Worker   if (MaxBBSuccFreq == 0)
1648*9880d681SAndroid Build Coastguard Worker     BBSuccProbs.assign(BBSuccFreq.size(),
1649*9880d681SAndroid Build Coastguard Worker                        {1, static_cast<unsigned>(BBSuccFreq.size())});
1650*9880d681SAndroid Build Coastguard Worker   else {
1651*9880d681SAndroid Build Coastguard Worker     for (uint64_t Freq : BBSuccFreq)
1652*9880d681SAndroid Build Coastguard Worker       BBSuccProbs.push_back(
1653*9880d681SAndroid Build Coastguard Worker           BranchProbability::getBranchProbability(Freq, MaxBBSuccFreq));
1654*9880d681SAndroid Build Coastguard Worker     // Normalize edge probabilities so that they sum up to one.
1655*9880d681SAndroid Build Coastguard Worker     BranchProbability::normalizeProbabilities(BBSuccProbs.begin(),
1656*9880d681SAndroid Build Coastguard Worker                                               BBSuccProbs.end());
1657*9880d681SAndroid Build Coastguard Worker   }
1658*9880d681SAndroid Build Coastguard Worker 
1659*9880d681SAndroid Build Coastguard Worker   // Update edge probabilities in BPI.
1660*9880d681SAndroid Build Coastguard Worker   for (int I = 0, E = BBSuccProbs.size(); I < E; I++)
1661*9880d681SAndroid Build Coastguard Worker     BPI->setEdgeProbability(BB, I, BBSuccProbs[I]);
1662*9880d681SAndroid Build Coastguard Worker 
1663*9880d681SAndroid Build Coastguard Worker   if (BBSuccProbs.size() >= 2) {
1664*9880d681SAndroid Build Coastguard Worker     SmallVector<uint32_t, 4> Weights;
1665*9880d681SAndroid Build Coastguard Worker     for (auto Prob : BBSuccProbs)
1666*9880d681SAndroid Build Coastguard Worker       Weights.push_back(Prob.getNumerator());
1667*9880d681SAndroid Build Coastguard Worker 
1668*9880d681SAndroid Build Coastguard Worker     auto TI = BB->getTerminator();
1669*9880d681SAndroid Build Coastguard Worker     TI->setMetadata(
1670*9880d681SAndroid Build Coastguard Worker         LLVMContext::MD_prof,
1671*9880d681SAndroid Build Coastguard Worker         MDBuilder(TI->getParent()->getContext()).createBranchWeights(Weights));
1672*9880d681SAndroid Build Coastguard Worker   }
1673*9880d681SAndroid Build Coastguard Worker }
1674*9880d681SAndroid Build Coastguard Worker 
1675*9880d681SAndroid Build Coastguard Worker /// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
1676*9880d681SAndroid Build Coastguard Worker /// to BB which contains an i1 PHI node and a conditional branch on that PHI.
1677*9880d681SAndroid Build Coastguard Worker /// If we can duplicate the contents of BB up into PredBB do so now, this
1678*9880d681SAndroid Build Coastguard Worker /// improves the odds that the branch will be on an analyzable instruction like
1679*9880d681SAndroid Build Coastguard Worker /// a compare.
DuplicateCondBranchOnPHIIntoPred(BasicBlock * BB,const SmallVectorImpl<BasicBlock * > & PredBBs)1680*9880d681SAndroid Build Coastguard Worker bool JumpThreadingPass::DuplicateCondBranchOnPHIIntoPred(
1681*9880d681SAndroid Build Coastguard Worker     BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs) {
1682*9880d681SAndroid Build Coastguard Worker   assert(!PredBBs.empty() && "Can't handle an empty set");
1683*9880d681SAndroid Build Coastguard Worker 
1684*9880d681SAndroid Build Coastguard Worker   // If BB is a loop header, then duplicating this block outside the loop would
1685*9880d681SAndroid Build Coastguard Worker   // cause us to transform this into an irreducible loop, don't do this.
1686*9880d681SAndroid Build Coastguard Worker   // See the comments above FindLoopHeaders for justifications and caveats.
1687*9880d681SAndroid Build Coastguard Worker   if (LoopHeaders.count(BB)) {
1688*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "  Not duplicating loop header '" << BB->getName()
1689*9880d681SAndroid Build Coastguard Worker           << "' into predecessor block '" << PredBBs[0]->getName()
1690*9880d681SAndroid Build Coastguard Worker           << "' - it might create an irreducible loop!\n");
1691*9880d681SAndroid Build Coastguard Worker     return false;
1692*9880d681SAndroid Build Coastguard Worker   }
1693*9880d681SAndroid Build Coastguard Worker 
1694*9880d681SAndroid Build Coastguard Worker   unsigned DuplicationCost = getJumpThreadDuplicationCost(BB, BBDupThreshold);
1695*9880d681SAndroid Build Coastguard Worker   if (DuplicationCost > BBDupThreshold) {
1696*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "  Not duplicating BB '" << BB->getName()
1697*9880d681SAndroid Build Coastguard Worker           << "' - Cost is too high: " << DuplicationCost << "\n");
1698*9880d681SAndroid Build Coastguard Worker     return false;
1699*9880d681SAndroid Build Coastguard Worker   }
1700*9880d681SAndroid Build Coastguard Worker 
1701*9880d681SAndroid Build Coastguard Worker   // And finally, do it!  Start by factoring the predecessors if needed.
1702*9880d681SAndroid Build Coastguard Worker   BasicBlock *PredBB;
1703*9880d681SAndroid Build Coastguard Worker   if (PredBBs.size() == 1)
1704*9880d681SAndroid Build Coastguard Worker     PredBB = PredBBs[0];
1705*9880d681SAndroid Build Coastguard Worker   else {
1706*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "  Factoring out " << PredBBs.size()
1707*9880d681SAndroid Build Coastguard Worker           << " common predecessors.\n");
1708*9880d681SAndroid Build Coastguard Worker     PredBB = SplitBlockPreds(BB, PredBBs, ".thr_comm");
1709*9880d681SAndroid Build Coastguard Worker   }
1710*9880d681SAndroid Build Coastguard Worker 
1711*9880d681SAndroid Build Coastguard Worker   // Okay, we decided to do this!  Clone all the instructions in BB onto the end
1712*9880d681SAndroid Build Coastguard Worker   // of PredBB.
1713*9880d681SAndroid Build Coastguard Worker   DEBUG(dbgs() << "  Duplicating block '" << BB->getName() << "' into end of '"
1714*9880d681SAndroid Build Coastguard Worker         << PredBB->getName() << "' to eliminate branch on phi.  Cost: "
1715*9880d681SAndroid Build Coastguard Worker         << DuplicationCost << " block is:" << *BB << "\n");
1716*9880d681SAndroid Build Coastguard Worker 
1717*9880d681SAndroid Build Coastguard Worker   // Unless PredBB ends with an unconditional branch, split the edge so that we
1718*9880d681SAndroid Build Coastguard Worker   // can just clone the bits from BB into the end of the new PredBB.
1719*9880d681SAndroid Build Coastguard Worker   BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
1720*9880d681SAndroid Build Coastguard Worker 
1721*9880d681SAndroid Build Coastguard Worker   if (!OldPredBranch || !OldPredBranch->isUnconditional()) {
1722*9880d681SAndroid Build Coastguard Worker     PredBB = SplitEdge(PredBB, BB);
1723*9880d681SAndroid Build Coastguard Worker     OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
1724*9880d681SAndroid Build Coastguard Worker   }
1725*9880d681SAndroid Build Coastguard Worker 
1726*9880d681SAndroid Build Coastguard Worker   // We are going to have to map operands from the original BB block into the
1727*9880d681SAndroid Build Coastguard Worker   // PredBB block.  Evaluate PHI nodes in BB.
1728*9880d681SAndroid Build Coastguard Worker   DenseMap<Instruction*, Value*> ValueMapping;
1729*9880d681SAndroid Build Coastguard Worker 
1730*9880d681SAndroid Build Coastguard Worker   BasicBlock::iterator BI = BB->begin();
1731*9880d681SAndroid Build Coastguard Worker   for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
1732*9880d681SAndroid Build Coastguard Worker     ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
1733*9880d681SAndroid Build Coastguard Worker   // Clone the non-phi instructions of BB into PredBB, keeping track of the
1734*9880d681SAndroid Build Coastguard Worker   // mapping and using it to remap operands in the cloned instructions.
1735*9880d681SAndroid Build Coastguard Worker   for (; BI != BB->end(); ++BI) {
1736*9880d681SAndroid Build Coastguard Worker     Instruction *New = BI->clone();
1737*9880d681SAndroid Build Coastguard Worker 
1738*9880d681SAndroid Build Coastguard Worker     // Remap operands to patch up intra-block references.
1739*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
1740*9880d681SAndroid Build Coastguard Worker       if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
1741*9880d681SAndroid Build Coastguard Worker         DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
1742*9880d681SAndroid Build Coastguard Worker         if (I != ValueMapping.end())
1743*9880d681SAndroid Build Coastguard Worker           New->setOperand(i, I->second);
1744*9880d681SAndroid Build Coastguard Worker       }
1745*9880d681SAndroid Build Coastguard Worker 
1746*9880d681SAndroid Build Coastguard Worker     // If this instruction can be simplified after the operands are updated,
1747*9880d681SAndroid Build Coastguard Worker     // just use the simplified value instead.  This frequently happens due to
1748*9880d681SAndroid Build Coastguard Worker     // phi translation.
1749*9880d681SAndroid Build Coastguard Worker     if (Value *IV =
1750*9880d681SAndroid Build Coastguard Worker             SimplifyInstruction(New, BB->getModule()->getDataLayout())) {
1751*9880d681SAndroid Build Coastguard Worker       ValueMapping[&*BI] = IV;
1752*9880d681SAndroid Build Coastguard Worker       if (!New->mayHaveSideEffects()) {
1753*9880d681SAndroid Build Coastguard Worker         delete New;
1754*9880d681SAndroid Build Coastguard Worker         New = nullptr;
1755*9880d681SAndroid Build Coastguard Worker       }
1756*9880d681SAndroid Build Coastguard Worker     } else {
1757*9880d681SAndroid Build Coastguard Worker       ValueMapping[&*BI] = New;
1758*9880d681SAndroid Build Coastguard Worker     }
1759*9880d681SAndroid Build Coastguard Worker     if (New) {
1760*9880d681SAndroid Build Coastguard Worker       // Otherwise, insert the new instruction into the block.
1761*9880d681SAndroid Build Coastguard Worker       New->setName(BI->getName());
1762*9880d681SAndroid Build Coastguard Worker       PredBB->getInstList().insert(OldPredBranch->getIterator(), New);
1763*9880d681SAndroid Build Coastguard Worker     }
1764*9880d681SAndroid Build Coastguard Worker   }
1765*9880d681SAndroid Build Coastguard Worker 
1766*9880d681SAndroid Build Coastguard Worker   // Check to see if the targets of the branch had PHI nodes. If so, we need to
1767*9880d681SAndroid Build Coastguard Worker   // add entries to the PHI nodes for branch from PredBB now.
1768*9880d681SAndroid Build Coastguard Worker   BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
1769*9880d681SAndroid Build Coastguard Worker   AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
1770*9880d681SAndroid Build Coastguard Worker                                   ValueMapping);
1771*9880d681SAndroid Build Coastguard Worker   AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
1772*9880d681SAndroid Build Coastguard Worker                                   ValueMapping);
1773*9880d681SAndroid Build Coastguard Worker 
1774*9880d681SAndroid Build Coastguard Worker   // If there were values defined in BB that are used outside the block, then we
1775*9880d681SAndroid Build Coastguard Worker   // now have to update all uses of the value to use either the original value,
1776*9880d681SAndroid Build Coastguard Worker   // the cloned value, or some PHI derived value.  This can require arbitrary
1777*9880d681SAndroid Build Coastguard Worker   // PHI insertion, of which we are prepared to do, clean these up now.
1778*9880d681SAndroid Build Coastguard Worker   SSAUpdater SSAUpdate;
1779*9880d681SAndroid Build Coastguard Worker   SmallVector<Use*, 16> UsesToRename;
1780*9880d681SAndroid Build Coastguard Worker   for (Instruction &I : *BB) {
1781*9880d681SAndroid Build Coastguard Worker     // Scan all uses of this instruction to see if it is used outside of its
1782*9880d681SAndroid Build Coastguard Worker     // block, and if so, record them in UsesToRename.
1783*9880d681SAndroid Build Coastguard Worker     for (Use &U : I.uses()) {
1784*9880d681SAndroid Build Coastguard Worker       Instruction *User = cast<Instruction>(U.getUser());
1785*9880d681SAndroid Build Coastguard Worker       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1786*9880d681SAndroid Build Coastguard Worker         if (UserPN->getIncomingBlock(U) == BB)
1787*9880d681SAndroid Build Coastguard Worker           continue;
1788*9880d681SAndroid Build Coastguard Worker       } else if (User->getParent() == BB)
1789*9880d681SAndroid Build Coastguard Worker         continue;
1790*9880d681SAndroid Build Coastguard Worker 
1791*9880d681SAndroid Build Coastguard Worker       UsesToRename.push_back(&U);
1792*9880d681SAndroid Build Coastguard Worker     }
1793*9880d681SAndroid Build Coastguard Worker 
1794*9880d681SAndroid Build Coastguard Worker     // If there are no uses outside the block, we're done with this instruction.
1795*9880d681SAndroid Build Coastguard Worker     if (UsesToRename.empty())
1796*9880d681SAndroid Build Coastguard Worker       continue;
1797*9880d681SAndroid Build Coastguard Worker 
1798*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n");
1799*9880d681SAndroid Build Coastguard Worker 
1800*9880d681SAndroid Build Coastguard Worker     // We found a use of I outside of BB.  Rename all uses of I that are outside
1801*9880d681SAndroid Build Coastguard Worker     // its block to be uses of the appropriate PHI node etc.  See ValuesInBlocks
1802*9880d681SAndroid Build Coastguard Worker     // with the two values we know.
1803*9880d681SAndroid Build Coastguard Worker     SSAUpdate.Initialize(I.getType(), I.getName());
1804*9880d681SAndroid Build Coastguard Worker     SSAUpdate.AddAvailableValue(BB, &I);
1805*9880d681SAndroid Build Coastguard Worker     SSAUpdate.AddAvailableValue(PredBB, ValueMapping[&I]);
1806*9880d681SAndroid Build Coastguard Worker 
1807*9880d681SAndroid Build Coastguard Worker     while (!UsesToRename.empty())
1808*9880d681SAndroid Build Coastguard Worker       SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
1809*9880d681SAndroid Build Coastguard Worker     DEBUG(dbgs() << "\n");
1810*9880d681SAndroid Build Coastguard Worker   }
1811*9880d681SAndroid Build Coastguard Worker 
1812*9880d681SAndroid Build Coastguard Worker   // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
1813*9880d681SAndroid Build Coastguard Worker   // that we nuked.
1814*9880d681SAndroid Build Coastguard Worker   BB->removePredecessor(PredBB, true);
1815*9880d681SAndroid Build Coastguard Worker 
1816*9880d681SAndroid Build Coastguard Worker   // Remove the unconditional branch at the end of the PredBB block.
1817*9880d681SAndroid Build Coastguard Worker   OldPredBranch->eraseFromParent();
1818*9880d681SAndroid Build Coastguard Worker 
1819*9880d681SAndroid Build Coastguard Worker   ++NumDupes;
1820*9880d681SAndroid Build Coastguard Worker   return true;
1821*9880d681SAndroid Build Coastguard Worker }
1822*9880d681SAndroid Build Coastguard Worker 
1823*9880d681SAndroid Build Coastguard Worker /// TryToUnfoldSelect - Look for blocks of the form
1824*9880d681SAndroid Build Coastguard Worker /// bb1:
1825*9880d681SAndroid Build Coastguard Worker ///   %a = select
1826*9880d681SAndroid Build Coastguard Worker ///   br bb
1827*9880d681SAndroid Build Coastguard Worker ///
1828*9880d681SAndroid Build Coastguard Worker /// bb2:
1829*9880d681SAndroid Build Coastguard Worker ///   %p = phi [%a, %bb] ...
1830*9880d681SAndroid Build Coastguard Worker ///   %c = icmp %p
1831*9880d681SAndroid Build Coastguard Worker ///   br i1 %c
1832*9880d681SAndroid Build Coastguard Worker ///
1833*9880d681SAndroid Build Coastguard Worker /// And expand the select into a branch structure if one of its arms allows %c
1834*9880d681SAndroid Build Coastguard Worker /// to be folded. This later enables threading from bb1 over bb2.
TryToUnfoldSelect(CmpInst * CondCmp,BasicBlock * BB)1835*9880d681SAndroid Build Coastguard Worker bool JumpThreadingPass::TryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) {
1836*9880d681SAndroid Build Coastguard Worker   BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
1837*9880d681SAndroid Build Coastguard Worker   PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0));
1838*9880d681SAndroid Build Coastguard Worker   Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1));
1839*9880d681SAndroid Build Coastguard Worker 
1840*9880d681SAndroid Build Coastguard Worker   if (!CondBr || !CondBr->isConditional() || !CondLHS ||
1841*9880d681SAndroid Build Coastguard Worker       CondLHS->getParent() != BB)
1842*9880d681SAndroid Build Coastguard Worker     return false;
1843*9880d681SAndroid Build Coastguard Worker 
1844*9880d681SAndroid Build Coastguard Worker   for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) {
1845*9880d681SAndroid Build Coastguard Worker     BasicBlock *Pred = CondLHS->getIncomingBlock(I);
1846*9880d681SAndroid Build Coastguard Worker     SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I));
1847*9880d681SAndroid Build Coastguard Worker 
1848*9880d681SAndroid Build Coastguard Worker     // Look if one of the incoming values is a select in the corresponding
1849*9880d681SAndroid Build Coastguard Worker     // predecessor.
1850*9880d681SAndroid Build Coastguard Worker     if (!SI || SI->getParent() != Pred || !SI->hasOneUse())
1851*9880d681SAndroid Build Coastguard Worker       continue;
1852*9880d681SAndroid Build Coastguard Worker 
1853*9880d681SAndroid Build Coastguard Worker     BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
1854*9880d681SAndroid Build Coastguard Worker     if (!PredTerm || !PredTerm->isUnconditional())
1855*9880d681SAndroid Build Coastguard Worker       continue;
1856*9880d681SAndroid Build Coastguard Worker 
1857*9880d681SAndroid Build Coastguard Worker     // Now check if one of the select values would allow us to constant fold the
1858*9880d681SAndroid Build Coastguard Worker     // terminator in BB. We don't do the transform if both sides fold, those
1859*9880d681SAndroid Build Coastguard Worker     // cases will be threaded in any case.
1860*9880d681SAndroid Build Coastguard Worker     LazyValueInfo::Tristate LHSFolds =
1861*9880d681SAndroid Build Coastguard Worker         LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1),
1862*9880d681SAndroid Build Coastguard Worker                                 CondRHS, Pred, BB, CondCmp);
1863*9880d681SAndroid Build Coastguard Worker     LazyValueInfo::Tristate RHSFolds =
1864*9880d681SAndroid Build Coastguard Worker         LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2),
1865*9880d681SAndroid Build Coastguard Worker                                 CondRHS, Pred, BB, CondCmp);
1866*9880d681SAndroid Build Coastguard Worker     if ((LHSFolds != LazyValueInfo::Unknown ||
1867*9880d681SAndroid Build Coastguard Worker          RHSFolds != LazyValueInfo::Unknown) &&
1868*9880d681SAndroid Build Coastguard Worker         LHSFolds != RHSFolds) {
1869*9880d681SAndroid Build Coastguard Worker       // Expand the select.
1870*9880d681SAndroid Build Coastguard Worker       //
1871*9880d681SAndroid Build Coastguard Worker       // Pred --
1872*9880d681SAndroid Build Coastguard Worker       //  |    v
1873*9880d681SAndroid Build Coastguard Worker       //  |  NewBB
1874*9880d681SAndroid Build Coastguard Worker       //  |    |
1875*9880d681SAndroid Build Coastguard Worker       //  |-----
1876*9880d681SAndroid Build Coastguard Worker       //  v
1877*9880d681SAndroid Build Coastguard Worker       // BB
1878*9880d681SAndroid Build Coastguard Worker       BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold",
1879*9880d681SAndroid Build Coastguard Worker                                              BB->getParent(), BB);
1880*9880d681SAndroid Build Coastguard Worker       // Move the unconditional branch to NewBB.
1881*9880d681SAndroid Build Coastguard Worker       PredTerm->removeFromParent();
1882*9880d681SAndroid Build Coastguard Worker       NewBB->getInstList().insert(NewBB->end(), PredTerm);
1883*9880d681SAndroid Build Coastguard Worker       // Create a conditional branch and update PHI nodes.
1884*9880d681SAndroid Build Coastguard Worker       BranchInst::Create(NewBB, BB, SI->getCondition(), Pred);
1885*9880d681SAndroid Build Coastguard Worker       CondLHS->setIncomingValue(I, SI->getFalseValue());
1886*9880d681SAndroid Build Coastguard Worker       CondLHS->addIncoming(SI->getTrueValue(), NewBB);
1887*9880d681SAndroid Build Coastguard Worker       // The select is now dead.
1888*9880d681SAndroid Build Coastguard Worker       SI->eraseFromParent();
1889*9880d681SAndroid Build Coastguard Worker 
1890*9880d681SAndroid Build Coastguard Worker       // Update any other PHI nodes in BB.
1891*9880d681SAndroid Build Coastguard Worker       for (BasicBlock::iterator BI = BB->begin();
1892*9880d681SAndroid Build Coastguard Worker            PHINode *Phi = dyn_cast<PHINode>(BI); ++BI)
1893*9880d681SAndroid Build Coastguard Worker         if (Phi != CondLHS)
1894*9880d681SAndroid Build Coastguard Worker           Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB);
1895*9880d681SAndroid Build Coastguard Worker       return true;
1896*9880d681SAndroid Build Coastguard Worker     }
1897*9880d681SAndroid Build Coastguard Worker   }
1898*9880d681SAndroid Build Coastguard Worker   return false;
1899*9880d681SAndroid Build Coastguard Worker }
1900*9880d681SAndroid Build Coastguard Worker 
1901*9880d681SAndroid Build Coastguard Worker /// TryToUnfoldSelectInCurrBB - Look for PHI/Select in the same BB of the form
1902*9880d681SAndroid Build Coastguard Worker /// bb:
1903*9880d681SAndroid Build Coastguard Worker ///   %p = phi [false, %bb1], [true, %bb2], [false, %bb3], [true, %bb4], ...
1904*9880d681SAndroid Build Coastguard Worker ///   %s = select p, trueval, falseval
1905*9880d681SAndroid Build Coastguard Worker ///
1906*9880d681SAndroid Build Coastguard Worker /// And expand the select into a branch structure. This later enables
1907*9880d681SAndroid Build Coastguard Worker /// jump-threading over bb in this pass.
1908*9880d681SAndroid Build Coastguard Worker ///
1909*9880d681SAndroid Build Coastguard Worker /// Using the similar approach of SimplifyCFG::FoldCondBranchOnPHI(), unfold
1910*9880d681SAndroid Build Coastguard Worker /// select if the associated PHI has at least one constant.  If the unfolded
1911*9880d681SAndroid Build Coastguard Worker /// select is not jump-threaded, it will be folded again in the later
1912*9880d681SAndroid Build Coastguard Worker /// optimizations.
TryToUnfoldSelectInCurrBB(BasicBlock * BB)1913*9880d681SAndroid Build Coastguard Worker bool JumpThreadingPass::TryToUnfoldSelectInCurrBB(BasicBlock *BB) {
1914*9880d681SAndroid Build Coastguard Worker   // If threading this would thread across a loop header, don't thread the edge.
1915*9880d681SAndroid Build Coastguard Worker   // See the comments above FindLoopHeaders for justifications and caveats.
1916*9880d681SAndroid Build Coastguard Worker   if (LoopHeaders.count(BB))
1917*9880d681SAndroid Build Coastguard Worker     return false;
1918*9880d681SAndroid Build Coastguard Worker 
1919*9880d681SAndroid Build Coastguard Worker   // Look for a Phi/Select pair in the same basic block.  The Phi feeds the
1920*9880d681SAndroid Build Coastguard Worker   // condition of the Select and at least one of the incoming values is a
1921*9880d681SAndroid Build Coastguard Worker   // constant.
1922*9880d681SAndroid Build Coastguard Worker   for (BasicBlock::iterator BI = BB->begin();
1923*9880d681SAndroid Build Coastguard Worker        PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
1924*9880d681SAndroid Build Coastguard Worker     unsigned NumPHIValues = PN->getNumIncomingValues();
1925*9880d681SAndroid Build Coastguard Worker     if (NumPHIValues == 0 || !PN->hasOneUse())
1926*9880d681SAndroid Build Coastguard Worker       continue;
1927*9880d681SAndroid Build Coastguard Worker 
1928*9880d681SAndroid Build Coastguard Worker     SelectInst *SI = dyn_cast<SelectInst>(PN->user_back());
1929*9880d681SAndroid Build Coastguard Worker     if (!SI || SI->getParent() != BB)
1930*9880d681SAndroid Build Coastguard Worker       continue;
1931*9880d681SAndroid Build Coastguard Worker 
1932*9880d681SAndroid Build Coastguard Worker     Value *Cond = SI->getCondition();
1933*9880d681SAndroid Build Coastguard Worker     if (!Cond || Cond != PN || !Cond->getType()->isIntegerTy(1))
1934*9880d681SAndroid Build Coastguard Worker       continue;
1935*9880d681SAndroid Build Coastguard Worker 
1936*9880d681SAndroid Build Coastguard Worker     bool HasConst = false;
1937*9880d681SAndroid Build Coastguard Worker     for (unsigned i = 0; i != NumPHIValues; ++i) {
1938*9880d681SAndroid Build Coastguard Worker       if (PN->getIncomingBlock(i) == BB)
1939*9880d681SAndroid Build Coastguard Worker         return false;
1940*9880d681SAndroid Build Coastguard Worker       if (isa<ConstantInt>(PN->getIncomingValue(i)))
1941*9880d681SAndroid Build Coastguard Worker         HasConst = true;
1942*9880d681SAndroid Build Coastguard Worker     }
1943*9880d681SAndroid Build Coastguard Worker 
1944*9880d681SAndroid Build Coastguard Worker     if (HasConst) {
1945*9880d681SAndroid Build Coastguard Worker       // Expand the select.
1946*9880d681SAndroid Build Coastguard Worker       TerminatorInst *Term =
1947*9880d681SAndroid Build Coastguard Worker           SplitBlockAndInsertIfThen(SI->getCondition(), SI, false);
1948*9880d681SAndroid Build Coastguard Worker       PHINode *NewPN = PHINode::Create(SI->getType(), 2, "", SI);
1949*9880d681SAndroid Build Coastguard Worker       NewPN->addIncoming(SI->getTrueValue(), Term->getParent());
1950*9880d681SAndroid Build Coastguard Worker       NewPN->addIncoming(SI->getFalseValue(), BB);
1951*9880d681SAndroid Build Coastguard Worker       SI->replaceAllUsesWith(NewPN);
1952*9880d681SAndroid Build Coastguard Worker       SI->eraseFromParent();
1953*9880d681SAndroid Build Coastguard Worker       return true;
1954*9880d681SAndroid Build Coastguard Worker     }
1955*9880d681SAndroid Build Coastguard Worker   }
1956*9880d681SAndroid Build Coastguard Worker 
1957*9880d681SAndroid Build Coastguard Worker   return false;
1958*9880d681SAndroid Build Coastguard Worker }
1959