12cab237bSDimitry Andric //===- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop -------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This pass transforms loops that contain branches on loop-invariant conditions
1151690af2SDimitry Andric // to multiple loops.  For example, it turns the left into the right code:
12f22ef01cSRoman Divacky //
13f22ef01cSRoman Divacky //  for (...)                  if (lic)
14f22ef01cSRoman Divacky //    A                          for (...)
15f22ef01cSRoman Divacky //    if (lic)                     A; B; C
16f22ef01cSRoman Divacky //      B                      else
17f22ef01cSRoman Divacky //    C                          for (...)
18f22ef01cSRoman Divacky //                                 A; C
19f22ef01cSRoman Divacky //
20f22ef01cSRoman Divacky // This can increase the size of the code exponentially (doubling it every time
21f22ef01cSRoman Divacky // a loop is unswitched) so we only unswitch if the resultant code will be
22f22ef01cSRoman Divacky // smaller than a threshold.
23f22ef01cSRoman Divacky //
24f22ef01cSRoman Divacky // This pass expects LICM to be run before it to hoist invariant conditions out
25f22ef01cSRoman Divacky // of the loop, to make the unswitching opportunity obvious.
26f22ef01cSRoman Divacky //
27f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
28f22ef01cSRoman Divacky 
292cab237bSDimitry Andric #include "llvm/ADT/DenseMap.h"
30139f7f9bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
312cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
32139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h"
3339d628a0SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
34dff0c46cSDimitry Andric #include "llvm/Analysis/CodeMetrics.h"
35f22ef01cSRoman Divacky #include "llvm/Analysis/InstructionSimplify.h"
36*b5893f02SDimitry Andric #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
37f22ef01cSRoman Divacky #include "llvm/Analysis/LoopInfo.h"
38*b5893f02SDimitry Andric #include "llvm/Analysis/LoopIterator.h"
39f22ef01cSRoman Divacky #include "llvm/Analysis/LoopPass.h"
40*b5893f02SDimitry Andric #include "llvm/Analysis/MemorySSA.h"
41*b5893f02SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
422754fe60SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
43139f7f9bSDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
442cab237bSDimitry Andric #include "llvm/IR/Attributes.h"
452cab237bSDimitry Andric #include "llvm/IR/BasicBlock.h"
462cab237bSDimitry Andric #include "llvm/IR/CallSite.h"
472cab237bSDimitry Andric #include "llvm/IR/Constant.h"
48139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
49139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
5091bc56edSDimitry Andric #include "llvm/IR/Dominators.h"
51139f7f9bSDimitry Andric #include "llvm/IR/Function.h"
522cab237bSDimitry Andric #include "llvm/IR/IRBuilder.h"
537a7e6055SDimitry Andric #include "llvm/IR/InstrTypes.h"
542cab237bSDimitry Andric #include "llvm/IR/Instruction.h"
55db17bf38SDimitry Andric #include "llvm/IR/Instructions.h"
562cab237bSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
572cab237bSDimitry Andric #include "llvm/IR/Intrinsics.h"
58db17bf38SDimitry Andric #include "llvm/IR/Module.h"
592cab237bSDimitry Andric #include "llvm/IR/Type.h"
602cab237bSDimitry Andric #include "llvm/IR/User.h"
612cab237bSDimitry Andric #include "llvm/IR/Value.h"
622cab237bSDimitry Andric #include "llvm/IR/ValueHandle.h"
632cab237bSDimitry Andric #include "llvm/Pass.h"
642cab237bSDimitry Andric #include "llvm/Support/Casting.h"
65f22ef01cSRoman Divacky #include "llvm/Support/CommandLine.h"
66f22ef01cSRoman Divacky #include "llvm/Support/Debug.h"
67f22ef01cSRoman Divacky #include "llvm/Support/raw_ostream.h"
68db17bf38SDimitry Andric #include "llvm/Transforms/Scalar.h"
69*b5893f02SDimitry Andric #include "llvm/Transforms/Scalar/LoopPassManager.h"
70139f7f9bSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
71139f7f9bSDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
72*b5893f02SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
733ca95b02SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
742cab237bSDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
75f22ef01cSRoman Divacky #include <algorithm>
762cab237bSDimitry Andric #include <cassert>
77dff0c46cSDimitry Andric #include <map>
78f22ef01cSRoman Divacky #include <set>
792cab237bSDimitry Andric #include <tuple>
802cab237bSDimitry Andric #include <utility>
812cab237bSDimitry Andric #include <vector>
822cab237bSDimitry Andric 
83f22ef01cSRoman Divacky using namespace llvm;
84f22ef01cSRoman Divacky 
8591bc56edSDimitry Andric #define DEBUG_TYPE "loop-unswitch"
8691bc56edSDimitry Andric 
87f22ef01cSRoman Divacky STATISTIC(NumBranches, "Number of branches unswitched");
88f22ef01cSRoman Divacky STATISTIC(NumSwitches, "Number of switches unswitched");
893ca95b02SDimitry Andric STATISTIC(NumGuards,   "Number of guards unswitched");
90f22ef01cSRoman Divacky STATISTIC(NumSelects , "Number of selects unswitched");
91f22ef01cSRoman Divacky STATISTIC(NumTrivial , "Number of unswitches that are trivial");
92f22ef01cSRoman Divacky STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
93dff0c46cSDimitry Andric STATISTIC(TotalInsts,  "Total number of instructions analyzed");
94f22ef01cSRoman Divacky 
95dff0c46cSDimitry Andric // The specific value of 100 here was chosen based only on intuition and a
96f22ef01cSRoman Divacky // few specific examples.
97f22ef01cSRoman Divacky static cl::opt<unsigned>
98f22ef01cSRoman Divacky Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
99dff0c46cSDimitry Andric           cl::init(100), cl::Hidden);
100f22ef01cSRoman Divacky 
101f22ef01cSRoman Divacky namespace {
102dff0c46cSDimitry Andric 
103dff0c46cSDimitry Andric   class LUAnalysisCache {
1042cab237bSDimitry Andric     using UnswitchedValsMap =
1052cab237bSDimitry Andric         DenseMap<const SwitchInst *, SmallPtrSet<const Value *, 8>>;
1062cab237bSDimitry Andric     using UnswitchedValsIt = UnswitchedValsMap::iterator;
107dff0c46cSDimitry Andric 
108dff0c46cSDimitry Andric     struct LoopProperties {
109dff0c46cSDimitry Andric       unsigned CanBeUnswitchedCount;
1103dac3a9bSDimitry Andric       unsigned WasUnswitchedCount;
111dff0c46cSDimitry Andric       unsigned SizeEstimation;
112dff0c46cSDimitry Andric       UnswitchedValsMap UnswitchedVals;
113dff0c46cSDimitry Andric     };
114dff0c46cSDimitry Andric 
115dff0c46cSDimitry Andric     // Here we use std::map instead of DenseMap, since we need to keep valid
116dff0c46cSDimitry Andric     // LoopProperties pointer for current loop for better performance.
1172cab237bSDimitry Andric     using LoopPropsMap = std::map<const Loop *, LoopProperties>;
1182cab237bSDimitry Andric     using LoopPropsMapIt = LoopPropsMap::iterator;
119dff0c46cSDimitry Andric 
120dff0c46cSDimitry Andric     LoopPropsMap LoopsProperties;
1212cab237bSDimitry Andric     UnswitchedValsMap *CurLoopInstructions = nullptr;
1222cab237bSDimitry Andric     LoopProperties *CurrentLoopProperties = nullptr;
123dff0c46cSDimitry Andric 
1243dac3a9bSDimitry Andric     // A loop unswitching with an estimated cost above this threshold
1253dac3a9bSDimitry Andric     // is not performed. MaxSize is turned into unswitching quota for
1263dac3a9bSDimitry Andric     // the current loop, and reduced correspondingly, though note that
1273dac3a9bSDimitry Andric     // the quota is returned by releaseMemory() when the loop has been
1283dac3a9bSDimitry Andric     // processed, so that MaxSize will return to its previous
1293dac3a9bSDimitry Andric     // value. So in most cases MaxSize will equal the Threshold flag
1303dac3a9bSDimitry Andric     // when a new loop is processed. An exception to that is that
1313dac3a9bSDimitry Andric     // MaxSize will have a smaller value while processing nested loops
1323dac3a9bSDimitry Andric     // that were introduced due to loop unswitching of an outer loop.
1333dac3a9bSDimitry Andric     //
1343dac3a9bSDimitry Andric     // FIXME: The way that MaxSize works is subtle and depends on the
1353dac3a9bSDimitry Andric     // pass manager processing loops and calling releaseMemory() in a
1363dac3a9bSDimitry Andric     // specific order. It would be good to find a more straightforward
1373dac3a9bSDimitry Andric     // way of doing what MaxSize does.
138dff0c46cSDimitry Andric     unsigned MaxSize;
139dff0c46cSDimitry Andric 
140dff0c46cSDimitry Andric   public:
LUAnalysisCache()1412cab237bSDimitry Andric     LUAnalysisCache() : MaxSize(Threshold) {}
142dff0c46cSDimitry Andric 
143dff0c46cSDimitry Andric     // Analyze loop. Check its size, calculate is it possible to unswitch
144dff0c46cSDimitry Andric     // it. Returns true if we can unswitch this loop.
14539d628a0SDimitry Andric     bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
14639d628a0SDimitry Andric                    AssumptionCache *AC);
147dff0c46cSDimitry Andric 
148dff0c46cSDimitry Andric     // Clean all data related to given loop.
149dff0c46cSDimitry Andric     void forgetLoop(const Loop *L);
150dff0c46cSDimitry Andric 
151dff0c46cSDimitry Andric     // Mark case value as unswitched.
152dff0c46cSDimitry Andric     // Since SI instruction can be partly unswitched, in order to avoid
153dff0c46cSDimitry Andric     // extra unswitching in cloned loops keep track all unswitched values.
154dff0c46cSDimitry Andric     void setUnswitched(const SwitchInst *SI, const Value *V);
155dff0c46cSDimitry Andric 
156dff0c46cSDimitry Andric     // Check was this case value unswitched before or not.
157dff0c46cSDimitry Andric     bool isUnswitched(const SwitchInst *SI, const Value *V);
158dff0c46cSDimitry Andric 
1593dac3a9bSDimitry Andric     // Returns true if another unswitching could be done within the cost
1603dac3a9bSDimitry Andric     // threshold.
1613dac3a9bSDimitry Andric     bool CostAllowsUnswitching();
1623dac3a9bSDimitry Andric 
163dff0c46cSDimitry Andric     // Clone all loop-unswitch related loop properties.
164dff0c46cSDimitry Andric     // Redistribute unswitching quotas.
165dff0c46cSDimitry Andric     // Note, that new loop data is stored inside the VMap.
166dff0c46cSDimitry Andric     void cloneData(const Loop *NewLoop, const Loop *OldLoop,
167dff0c46cSDimitry Andric                    const ValueToValueMapTy &VMap);
168dff0c46cSDimitry Andric   };
169dff0c46cSDimitry Andric 
170f22ef01cSRoman Divacky   class LoopUnswitch : public LoopPass {
171f22ef01cSRoman Divacky     LoopInfo *LI;  // Loop information
172f22ef01cSRoman Divacky     LPPassManager *LPM;
17339d628a0SDimitry Andric     AssumptionCache *AC;
174f22ef01cSRoman Divacky 
1757d523365SDimitry Andric     // Used to check if second loop needs processing after
1767d523365SDimitry Andric     // RewriteLoopBodyWithConditionConstant rewrites first loop.
177f22ef01cSRoman Divacky     std::vector<Loop*> LoopProcessWorklist;
178dff0c46cSDimitry Andric 
179dff0c46cSDimitry Andric     LUAnalysisCache BranchesInfo;
180f22ef01cSRoman Divacky 
181f22ef01cSRoman Divacky     bool OptimizeForSize;
1822cab237bSDimitry Andric     bool redoLoop = false;
183f22ef01cSRoman Divacky 
1842cab237bSDimitry Andric     Loop *currentLoop = nullptr;
1852cab237bSDimitry Andric     DominatorTree *DT = nullptr;
186*b5893f02SDimitry Andric     MemorySSA *MSSA = nullptr;
187*b5893f02SDimitry Andric     std::unique_ptr<MemorySSAUpdater> MSSAU;
1882cab237bSDimitry Andric     BasicBlock *loopHeader = nullptr;
1892cab237bSDimitry Andric     BasicBlock *loopPreheader = nullptr;
190f22ef01cSRoman Divacky 
1913ca95b02SDimitry Andric     bool SanitizeMemory;
192*b5893f02SDimitry Andric     SimpleLoopSafetyInfo SafetyInfo;
1933ca95b02SDimitry Andric 
194f22ef01cSRoman Divacky     // LoopBlocks contains all of the basic blocks of the loop, including the
195f22ef01cSRoman Divacky     // preheader of the loop, the body of the loop, and the exit blocks of the
196f22ef01cSRoman Divacky     // loop, in that order.
197f22ef01cSRoman Divacky     std::vector<BasicBlock*> LoopBlocks;
198f22ef01cSRoman Divacky     // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
199f22ef01cSRoman Divacky     std::vector<BasicBlock*> NewBlocks;
200f22ef01cSRoman Divacky 
2017a7e6055SDimitry Andric     bool hasBranchDivergence;
2027a7e6055SDimitry Andric 
203f22ef01cSRoman Divacky   public:
204f22ef01cSRoman Divacky     static char ID; // Pass ID, replacement for typeid
2052cab237bSDimitry Andric 
LoopUnswitch(bool Os=false,bool hasBranchDivergence=false)2062cab237bSDimitry Andric     explicit LoopUnswitch(bool Os = false, bool hasBranchDivergence = false)
2072cab237bSDimitry Andric         : LoopPass(ID), OptimizeForSize(Os),
2082cab237bSDimitry Andric           hasBranchDivergence(hasBranchDivergence) {
2092754fe60SDimitry Andric         initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
2102754fe60SDimitry Andric     }
211f22ef01cSRoman Divacky 
21291bc56edSDimitry Andric     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
213f22ef01cSRoman Divacky     bool processCurrentLoop();
214d88c1a5aSDimitry Andric     bool isUnreachableDueToPreviousUnswitching(BasicBlock *);
2152cab237bSDimitry Andric 
216f22ef01cSRoman Divacky     /// This transformation requires natural loop information & requires that
217e580952dSDimitry Andric     /// loop preheaders be inserted into the CFG.
218f22ef01cSRoman Divacky     ///
getAnalysisUsage(AnalysisUsage & AU) const21991bc56edSDimitry Andric     void getAnalysisUsage(AnalysisUsage &AU) const override {
22039d628a0SDimitry Andric       AU.addRequired<AssumptionCacheTracker>();
221ff0cc061SDimitry Andric       AU.addRequired<TargetTransformInfoWrapperPass>();
222*b5893f02SDimitry Andric       if (EnableMSSALoopDependency) {
223*b5893f02SDimitry Andric         AU.addRequired<MemorySSAWrapperPass>();
224*b5893f02SDimitry Andric         AU.addPreserved<MemorySSAWrapperPass>();
225*b5893f02SDimitry Andric       }
2267a7e6055SDimitry Andric       if (hasBranchDivergence)
227*b5893f02SDimitry Andric         AU.addRequired<LegacyDivergenceAnalysis>();
2283ca95b02SDimitry Andric       getLoopAnalysisUsage(AU);
229f22ef01cSRoman Divacky     }
230f22ef01cSRoman Divacky 
231f22ef01cSRoman Divacky   private:
releaseMemory()23291bc56edSDimitry Andric     void releaseMemory() override {
233dff0c46cSDimitry Andric       BranchesInfo.forgetLoop(currentLoop);
234f22ef01cSRoman Divacky     }
235f22ef01cSRoman Divacky 
initLoopData()236f22ef01cSRoman Divacky     void initLoopData() {
237f22ef01cSRoman Divacky       loopHeader = currentLoop->getHeader();
238f22ef01cSRoman Divacky       loopPreheader = currentLoop->getLoopPreheader();
239f22ef01cSRoman Divacky     }
240f22ef01cSRoman Divacky 
241f22ef01cSRoman Divacky     /// Split all of the edges from inside the loop to their exit blocks.
242f22ef01cSRoman Divacky     /// Update the appropriate Phi nodes as we do so.
2437d523365SDimitry Andric     void SplitExitEdges(Loop *L,
2447d523365SDimitry Andric                         const SmallVectorImpl<BasicBlock *> &ExitBlocks);
2457d523365SDimitry Andric 
2467d523365SDimitry Andric     bool TryTrivialLoopUnswitch(bool &Changed);
247f22ef01cSRoman Divacky 
2483dac3a9bSDimitry Andric     bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,
249*b5893f02SDimitry Andric                               Instruction *TI = nullptr);
250f22ef01cSRoman Divacky     void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
251*b5893f02SDimitry Andric                                   BasicBlock *ExitBlock, Instruction *TI);
2523dac3a9bSDimitry Andric     void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L,
253*b5893f02SDimitry Andric                                      Instruction *TI);
254f22ef01cSRoman Divacky 
255f22ef01cSRoman Divacky     void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
256f22ef01cSRoman Divacky                                               Constant *Val, bool isEqual);
257f22ef01cSRoman Divacky 
258f22ef01cSRoman Divacky     void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
259f22ef01cSRoman Divacky                                         BasicBlock *TrueDest,
260f22ef01cSRoman Divacky                                         BasicBlock *FalseDest,
261*b5893f02SDimitry Andric                                         BranchInst *OldBranch, Instruction *TI);
262f22ef01cSRoman Divacky 
263f22ef01cSRoman Divacky     void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
2647a7e6055SDimitry Andric 
2657a7e6055SDimitry Andric     /// Given that the Invariant is not equal to Val. Simplify instructions
2667a7e6055SDimitry Andric     /// in the loop.
2677a7e6055SDimitry Andric     Value *SimplifyInstructionWithNotEqual(Instruction *Inst, Value *Invariant,
2687a7e6055SDimitry Andric                                            Constant *Val);
269f22ef01cSRoman Divacky   };
2702cab237bSDimitry Andric 
2712cab237bSDimitry Andric } // end anonymous namespace
272dff0c46cSDimitry Andric 
273dff0c46cSDimitry Andric // Analyze loop. Check its size, calculate is it possible to unswitch
274dff0c46cSDimitry Andric // it. Returns true if we can unswitch this loop.
countLoop(const Loop * L,const TargetTransformInfo & TTI,AssumptionCache * AC)27539d628a0SDimitry Andric bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
27639d628a0SDimitry Andric                                 AssumptionCache *AC) {
277f785676fSDimitry Andric   LoopPropsMapIt PropsIt;
278f785676fSDimitry Andric   bool Inserted;
27991bc56edSDimitry Andric   std::tie(PropsIt, Inserted) =
280dff0c46cSDimitry Andric       LoopsProperties.insert(std::make_pair(L, LoopProperties()));
281dff0c46cSDimitry Andric 
282f785676fSDimitry Andric   LoopProperties &Props = PropsIt->second;
283dff0c46cSDimitry Andric 
284f785676fSDimitry Andric   if (Inserted) {
285dff0c46cSDimitry Andric     // New loop.
286dff0c46cSDimitry Andric 
287dff0c46cSDimitry Andric     // Limit the number of instructions to avoid causing significant code
288dff0c46cSDimitry Andric     // expansion, and the number of basic blocks, to avoid loops with
289dff0c46cSDimitry Andric     // large numbers of branches which cause loop unswitching to go crazy.
290dff0c46cSDimitry Andric     // This is a very ad-hoc heuristic.
291dff0c46cSDimitry Andric 
29239d628a0SDimitry Andric     SmallPtrSet<const Value *, 32> EphValues;
29339d628a0SDimitry Andric     CodeMetrics::collectEphemeralValues(L, AC, EphValues);
29439d628a0SDimitry Andric 
295dff0c46cSDimitry Andric     // FIXME: This is overly conservative because it does not take into
296dff0c46cSDimitry Andric     // consideration code simplification opportunities and code that can
297dff0c46cSDimitry Andric     // be shared by the resultant unswitched loops.
298dff0c46cSDimitry Andric     CodeMetrics Metrics;
2993dac3a9bSDimitry Andric     for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
3003dac3a9bSDimitry Andric          ++I)
30139d628a0SDimitry Andric       Metrics.analyzeBasicBlock(*I, TTI, EphValues);
302dff0c46cSDimitry Andric 
3033dac3a9bSDimitry Andric     Props.SizeEstimation = Metrics.NumInsts;
304dff0c46cSDimitry Andric     Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
3053dac3a9bSDimitry Andric     Props.WasUnswitchedCount = 0;
306dff0c46cSDimitry Andric     MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
307139f7f9bSDimitry Andric 
308139f7f9bSDimitry Andric     if (Metrics.notDuplicatable) {
3094ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "NOT unswitching loop %" << L->getHeader()->getName()
3104ba319b5SDimitry Andric                         << ", contents cannot be "
311139f7f9bSDimitry Andric                         << "duplicated!\n");
312139f7f9bSDimitry Andric       return false;
313139f7f9bSDimitry Andric     }
314dff0c46cSDimitry Andric   }
315dff0c46cSDimitry Andric 
316dff0c46cSDimitry Andric   // Be careful. This links are good only before new loop addition.
317dff0c46cSDimitry Andric   CurrentLoopProperties = &Props;
318dff0c46cSDimitry Andric   CurLoopInstructions = &Props.UnswitchedVals;
319dff0c46cSDimitry Andric 
320dff0c46cSDimitry Andric   return true;
321dff0c46cSDimitry Andric }
322dff0c46cSDimitry Andric 
323dff0c46cSDimitry Andric // Clean all data related to given loop.
forgetLoop(const Loop * L)324dff0c46cSDimitry Andric void LUAnalysisCache::forgetLoop(const Loop *L) {
325dff0c46cSDimitry Andric   LoopPropsMapIt LIt = LoopsProperties.find(L);
326dff0c46cSDimitry Andric 
327dff0c46cSDimitry Andric   if (LIt != LoopsProperties.end()) {
328dff0c46cSDimitry Andric     LoopProperties &Props = LIt->second;
3293dac3a9bSDimitry Andric     MaxSize += (Props.CanBeUnswitchedCount + Props.WasUnswitchedCount) *
3303dac3a9bSDimitry Andric                Props.SizeEstimation;
331dff0c46cSDimitry Andric     LoopsProperties.erase(LIt);
332dff0c46cSDimitry Andric   }
333dff0c46cSDimitry Andric 
33491bc56edSDimitry Andric   CurrentLoopProperties = nullptr;
33591bc56edSDimitry Andric   CurLoopInstructions = nullptr;
336dff0c46cSDimitry Andric }
337dff0c46cSDimitry Andric 
338dff0c46cSDimitry Andric // Mark case value as unswitched.
339dff0c46cSDimitry Andric // Since SI instruction can be partly unswitched, in order to avoid
340dff0c46cSDimitry Andric // extra unswitching in cloned loops keep track all unswitched values.
setUnswitched(const SwitchInst * SI,const Value * V)341dff0c46cSDimitry Andric void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
342dff0c46cSDimitry Andric   (*CurLoopInstructions)[SI].insert(V);
343dff0c46cSDimitry Andric }
344dff0c46cSDimitry Andric 
345dff0c46cSDimitry Andric // Check was this case value unswitched before or not.
isUnswitched(const SwitchInst * SI,const Value * V)346dff0c46cSDimitry Andric bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
347dff0c46cSDimitry Andric   return (*CurLoopInstructions)[SI].count(V);
348dff0c46cSDimitry Andric }
349dff0c46cSDimitry Andric 
CostAllowsUnswitching()3503dac3a9bSDimitry Andric bool LUAnalysisCache::CostAllowsUnswitching() {
3513dac3a9bSDimitry Andric   return CurrentLoopProperties->CanBeUnswitchedCount > 0;
3523dac3a9bSDimitry Andric }
3533dac3a9bSDimitry Andric 
354dff0c46cSDimitry Andric // Clone all loop-unswitch related loop properties.
355dff0c46cSDimitry Andric // Redistribute unswitching quotas.
356dff0c46cSDimitry Andric // Note, that new loop data is stored inside the VMap.
cloneData(const Loop * NewLoop,const Loop * OldLoop,const ValueToValueMapTy & VMap)357dff0c46cSDimitry Andric void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
358dff0c46cSDimitry Andric                                 const ValueToValueMapTy &VMap) {
359dff0c46cSDimitry Andric   LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
360dff0c46cSDimitry Andric   LoopProperties &OldLoopProps = *CurrentLoopProperties;
361dff0c46cSDimitry Andric   UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
362dff0c46cSDimitry Andric 
363dff0c46cSDimitry Andric   // Reallocate "can-be-unswitched quota"
364dff0c46cSDimitry Andric 
365dff0c46cSDimitry Andric   --OldLoopProps.CanBeUnswitchedCount;
3663dac3a9bSDimitry Andric   ++OldLoopProps.WasUnswitchedCount;
3673dac3a9bSDimitry Andric   NewLoopProps.WasUnswitchedCount = 0;
368dff0c46cSDimitry Andric   unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
369dff0c46cSDimitry Andric   NewLoopProps.CanBeUnswitchedCount = Quota / 2;
370dff0c46cSDimitry Andric   OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
371dff0c46cSDimitry Andric 
372dff0c46cSDimitry Andric   NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
373dff0c46cSDimitry Andric 
374dff0c46cSDimitry Andric   // Clone unswitched values info:
375dff0c46cSDimitry Andric   // for new loop switches we clone info about values that was
376dff0c46cSDimitry Andric   // already unswitched and has redundant successors.
377dff0c46cSDimitry Andric   for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
378dff0c46cSDimitry Andric     const SwitchInst *OldInst = I->first;
379dff0c46cSDimitry Andric     Value *NewI = VMap.lookup(OldInst);
380dff0c46cSDimitry Andric     const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
381dff0c46cSDimitry Andric     assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
382dff0c46cSDimitry Andric 
383dff0c46cSDimitry Andric     NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
384dff0c46cSDimitry Andric   }
385dff0c46cSDimitry Andric }
386dff0c46cSDimitry Andric 
387f22ef01cSRoman Divacky char LoopUnswitch::ID = 0;
3882cab237bSDimitry Andric 
3892754fe60SDimitry Andric INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
3902754fe60SDimitry Andric                       false, false)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)39139d628a0SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3923ca95b02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopPass)
3933ca95b02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
394*b5893f02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
395*b5893f02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
3962754fe60SDimitry Andric INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
3972754fe60SDimitry Andric                       false, false)
398f22ef01cSRoman Divacky 
3997a7e6055SDimitry Andric Pass *llvm::createLoopUnswitchPass(bool Os, bool hasBranchDivergence) {
4007a7e6055SDimitry Andric   return new LoopUnswitch(Os, hasBranchDivergence);
401f22ef01cSRoman Divacky }
402f22ef01cSRoman Divacky 
4037a7e6055SDimitry Andric /// Operator chain lattice.
4047a7e6055SDimitry Andric enum OperatorChain {
4057a7e6055SDimitry Andric   OC_OpChainNone,    ///< There is no operator.
4067a7e6055SDimitry Andric   OC_OpChainOr,      ///< There are only ORs.
4077a7e6055SDimitry Andric   OC_OpChainAnd,     ///< There are only ANDs.
4087a7e6055SDimitry Andric   OC_OpChainMixed    ///< There are ANDs and ORs.
4097a7e6055SDimitry Andric };
4107a7e6055SDimitry Andric 
4117d523365SDimitry Andric /// Cond is a condition that occurs in L. If it is invariant in the loop, or has
4127d523365SDimitry Andric /// an invariant piece, return the invariant. Otherwise, return null.
4137a7e6055SDimitry Andric //
4147a7e6055SDimitry Andric /// NOTE: FindLIVLoopCondition will not return a partial LIV by walking up a
4157a7e6055SDimitry Andric /// mixed operator chain, as we can not reliably find a value which will simplify
4167a7e6055SDimitry Andric /// the operator chain. If the chain is AND-only or OR-only, we can use 0 or ~0
4177a7e6055SDimitry Andric /// to simplify the chain.
4187a7e6055SDimitry Andric ///
4197a7e6055SDimitry Andric /// NOTE: In case a partial LIV and a mixed operator chain, we may be able to
4207a7e6055SDimitry Andric /// simplify the condition itself to a loop variant condition, but at the
4217a7e6055SDimitry Andric /// cost of creating an entirely new loop.
FindLIVLoopCondition(Value * Cond,Loop * L,bool & Changed,OperatorChain & ParentChain,DenseMap<Value *,Value * > & Cache)4223ca95b02SDimitry Andric static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed,
4237a7e6055SDimitry Andric                                    OperatorChain &ParentChain,
4243ca95b02SDimitry Andric                                    DenseMap<Value *, Value *> &Cache) {
4253ca95b02SDimitry Andric   auto CacheIt = Cache.find(Cond);
4263ca95b02SDimitry Andric   if (CacheIt != Cache.end())
4273ca95b02SDimitry Andric     return CacheIt->second;
428dff0c46cSDimitry Andric 
429dff0c46cSDimitry Andric   // We started analyze new instruction, increment scanned instructions counter.
430dff0c46cSDimitry Andric   ++TotalInsts;
431dff0c46cSDimitry Andric 
432f22ef01cSRoman Divacky   // We can never unswitch on vector conditions.
433f22ef01cSRoman Divacky   if (Cond->getType()->isVectorTy())
43491bc56edSDimitry Andric     return nullptr;
435f22ef01cSRoman Divacky 
436f22ef01cSRoman Divacky   // Constants should be folded, not unswitched on!
43791bc56edSDimitry Andric   if (isa<Constant>(Cond)) return nullptr;
438f22ef01cSRoman Divacky 
439f22ef01cSRoman Divacky   // TODO: Handle: br (VARIANT|INVARIANT).
440f22ef01cSRoman Divacky 
441f22ef01cSRoman Divacky   // Hoist simple values out.
4423ca95b02SDimitry Andric   if (L->makeLoopInvariant(Cond, Changed)) {
4433ca95b02SDimitry Andric     Cache[Cond] = Cond;
444f22ef01cSRoman Divacky     return Cond;
4453ca95b02SDimitry Andric   }
446f22ef01cSRoman Divacky 
4477a7e6055SDimitry Andric   // Walk up the operator chain to find partial invariant conditions.
448f22ef01cSRoman Divacky   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
449f22ef01cSRoman Divacky     if (BO->getOpcode() == Instruction::And ||
450f22ef01cSRoman Divacky         BO->getOpcode() == Instruction::Or) {
4517a7e6055SDimitry Andric       // Given the previous operator, compute the current operator chain status.
4527a7e6055SDimitry Andric       OperatorChain NewChain;
4537a7e6055SDimitry Andric       switch (ParentChain) {
4547a7e6055SDimitry Andric       case OC_OpChainNone:
4557a7e6055SDimitry Andric         NewChain = BO->getOpcode() == Instruction::And ? OC_OpChainAnd :
4567a7e6055SDimitry Andric                                       OC_OpChainOr;
4577a7e6055SDimitry Andric         break;
4587a7e6055SDimitry Andric       case OC_OpChainOr:
4597a7e6055SDimitry Andric         NewChain = BO->getOpcode() == Instruction::Or ? OC_OpChainOr :
4607a7e6055SDimitry Andric                                       OC_OpChainMixed;
4617a7e6055SDimitry Andric         break;
4627a7e6055SDimitry Andric       case OC_OpChainAnd:
4637a7e6055SDimitry Andric         NewChain = BO->getOpcode() == Instruction::And ? OC_OpChainAnd :
4647a7e6055SDimitry Andric                                       OC_OpChainMixed;
4657a7e6055SDimitry Andric         break;
4667a7e6055SDimitry Andric       case OC_OpChainMixed:
4677a7e6055SDimitry Andric         NewChain = OC_OpChainMixed;
4687a7e6055SDimitry Andric         break;
4697a7e6055SDimitry Andric       }
4707a7e6055SDimitry Andric 
4717a7e6055SDimitry Andric       // If we reach a Mixed state, we do not want to keep walking up as we can not
4727a7e6055SDimitry Andric       // reliably find a value that will simplify the chain. With this check, we
4737a7e6055SDimitry Andric       // will return null on the first sight of mixed chain and the caller will
4747a7e6055SDimitry Andric       // either backtrack to find partial LIV in other operand or return null.
4757a7e6055SDimitry Andric       if (NewChain != OC_OpChainMixed) {
4767a7e6055SDimitry Andric         // Update the current operator chain type before we search up the chain.
4777a7e6055SDimitry Andric         ParentChain = NewChain;
478f22ef01cSRoman Divacky         // If either the left or right side is invariant, we can unswitch on this,
479f22ef01cSRoman Divacky         // which will cause the branch to go away in one loop and the condition to
480f22ef01cSRoman Divacky         // simplify in the other one.
4817a7e6055SDimitry Andric         if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed,
4827a7e6055SDimitry Andric                                               ParentChain, Cache)) {
4833ca95b02SDimitry Andric           Cache[Cond] = LHS;
484f22ef01cSRoman Divacky           return LHS;
4853ca95b02SDimitry Andric         }
4867a7e6055SDimitry Andric         // We did not manage to find a partial LIV in operand(0). Backtrack and try
4877a7e6055SDimitry Andric         // operand(1).
4887a7e6055SDimitry Andric         ParentChain = NewChain;
4897a7e6055SDimitry Andric         if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed,
4907a7e6055SDimitry Andric                                               ParentChain, Cache)) {
4913ca95b02SDimitry Andric           Cache[Cond] = RHS;
492f22ef01cSRoman Divacky           return RHS;
493f22ef01cSRoman Divacky         }
4943ca95b02SDimitry Andric       }
4957a7e6055SDimitry Andric     }
496f22ef01cSRoman Divacky 
4973ca95b02SDimitry Andric   Cache[Cond] = nullptr;
49891bc56edSDimitry Andric   return nullptr;
499f22ef01cSRoman Divacky }
500f22ef01cSRoman Divacky 
5017a7e6055SDimitry Andric /// Cond is a condition that occurs in L. If it is invariant in the loop, or has
5027a7e6055SDimitry Andric /// an invariant piece, return the invariant along with the operator chain type.
5037a7e6055SDimitry Andric /// Otherwise, return null.
FindLIVLoopCondition(Value * Cond,Loop * L,bool & Changed)5047a7e6055SDimitry Andric static std::pair<Value *, OperatorChain> FindLIVLoopCondition(Value *Cond,
5057a7e6055SDimitry Andric                                                               Loop *L,
5067a7e6055SDimitry Andric                                                               bool &Changed) {
5073ca95b02SDimitry Andric   DenseMap<Value *, Value *> Cache;
5087a7e6055SDimitry Andric   OperatorChain OpChain = OC_OpChainNone;
5097a7e6055SDimitry Andric   Value *FCond = FindLIVLoopCondition(Cond, L, Changed, OpChain, Cache);
5107a7e6055SDimitry Andric 
5117a7e6055SDimitry Andric   // In case we do find a LIV, it can not be obtained by walking up a mixed
5127a7e6055SDimitry Andric   // operator chain.
5137a7e6055SDimitry Andric   assert((!FCond || OpChain != OC_OpChainMixed) &&
5147a7e6055SDimitry Andric         "Do not expect a partial LIV with mixed operator chain");
5157a7e6055SDimitry Andric   return {FCond, OpChain};
5163ca95b02SDimitry Andric }
5173ca95b02SDimitry Andric 
runOnLoop(Loop * L,LPPassManager & LPM_Ref)518f22ef01cSRoman Divacky bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
5193ca95b02SDimitry Andric   if (skipLoop(L))
52091bc56edSDimitry Andric     return false;
52191bc56edSDimitry Andric 
52239d628a0SDimitry Andric   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
52339d628a0SDimitry Andric       *L->getHeader()->getParent());
524ff0cc061SDimitry Andric   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
525f22ef01cSRoman Divacky   LPM = &LPM_Ref;
5267d523365SDimitry Andric   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
527*b5893f02SDimitry Andric   if (EnableMSSALoopDependency) {
528*b5893f02SDimitry Andric     MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
529*b5893f02SDimitry Andric     MSSAU = make_unique<MemorySSAUpdater>(MSSA);
530*b5893f02SDimitry Andric     assert(DT && "Cannot update MemorySSA without a valid DomTree.");
531*b5893f02SDimitry Andric   }
532f22ef01cSRoman Divacky   currentLoop = L;
533f22ef01cSRoman Divacky   Function *F = currentLoop->getHeader()->getParent();
5347d523365SDimitry Andric 
5353ca95b02SDimitry Andric   SanitizeMemory = F->hasFnAttribute(Attribute::SanitizeMemory);
5363ca95b02SDimitry Andric   if (SanitizeMemory)
537*b5893f02SDimitry Andric     SafetyInfo.computeLoopSafetyInfo(L);
538*b5893f02SDimitry Andric 
539*b5893f02SDimitry Andric   if (MSSA && VerifyMemorySSA)
540*b5893f02SDimitry Andric     MSSA->verifyMemorySSA();
5413ca95b02SDimitry Andric 
542f22ef01cSRoman Divacky   bool Changed = false;
543f22ef01cSRoman Divacky   do {
544f22ef01cSRoman Divacky     assert(currentLoop->isLCSSAForm(*DT));
545*b5893f02SDimitry Andric     if (MSSA && VerifyMemorySSA)
546*b5893f02SDimitry Andric       MSSA->verifyMemorySSA();
547f22ef01cSRoman Divacky     redoLoop = false;
548f22ef01cSRoman Divacky     Changed |= processCurrentLoop();
549f22ef01cSRoman Divacky   } while(redoLoop);
550f22ef01cSRoman Divacky 
551*b5893f02SDimitry Andric   if (MSSA && VerifyMemorySSA)
552*b5893f02SDimitry Andric     MSSA->verifyMemorySSA();
553*b5893f02SDimitry Andric 
554f22ef01cSRoman Divacky   return Changed;
555f22ef01cSRoman Divacky }
556f22ef01cSRoman Divacky 
557d88c1a5aSDimitry Andric // Return true if the BasicBlock BB is unreachable from the loop header.
558d88c1a5aSDimitry Andric // Return false, otherwise.
isUnreachableDueToPreviousUnswitching(BasicBlock * BB)559d88c1a5aSDimitry Andric bool LoopUnswitch::isUnreachableDueToPreviousUnswitching(BasicBlock *BB) {
560d88c1a5aSDimitry Andric   auto *Node = DT->getNode(BB)->getIDom();
561d88c1a5aSDimitry Andric   BasicBlock *DomBB = Node->getBlock();
562d88c1a5aSDimitry Andric   while (currentLoop->contains(DomBB)) {
563d88c1a5aSDimitry Andric     BranchInst *BInst = dyn_cast<BranchInst>(DomBB->getTerminator());
564d88c1a5aSDimitry Andric 
565d88c1a5aSDimitry Andric     Node = DT->getNode(DomBB)->getIDom();
566d88c1a5aSDimitry Andric     DomBB = Node->getBlock();
567d88c1a5aSDimitry Andric 
568d88c1a5aSDimitry Andric     if (!BInst || !BInst->isConditional())
569d88c1a5aSDimitry Andric       continue;
570d88c1a5aSDimitry Andric 
571d88c1a5aSDimitry Andric     Value *Cond = BInst->getCondition();
572d88c1a5aSDimitry Andric     if (!isa<ConstantInt>(Cond))
573d88c1a5aSDimitry Andric       continue;
574d88c1a5aSDimitry Andric 
575d88c1a5aSDimitry Andric     BasicBlock *UnreachableSucc =
576d88c1a5aSDimitry Andric         Cond == ConstantInt::getTrue(Cond->getContext())
577d88c1a5aSDimitry Andric             ? BInst->getSuccessor(1)
578d88c1a5aSDimitry Andric             : BInst->getSuccessor(0);
579d88c1a5aSDimitry Andric 
580d88c1a5aSDimitry Andric     if (DT->dominates(UnreachableSucc, BB))
581d88c1a5aSDimitry Andric       return true;
582d88c1a5aSDimitry Andric   }
583d88c1a5aSDimitry Andric   return false;
584d88c1a5aSDimitry Andric }
585d88c1a5aSDimitry Andric 
5862cab237bSDimitry Andric /// FIXME: Remove this workaround when freeze related patches are done.
5872cab237bSDimitry Andric /// LoopUnswitch and Equality propagation in GVN have discrepancy about
5882cab237bSDimitry Andric /// whether branch on undef/poison has undefine behavior. Here it is to
5892cab237bSDimitry Andric /// rule out some common cases that we found such discrepancy already
5902cab237bSDimitry Andric /// causing problems. Detail could be found in PR31652. Note if the
5912cab237bSDimitry Andric /// func returns true, it is unsafe. But if it is false, it doesn't mean
5922cab237bSDimitry Andric /// it is necessarily safe.
EqualityPropUnSafe(Value & LoopCond)5932cab237bSDimitry Andric static bool EqualityPropUnSafe(Value &LoopCond) {
5942cab237bSDimitry Andric   ICmpInst *CI = dyn_cast<ICmpInst>(&LoopCond);
5952cab237bSDimitry Andric   if (!CI || !CI->isEquality())
5962cab237bSDimitry Andric     return false;
5972cab237bSDimitry Andric 
5982cab237bSDimitry Andric   Value *LHS = CI->getOperand(0);
5992cab237bSDimitry Andric   Value *RHS = CI->getOperand(1);
6002cab237bSDimitry Andric   if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
6012cab237bSDimitry Andric     return true;
6022cab237bSDimitry Andric 
6032cab237bSDimitry Andric   auto hasUndefInPHI = [](PHINode &PN) {
6042cab237bSDimitry Andric     for (Value *Opd : PN.incoming_values()) {
6052cab237bSDimitry Andric       if (isa<UndefValue>(Opd))
6062cab237bSDimitry Andric         return true;
6072cab237bSDimitry Andric     }
6082cab237bSDimitry Andric     return false;
6092cab237bSDimitry Andric   };
6102cab237bSDimitry Andric   PHINode *LPHI = dyn_cast<PHINode>(LHS);
6112cab237bSDimitry Andric   PHINode *RPHI = dyn_cast<PHINode>(RHS);
6122cab237bSDimitry Andric   if ((LPHI && hasUndefInPHI(*LPHI)) || (RPHI && hasUndefInPHI(*RPHI)))
6132cab237bSDimitry Andric     return true;
6142cab237bSDimitry Andric 
6152cab237bSDimitry Andric   auto hasUndefInSelect = [](SelectInst &SI) {
6162cab237bSDimitry Andric     if (isa<UndefValue>(SI.getTrueValue()) ||
6172cab237bSDimitry Andric         isa<UndefValue>(SI.getFalseValue()))
6182cab237bSDimitry Andric       return true;
6192cab237bSDimitry Andric     return false;
6202cab237bSDimitry Andric   };
6212cab237bSDimitry Andric   SelectInst *LSI = dyn_cast<SelectInst>(LHS);
6222cab237bSDimitry Andric   SelectInst *RSI = dyn_cast<SelectInst>(RHS);
6232cab237bSDimitry Andric   if ((LSI && hasUndefInSelect(*LSI)) || (RSI && hasUndefInSelect(*RSI)))
6242cab237bSDimitry Andric     return true;
6252cab237bSDimitry Andric   return false;
6262cab237bSDimitry Andric }
6272cab237bSDimitry Andric 
6287d523365SDimitry Andric /// Do actual work and unswitch loop if possible and profitable.
processCurrentLoop()629f22ef01cSRoman Divacky bool LoopUnswitch::processCurrentLoop() {
630f22ef01cSRoman Divacky   bool Changed = false;
631dff0c46cSDimitry Andric 
632dff0c46cSDimitry Andric   initLoopData();
633dff0c46cSDimitry Andric 
634dff0c46cSDimitry Andric   // If LoopSimplify was unable to form a preheader, don't do any unswitching.
635dff0c46cSDimitry Andric   if (!loopPreheader)
636dff0c46cSDimitry Andric     return false;
637dff0c46cSDimitry Andric 
638dff0c46cSDimitry Andric   // Loops with indirectbr cannot be cloned.
639dff0c46cSDimitry Andric   if (!currentLoop->isSafeToClone())
640dff0c46cSDimitry Andric     return false;
641dff0c46cSDimitry Andric 
642dff0c46cSDimitry Andric   // Without dedicated exits, splitting the exit edge may fail.
643dff0c46cSDimitry Andric   if (!currentLoop->hasDedicatedExits())
644dff0c46cSDimitry Andric     return false;
645dff0c46cSDimitry Andric 
646dff0c46cSDimitry Andric   LLVMContext &Context = loopHeader->getContext();
647dff0c46cSDimitry Andric 
6487d523365SDimitry Andric   // Analyze loop cost, and stop unswitching if loop content can not be duplicated.
649ff0cc061SDimitry Andric   if (!BranchesInfo.countLoop(
650ff0cc061SDimitry Andric           currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
651ff0cc061SDimitry Andric                            *currentLoop->getHeader()->getParent()),
65239d628a0SDimitry Andric           AC))
653dff0c46cSDimitry Andric     return false;
654f22ef01cSRoman Divacky 
6557d523365SDimitry Andric   // Try trivial unswitch first before loop over other basic blocks in the loop.
6567d523365SDimitry Andric   if (TryTrivialLoopUnswitch(Changed)) {
6577d523365SDimitry Andric     return true;
6587d523365SDimitry Andric   }
6597d523365SDimitry Andric 
6604ba319b5SDimitry Andric   // Do not do non-trivial unswitch while optimizing for size.
6614ba319b5SDimitry Andric   // FIXME: Use Function::optForSize().
6624ba319b5SDimitry Andric   if (OptimizeForSize ||
6634ba319b5SDimitry Andric       loopHeader->getParent()->hasFnAttribute(Attribute::OptimizeForSize))
6644ba319b5SDimitry Andric     return false;
6654ba319b5SDimitry Andric 
6663ca95b02SDimitry Andric   // Run through the instructions in the loop, keeping track of three things:
6673ca95b02SDimitry Andric   //
6683ca95b02SDimitry Andric   //  - That we do not unswitch loops containing convergent operations, as we
6693ca95b02SDimitry Andric   //    might be making them control dependent on the unswitch value when they
6703ca95b02SDimitry Andric   //    were not before.
6717d523365SDimitry Andric   //    FIXME: This could be refined to only bail if the convergent operation is
6727d523365SDimitry Andric   //    not already control-dependent on the unswitch value.
6733ca95b02SDimitry Andric   //
6743ca95b02SDimitry Andric   //  - That basic blocks in the loop contain invokes whose predecessor edges we
6753ca95b02SDimitry Andric   //    cannot split.
6763ca95b02SDimitry Andric   //
6773ca95b02SDimitry Andric   //  - The set of guard intrinsics encountered (these are non terminator
6783ca95b02SDimitry Andric   //    instructions that are also profitable to be unswitched).
6793ca95b02SDimitry Andric 
6803ca95b02SDimitry Andric   SmallVector<IntrinsicInst *, 4> Guards;
6813ca95b02SDimitry Andric 
6827d523365SDimitry Andric   for (const auto BB : currentLoop->blocks()) {
6837d523365SDimitry Andric     for (auto &I : *BB) {
6847d523365SDimitry Andric       auto CS = CallSite(&I);
6857d523365SDimitry Andric       if (!CS) continue;
6867d523365SDimitry Andric       if (CS.hasFnAttr(Attribute::Convergent))
6877d523365SDimitry Andric         return false;
6883ca95b02SDimitry Andric       if (auto *II = dyn_cast<InvokeInst>(&I))
6893ca95b02SDimitry Andric         if (!II->getUnwindDest()->canSplitPredecessors())
6903ca95b02SDimitry Andric           return false;
6913ca95b02SDimitry Andric       if (auto *II = dyn_cast<IntrinsicInst>(&I))
6923ca95b02SDimitry Andric         if (II->getIntrinsicID() == Intrinsic::experimental_guard)
6933ca95b02SDimitry Andric           Guards.push_back(II);
6947d523365SDimitry Andric     }
6957d523365SDimitry Andric   }
6967d523365SDimitry Andric 
6973ca95b02SDimitry Andric   for (IntrinsicInst *Guard : Guards) {
6983ca95b02SDimitry Andric     Value *LoopCond =
6997a7e6055SDimitry Andric         FindLIVLoopCondition(Guard->getOperand(0), currentLoop, Changed).first;
7003ca95b02SDimitry Andric     if (LoopCond &&
7013ca95b02SDimitry Andric         UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context))) {
7023ca95b02SDimitry Andric       // NB! Unswitching (if successful) could have erased some of the
7033ca95b02SDimitry Andric       // instructions in Guards leaving dangling pointers there.  This is fine
7043ca95b02SDimitry Andric       // because we're returning now, and won't look at Guards again.
7053ca95b02SDimitry Andric       ++NumGuards;
7063ca95b02SDimitry Andric       return true;
7073ca95b02SDimitry Andric     }
7083ca95b02SDimitry Andric   }
7093ca95b02SDimitry Andric 
710f22ef01cSRoman Divacky   // Loop over all of the basic blocks in the loop.  If we find an interior
711f22ef01cSRoman Divacky   // block that is branching on a loop-invariant condition, we can unswitch this
712f22ef01cSRoman Divacky   // loop.
713f22ef01cSRoman Divacky   for (Loop::block_iterator I = currentLoop->block_begin(),
714f22ef01cSRoman Divacky          E = currentLoop->block_end(); I != E; ++I) {
715*b5893f02SDimitry Andric     Instruction *TI = (*I)->getTerminator();
7163ca95b02SDimitry Andric 
7173ca95b02SDimitry Andric     // Unswitching on a potentially uninitialized predicate is not
7183ca95b02SDimitry Andric     // MSan-friendly. Limit this to the cases when the original predicate is
7193ca95b02SDimitry Andric     // guaranteed to execute, to avoid creating a use-of-uninitialized-value
7203ca95b02SDimitry Andric     // in the code that did not have one.
7213ca95b02SDimitry Andric     // This is a workaround for the discrepancy between LLVM IR and MSan
7223ca95b02SDimitry Andric     // semantics. See PR28054 for more details.
7233ca95b02SDimitry Andric     if (SanitizeMemory &&
724*b5893f02SDimitry Andric         !SafetyInfo.isGuaranteedToExecute(*TI, DT, currentLoop))
7253ca95b02SDimitry Andric       continue;
7263ca95b02SDimitry Andric 
727f22ef01cSRoman Divacky     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
728d88c1a5aSDimitry Andric       // Some branches may be rendered unreachable because of previous
729d88c1a5aSDimitry Andric       // unswitching.
730d88c1a5aSDimitry Andric       // Unswitch only those branches that are reachable.
731d88c1a5aSDimitry Andric       if (isUnreachableDueToPreviousUnswitching(*I))
732d88c1a5aSDimitry Andric         continue;
733d88c1a5aSDimitry Andric 
734f22ef01cSRoman Divacky       // If this isn't branching on an invariant condition, we can't unswitch
735f22ef01cSRoman Divacky       // it.
736f22ef01cSRoman Divacky       if (BI->isConditional()) {
737f22ef01cSRoman Divacky         // See if this, or some part of it, is loop invariant.  If so, we can
738f22ef01cSRoman Divacky         // unswitch on it if we desire.
739f22ef01cSRoman Divacky         Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
7407a7e6055SDimitry Andric                                                currentLoop, Changed).first;
7412cab237bSDimitry Andric         if (LoopCond && !EqualityPropUnSafe(*LoopCond) &&
7423dac3a9bSDimitry Andric             UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context), TI)) {
743f22ef01cSRoman Divacky           ++NumBranches;
744f22ef01cSRoman Divacky           return true;
745f22ef01cSRoman Divacky         }
746f22ef01cSRoman Divacky       }
747f22ef01cSRoman Divacky     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
7487a7e6055SDimitry Andric       Value *SC = SI->getCondition();
7497a7e6055SDimitry Andric       Value *LoopCond;
7507a7e6055SDimitry Andric       OperatorChain OpChain;
7517a7e6055SDimitry Andric       std::tie(LoopCond, OpChain) =
7527a7e6055SDimitry Andric         FindLIVLoopCondition(SC, currentLoop, Changed);
7537a7e6055SDimitry Andric 
754dff0c46cSDimitry Andric       unsigned NumCases = SI->getNumCases();
755dff0c46cSDimitry Andric       if (LoopCond && NumCases) {
756f22ef01cSRoman Divacky         // Find a value to unswitch on:
757f22ef01cSRoman Divacky         // FIXME: this should chose the most expensive case!
758bd5abe19SDimitry Andric         // FIXME: scan for a case with a non-critical edge?
75991bc56edSDimitry Andric         Constant *UnswitchVal = nullptr;
7607a7e6055SDimitry Andric         // Find a case value such that at least one case value is unswitched
7617a7e6055SDimitry Andric         // out.
7627a7e6055SDimitry Andric         if (OpChain == OC_OpChainAnd) {
7637a7e6055SDimitry Andric           // If the chain only has ANDs and the switch has a case value of 0.
7647a7e6055SDimitry Andric           // Dropping in a 0 to the chain will unswitch out the 0-casevalue.
7657a7e6055SDimitry Andric           auto *AllZero = cast<ConstantInt>(Constant::getNullValue(SC->getType()));
7667a7e6055SDimitry Andric           if (BranchesInfo.isUnswitched(SI, AllZero))
7677a7e6055SDimitry Andric             continue;
7687a7e6055SDimitry Andric           // We are unswitching 0 out.
7697a7e6055SDimitry Andric           UnswitchVal = AllZero;
7707a7e6055SDimitry Andric         } else if (OpChain == OC_OpChainOr) {
7717a7e6055SDimitry Andric           // If the chain only has ORs and the switch has a case value of ~0.
7727a7e6055SDimitry Andric           // Dropping in a ~0 to the chain will unswitch out the ~0-casevalue.
7737a7e6055SDimitry Andric           auto *AllOne = cast<ConstantInt>(Constant::getAllOnesValue(SC->getType()));
7747a7e6055SDimitry Andric           if (BranchesInfo.isUnswitched(SI, AllOne))
7757a7e6055SDimitry Andric             continue;
7767a7e6055SDimitry Andric           // We are unswitching ~0 out.
7777a7e6055SDimitry Andric           UnswitchVal = AllOne;
7787a7e6055SDimitry Andric         } else {
7797a7e6055SDimitry Andric           assert(OpChain == OC_OpChainNone &&
7807a7e6055SDimitry Andric                  "Expect to unswitch on trivial chain");
781f22ef01cSRoman Divacky           // Do not process same value again and again.
782dff0c46cSDimitry Andric           // At this point we have some cases already unswitched and
783dff0c46cSDimitry Andric           // some not yet unswitched. Let's find the first not yet unswitched one.
7847a7e6055SDimitry Andric           for (auto Case : SI->cases()) {
7857a7e6055SDimitry Andric             Constant *UnswitchValCandidate = Case.getCaseValue();
786dff0c46cSDimitry Andric             if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
787dff0c46cSDimitry Andric               UnswitchVal = UnswitchValCandidate;
788dff0c46cSDimitry Andric               break;
789dff0c46cSDimitry Andric             }
790dff0c46cSDimitry Andric           }
7917a7e6055SDimitry Andric         }
792dff0c46cSDimitry Andric 
793dff0c46cSDimitry Andric         if (!UnswitchVal)
794f22ef01cSRoman Divacky           continue;
795f22ef01cSRoman Divacky 
796f22ef01cSRoman Divacky         if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
797f22ef01cSRoman Divacky           ++NumSwitches;
7987a7e6055SDimitry Andric           // In case of a full LIV, UnswitchVal is the value we unswitched out.
7997a7e6055SDimitry Andric           // In case of a partial LIV, we only unswitch when its an AND-chain
8007a7e6055SDimitry Andric           // or OR-chain. In both cases switch input value simplifies to
8017a7e6055SDimitry Andric           // UnswitchVal.
8027a7e6055SDimitry Andric           BranchesInfo.setUnswitched(SI, UnswitchVal);
803f22ef01cSRoman Divacky           return true;
804f22ef01cSRoman Divacky         }
805f22ef01cSRoman Divacky       }
806f22ef01cSRoman Divacky     }
807f22ef01cSRoman Divacky 
808f22ef01cSRoman Divacky     // Scan the instructions to check for unswitchable values.
809f22ef01cSRoman Divacky     for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
810f22ef01cSRoman Divacky          BBI != E; ++BBI)
811f22ef01cSRoman Divacky       if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
812f22ef01cSRoman Divacky         Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
8137a7e6055SDimitry Andric                                                currentLoop, Changed).first;
814f22ef01cSRoman Divacky         if (LoopCond && UnswitchIfProfitable(LoopCond,
815f22ef01cSRoman Divacky                                              ConstantInt::getTrue(Context))) {
816f22ef01cSRoman Divacky           ++NumSelects;
817f22ef01cSRoman Divacky           return true;
818f22ef01cSRoman Divacky         }
819f22ef01cSRoman Divacky       }
820f22ef01cSRoman Divacky   }
821f22ef01cSRoman Divacky   return Changed;
822f22ef01cSRoman Divacky }
823f22ef01cSRoman Divacky 
8247d523365SDimitry Andric /// Check to see if all paths from BB exit the loop with no side effects
8257d523365SDimitry Andric /// (including infinite loops).
826f22ef01cSRoman Divacky ///
827e580952dSDimitry Andric /// If true, we return true and set ExitBB to the block we
828f22ef01cSRoman Divacky /// exit through.
829f22ef01cSRoman Divacky ///
isTrivialLoopExitBlockHelper(Loop * L,BasicBlock * BB,BasicBlock * & ExitBB,std::set<BasicBlock * > & Visited)830f22ef01cSRoman Divacky static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
831f22ef01cSRoman Divacky                                          BasicBlock *&ExitBB,
832f22ef01cSRoman Divacky                                          std::set<BasicBlock*> &Visited) {
833f22ef01cSRoman Divacky   if (!Visited.insert(BB).second) {
834dff0c46cSDimitry Andric     // Already visited. Without more analysis, this could indicate an infinite
835dff0c46cSDimitry Andric     // loop.
836e580952dSDimitry Andric     return false;
837f785676fSDimitry Andric   }
838f785676fSDimitry Andric   if (!L->contains(BB)) {
839f22ef01cSRoman Divacky     // Otherwise, this is a loop exit, this is fine so long as this is the
840f22ef01cSRoman Divacky     // first exit.
84191bc56edSDimitry Andric     if (ExitBB) return false;
842f22ef01cSRoman Divacky     ExitBB = BB;
843f22ef01cSRoman Divacky     return true;
844f22ef01cSRoman Divacky   }
845f22ef01cSRoman Divacky 
846f22ef01cSRoman Divacky   // Otherwise, this is an unvisited intra-loop node.  Check all successors.
847f22ef01cSRoman Divacky   for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
848f22ef01cSRoman Divacky     // Check to see if the successor is a trivial loop exit.
849f22ef01cSRoman Divacky     if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
850f22ef01cSRoman Divacky       return false;
851f22ef01cSRoman Divacky   }
852f22ef01cSRoman Divacky 
853f22ef01cSRoman Divacky   // Okay, everything after this looks good, check to make sure that this block
854f22ef01cSRoman Divacky   // doesn't include any side effects.
8553ca95b02SDimitry Andric   for (Instruction &I : *BB)
8563ca95b02SDimitry Andric     if (I.mayHaveSideEffects())
857f22ef01cSRoman Divacky       return false;
858f22ef01cSRoman Divacky 
859f22ef01cSRoman Divacky   return true;
860f22ef01cSRoman Divacky }
861f22ef01cSRoman Divacky 
8627d523365SDimitry Andric /// Return true if the specified block unconditionally leads to an exit from
8637d523365SDimitry Andric /// the specified loop, and has no side-effects in the process. If so, return
8647d523365SDimitry Andric /// the block that is exited to, otherwise return null.
isTrivialLoopExitBlock(Loop * L,BasicBlock * BB)865f22ef01cSRoman Divacky static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
866f22ef01cSRoman Divacky   std::set<BasicBlock*> Visited;
867e580952dSDimitry Andric   Visited.insert(L->getHeader());  // Branches to header make infinite loops.
86891bc56edSDimitry Andric   BasicBlock *ExitBB = nullptr;
869f22ef01cSRoman Divacky   if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
870f22ef01cSRoman Divacky     return ExitBB;
87191bc56edSDimitry Andric   return nullptr;
872f22ef01cSRoman Divacky }
873f22ef01cSRoman Divacky 
8747d523365SDimitry Andric /// We have found that we can unswitch currentLoop when LoopCond == Val to
8757d523365SDimitry Andric /// simplify the loop.  If we decide that this is profitable,
876f22ef01cSRoman Divacky /// unswitch the loop, reprocess the pieces, then return true.
UnswitchIfProfitable(Value * LoopCond,Constant * Val,Instruction * TI)8773dac3a9bSDimitry Andric bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,
878*b5893f02SDimitry Andric                                         Instruction *TI) {
879f22ef01cSRoman Divacky   // Check to see if it would be profitable to unswitch current loop.
8803dac3a9bSDimitry Andric   if (!BranchesInfo.CostAllowsUnswitching()) {
8814ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "NOT unswitching loop %"
8823dac3a9bSDimitry Andric                       << currentLoop->getHeader()->getName()
8833dac3a9bSDimitry Andric                       << " at non-trivial condition '" << *Val
8843dac3a9bSDimitry Andric                       << "' == " << *LoopCond << "\n"
8853dac3a9bSDimitry Andric                       << ". Cost too high.\n");
8863dac3a9bSDimitry Andric     return false;
8873dac3a9bSDimitry Andric   }
8887a7e6055SDimitry Andric   if (hasBranchDivergence &&
889*b5893f02SDimitry Andric       getAnalysis<LegacyDivergenceAnalysis>().isDivergent(LoopCond)) {
8904ba319b5SDimitry Andric     LLVM_DEBUG(dbgs() << "NOT unswitching loop %"
8917a7e6055SDimitry Andric                       << currentLoop->getHeader()->getName()
8927a7e6055SDimitry Andric                       << " at non-trivial condition '" << *Val
8937a7e6055SDimitry Andric                       << "' == " << *LoopCond << "\n"
8947a7e6055SDimitry Andric                       << ". Condition is divergent.\n");
8957a7e6055SDimitry Andric     return false;
8967a7e6055SDimitry Andric   }
897f22ef01cSRoman Divacky 
8983dac3a9bSDimitry Andric   UnswitchNontrivialCondition(LoopCond, Val, currentLoop, TI);
899f22ef01cSRoman Divacky   return true;
900f22ef01cSRoman Divacky }
901f22ef01cSRoman Divacky 
9027d523365SDimitry Andric /// Recursively clone the specified loop and all of its children,
903f22ef01cSRoman Divacky /// mapping the blocks with the specified map.
CloneLoop(Loop * L,Loop * PL,ValueToValueMapTy & VM,LoopInfo * LI,LPPassManager * LPM)9042754fe60SDimitry Andric static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
905f22ef01cSRoman Divacky                        LoopInfo *LI, LPPassManager *LPM) {
9062cab237bSDimitry Andric   Loop &New = *LI->AllocateLoop();
907302affcbSDimitry Andric   if (PL)
908302affcbSDimitry Andric     PL->addChildLoop(&New);
909302affcbSDimitry Andric   else
910302affcbSDimitry Andric     LI->addTopLevelLoop(&New);
911302affcbSDimitry Andric   LPM->addLoop(New);
912f22ef01cSRoman Divacky 
913f22ef01cSRoman Divacky   // Add all of the blocks in L to the new loop.
914f22ef01cSRoman Divacky   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
915f22ef01cSRoman Divacky        I != E; ++I)
916f22ef01cSRoman Divacky     if (LI->getLoopFor(*I) == L)
9177d523365SDimitry Andric       New.addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
918f22ef01cSRoman Divacky 
919f22ef01cSRoman Divacky   // Add all of the subloops to the new loop.
9203ca95b02SDimitry Andric   for (Loop *I : *L)
9213ca95b02SDimitry Andric     CloneLoop(I, &New, VM, LI, LPM);
922f22ef01cSRoman Divacky 
9237d523365SDimitry Andric   return &New;
924f22ef01cSRoman Divacky }
925f22ef01cSRoman Divacky 
9267d523365SDimitry Andric /// Emit a conditional branch on two values if LIC == Val, branch to TrueDst,
9272cab237bSDimitry Andric /// otherwise branch to FalseDest. Insert the code immediately before OldBranch
9282cab237bSDimitry Andric /// and remove (but not erase!) it from the function.
EmitPreheaderBranchOnCondition(Value * LIC,Constant * Val,BasicBlock * TrueDest,BasicBlock * FalseDest,BranchInst * OldBranch,Instruction * TI)929f22ef01cSRoman Divacky void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
930f22ef01cSRoman Divacky                                                   BasicBlock *TrueDest,
931f22ef01cSRoman Divacky                                                   BasicBlock *FalseDest,
9322cab237bSDimitry Andric                                                   BranchInst *OldBranch,
933*b5893f02SDimitry Andric                                                   Instruction *TI) {
9342cab237bSDimitry Andric   assert(OldBranch->isUnconditional() && "Preheader is not split correctly");
9354ba319b5SDimitry Andric   assert(TrueDest != FalseDest && "Branch targets should be different");
936f22ef01cSRoman Divacky   // Insert a conditional branch on LIC to the two preheaders.  The original
937f22ef01cSRoman Divacky   // code is the true version and the new code is the false version.
938f22ef01cSRoman Divacky   Value *BranchVal = LIC;
9393dac3a9bSDimitry Andric   bool Swapped = false;
940f22ef01cSRoman Divacky   if (!isa<ConstantInt>(Val) ||
941f22ef01cSRoman Divacky       Val->getType() != Type::getInt1Ty(LIC->getContext()))
9422cab237bSDimitry Andric     BranchVal = new ICmpInst(OldBranch, ICmpInst::ICMP_EQ, LIC, Val);
9433dac3a9bSDimitry Andric   else if (Val != ConstantInt::getTrue(Val->getContext())) {
944f22ef01cSRoman Divacky     // We want to enter the new loop when the condition is true.
945f22ef01cSRoman Divacky     std::swap(TrueDest, FalseDest);
9463dac3a9bSDimitry Andric     Swapped = true;
9473dac3a9bSDimitry Andric   }
948f22ef01cSRoman Divacky 
9492cab237bSDimitry Andric   // Old branch will be removed, so save its parent and successor to update the
9502cab237bSDimitry Andric   // DomTree.
9512cab237bSDimitry Andric   auto *OldBranchSucc = OldBranch->getSuccessor(0);
9522cab237bSDimitry Andric   auto *OldBranchParent = OldBranch->getParent();
9532cab237bSDimitry Andric 
954f22ef01cSRoman Divacky   // Insert the new branch.
955d88c1a5aSDimitry Andric   BranchInst *BI =
9562cab237bSDimitry Andric       IRBuilder<>(OldBranch).CreateCondBr(BranchVal, TrueDest, FalseDest, TI);
957d88c1a5aSDimitry Andric   if (Swapped)
958d88c1a5aSDimitry Andric     BI->swapProfMetadata();
959f22ef01cSRoman Divacky 
9602cab237bSDimitry Andric   // Remove the old branch so there is only one branch at the end. This is
9612cab237bSDimitry Andric   // needed to perform DomTree's internal DFS walk on the function's CFG.
9622cab237bSDimitry Andric   OldBranch->removeFromParent();
9632cab237bSDimitry Andric 
9642cab237bSDimitry Andric   // Inform the DT about the new branch.
9652cab237bSDimitry Andric   if (DT) {
9662cab237bSDimitry Andric     // First, add both successors.
9672cab237bSDimitry Andric     SmallVector<DominatorTree::UpdateType, 3> Updates;
9684ba319b5SDimitry Andric     if (TrueDest != OldBranchSucc)
9692cab237bSDimitry Andric       Updates.push_back({DominatorTree::Insert, OldBranchParent, TrueDest});
9704ba319b5SDimitry Andric     if (FalseDest != OldBranchSucc)
9712cab237bSDimitry Andric       Updates.push_back({DominatorTree::Insert, OldBranchParent, FalseDest});
9722cab237bSDimitry Andric     // If both of the new successors are different from the old one, inform the
9732cab237bSDimitry Andric     // DT that the edge was deleted.
9742cab237bSDimitry Andric     if (OldBranchSucc != TrueDest && OldBranchSucc != FalseDest) {
9752cab237bSDimitry Andric       Updates.push_back({DominatorTree::Delete, OldBranchParent, OldBranchSucc});
9762cab237bSDimitry Andric     }
9772cab237bSDimitry Andric     DT->applyUpdates(Updates);
978*b5893f02SDimitry Andric 
979*b5893f02SDimitry Andric     if (MSSAU)
980*b5893f02SDimitry Andric       MSSAU->applyUpdates(Updates, *DT);
9812cab237bSDimitry Andric   }
9822cab237bSDimitry Andric 
983f22ef01cSRoman Divacky   // If either edge is critical, split it. This helps preserve LoopSimplify
984f22ef01cSRoman Divacky   // form for enclosing loops.
985*b5893f02SDimitry Andric   auto Options =
986*b5893f02SDimitry Andric       CriticalEdgeSplittingOptions(DT, LI, MSSAU.get()).setPreserveLCSSA();
987ff0cc061SDimitry Andric   SplitCriticalEdge(BI, 0, Options);
988ff0cc061SDimitry Andric   SplitCriticalEdge(BI, 1, Options);
989f22ef01cSRoman Divacky }
990f22ef01cSRoman Divacky 
9917d523365SDimitry Andric /// Given a loop that has a trivial unswitchable condition in it (a cond branch
9927d523365SDimitry Andric /// from its header block to its latch block, where the path through the loop
9937d523365SDimitry Andric /// that doesn't execute its body has no side-effects), unswitch it. This
9947d523365SDimitry Andric /// doesn't involve any code duplication, just moving the conditional branch
9957d523365SDimitry Andric /// outside of the loop and updating loop info.
UnswitchTrivialCondition(Loop * L,Value * Cond,Constant * Val,BasicBlock * ExitBlock,Instruction * TI)9963dac3a9bSDimitry Andric void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
9973dac3a9bSDimitry Andric                                             BasicBlock *ExitBlock,
998*b5893f02SDimitry Andric                                             Instruction *TI) {
9994ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
1000f22ef01cSRoman Divacky                     << loopHeader->getName() << " [" << L->getBlocks().size()
10013dac3a9bSDimitry Andric                     << " blocks] in Function "
10024ba319b5SDimitry Andric                     << L->getHeader()->getParent()->getName()
10034ba319b5SDimitry Andric                     << " on cond: " << *Val << " == " << *Cond << "\n");
10044ba319b5SDimitry Andric   // We are going to make essential changes to CFG. This may invalidate cached
10054ba319b5SDimitry Andric   // information for L or one of its parent loops in SCEV.
10064ba319b5SDimitry Andric   if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
10074ba319b5SDimitry Andric     SEWP->getSE().forgetTopmostLoop(L);
1008f22ef01cSRoman Divacky 
1009f22ef01cSRoman Divacky   // First step, split the preheader, so that we know that there is a safe place
1010f22ef01cSRoman Divacky   // to insert the conditional branch.  We will change loopPreheader to have a
1011f22ef01cSRoman Divacky   // conditional branch on Cond.
1012*b5893f02SDimitry Andric   BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, DT, LI, MSSAU.get());
1013f22ef01cSRoman Divacky 
1014f22ef01cSRoman Divacky   // Now that we have a place to insert the conditional branch, create a place
1015f22ef01cSRoman Divacky   // to branch to: this is the exit block out of the loop that we should
1016f22ef01cSRoman Divacky   // short-circuit to.
1017f22ef01cSRoman Divacky 
1018f22ef01cSRoman Divacky   // Split this block now, so that the loop maintains its exit block, and so
1019f22ef01cSRoman Divacky   // that the jump from the preheader can execute the contents of the exit block
1020f22ef01cSRoman Divacky   // without actually branching to it (the exit block should be dominated by the
1021f22ef01cSRoman Divacky   // loop header, not the preheader).
1022f22ef01cSRoman Divacky   assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
1023*b5893f02SDimitry Andric   BasicBlock *NewExit =
1024*b5893f02SDimitry Andric       SplitBlock(ExitBlock, &ExitBlock->front(), DT, LI, MSSAU.get());
1025f22ef01cSRoman Divacky 
1026f22ef01cSRoman Divacky   // Okay, now we have a position to branch from and a position to branch to,
1027f22ef01cSRoman Divacky   // insert the new conditional branch.
10282cab237bSDimitry Andric   auto *OldBranch = dyn_cast<BranchInst>(loopPreheader->getTerminator());
10292cab237bSDimitry Andric   assert(OldBranch && "Failed to split the preheader");
10302cab237bSDimitry Andric   EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH, OldBranch, TI);
10312cab237bSDimitry Andric   LPM->deleteSimpleAnalysisValue(OldBranch, L);
10322cab237bSDimitry Andric 
10332cab237bSDimitry Andric   // EmitPreheaderBranchOnCondition removed the OldBranch from the function.
10342cab237bSDimitry Andric   // Delete it, as it is no longer needed.
10352cab237bSDimitry Andric   delete OldBranch;
1036f22ef01cSRoman Divacky 
1037f22ef01cSRoman Divacky   // We need to reprocess this loop, it could be unswitched again.
1038f22ef01cSRoman Divacky   redoLoop = true;
1039f22ef01cSRoman Divacky 
1040f22ef01cSRoman Divacky   // Now that we know that the loop is never entered when this condition is a
1041f22ef01cSRoman Divacky   // particular value, rewrite the loop with this info.  We know that this will
1042f22ef01cSRoman Divacky   // at least eliminate the old branch.
1043f22ef01cSRoman Divacky   RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
1044*b5893f02SDimitry Andric 
1045f22ef01cSRoman Divacky   ++NumTrivial;
1046f22ef01cSRoman Divacky }
1047f22ef01cSRoman Divacky 
10487d523365SDimitry Andric /// Check if the first non-constant condition starting from the loop header is
10497d523365SDimitry Andric /// a trivial unswitch condition: that is, a condition controls whether or not
10507d523365SDimitry Andric /// the loop does anything at all. If it is a trivial condition, unswitching
10517d523365SDimitry Andric /// produces no code duplications (equivalently, it produces a simpler loop and
10527d523365SDimitry Andric /// a new empty loop, which gets deleted). Therefore always unswitch trivial
10537d523365SDimitry Andric /// condition.
TryTrivialLoopUnswitch(bool & Changed)10547d523365SDimitry Andric bool LoopUnswitch::TryTrivialLoopUnswitch(bool &Changed) {
10557d523365SDimitry Andric   BasicBlock *CurrentBB = currentLoop->getHeader();
1056*b5893f02SDimitry Andric   Instruction *CurrentTerm = CurrentBB->getTerminator();
10577d523365SDimitry Andric   LLVMContext &Context = CurrentBB->getContext();
10587d523365SDimitry Andric 
10597d523365SDimitry Andric   // If loop header has only one reachable successor (currently via an
10607d523365SDimitry Andric   // unconditional branch or constant foldable conditional branch, but
10617d523365SDimitry Andric   // should also consider adding constant foldable switch instruction in
10627d523365SDimitry Andric   // future), we should keep looking for trivial condition candidates in
10637d523365SDimitry Andric   // the successor as well. An alternative is to constant fold conditions
10647d523365SDimitry Andric   // and merge successors into loop header (then we only need to check header's
10657d523365SDimitry Andric   // terminator). The reason for not doing this in LoopUnswitch pass is that
10667d523365SDimitry Andric   // it could potentially break LoopPassManager's invariants. Folding dead
10677d523365SDimitry Andric   // branches could either eliminate the current loop or make other loops
10687d523365SDimitry Andric   // unreachable. LCSSA form might also not be preserved after deleting
10697d523365SDimitry Andric   // branches. The following code keeps traversing loop header's successors
10707d523365SDimitry Andric   // until it finds the trivial condition candidate (condition that is not a
10717d523365SDimitry Andric   // constant). Since unswitching generates branches with constant conditions,
10727d523365SDimitry Andric   // this scenario could be very common in practice.
10734ba319b5SDimitry Andric   SmallPtrSet<BasicBlock*, 8> Visited;
10747d523365SDimitry Andric 
10757d523365SDimitry Andric   while (true) {
10767d523365SDimitry Andric     // If we exit loop or reach a previous visited block, then
10777d523365SDimitry Andric     // we can not reach any trivial condition candidates (unfoldable
10787d523365SDimitry Andric     // branch instructions or switch instructions) and no unswitch
10797d523365SDimitry Andric     // can happen. Exit and return false.
10807d523365SDimitry Andric     if (!currentLoop->contains(CurrentBB) || !Visited.insert(CurrentBB).second)
10817d523365SDimitry Andric       return false;
10827d523365SDimitry Andric 
10837d523365SDimitry Andric     // Check if this loop will execute any side-effecting instructions (e.g.
10847d523365SDimitry Andric     // stores, calls, volatile loads) in the part of the loop that the code
10857d523365SDimitry Andric     // *would* execute. Check the header first.
10867d523365SDimitry Andric     for (Instruction &I : *CurrentBB)
10877d523365SDimitry Andric       if (I.mayHaveSideEffects())
10887d523365SDimitry Andric         return false;
10897d523365SDimitry Andric 
10907d523365SDimitry Andric     if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
10917d523365SDimitry Andric       if (BI->isUnconditional()) {
10927d523365SDimitry Andric         CurrentBB = BI->getSuccessor(0);
10937d523365SDimitry Andric       } else if (BI->getCondition() == ConstantInt::getTrue(Context)) {
10947d523365SDimitry Andric         CurrentBB = BI->getSuccessor(0);
10957d523365SDimitry Andric       } else if (BI->getCondition() == ConstantInt::getFalse(Context)) {
10967d523365SDimitry Andric         CurrentBB = BI->getSuccessor(1);
10977d523365SDimitry Andric       } else {
10987d523365SDimitry Andric         // Found a trivial condition candidate: non-foldable conditional branch.
10997d523365SDimitry Andric         break;
11007d523365SDimitry Andric       }
11017a7e6055SDimitry Andric     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
11027a7e6055SDimitry Andric       // At this point, any constant-foldable instructions should have probably
11037a7e6055SDimitry Andric       // been folded.
11047a7e6055SDimitry Andric       ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
11057a7e6055SDimitry Andric       if (!Cond)
11067a7e6055SDimitry Andric         break;
11077a7e6055SDimitry Andric       // Find the target block we are definitely going to.
11087a7e6055SDimitry Andric       CurrentBB = SI->findCaseValue(Cond)->getCaseSuccessor();
11097d523365SDimitry Andric     } else {
11107a7e6055SDimitry Andric       // We do not understand these terminator instructions.
11117d523365SDimitry Andric       break;
11127d523365SDimitry Andric     }
11137d523365SDimitry Andric 
11147d523365SDimitry Andric     CurrentTerm = CurrentBB->getTerminator();
11157d523365SDimitry Andric   }
11167d523365SDimitry Andric 
11177d523365SDimitry Andric   // CondVal is the condition that controls the trivial condition.
11187d523365SDimitry Andric   // LoopExitBB is the BasicBlock that loop exits when meets trivial condition.
11197d523365SDimitry Andric   Constant *CondVal = nullptr;
11207d523365SDimitry Andric   BasicBlock *LoopExitBB = nullptr;
11217d523365SDimitry Andric 
11227d523365SDimitry Andric   if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
11237d523365SDimitry Andric     // If this isn't branching on an invariant condition, we can't unswitch it.
11247d523365SDimitry Andric     if (!BI->isConditional())
11257d523365SDimitry Andric       return false;
11267d523365SDimitry Andric 
11277d523365SDimitry Andric     Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
11287a7e6055SDimitry Andric                                            currentLoop, Changed).first;
11297d523365SDimitry Andric 
11307d523365SDimitry Andric     // Unswitch only if the trivial condition itself is an LIV (not
11317d523365SDimitry Andric     // partial LIV which could occur in and/or)
11327d523365SDimitry Andric     if (!LoopCond || LoopCond != BI->getCondition())
11337d523365SDimitry Andric       return false;
11347d523365SDimitry Andric 
11357d523365SDimitry Andric     // Check to see if a successor of the branch is guaranteed to
11367d523365SDimitry Andric     // exit through a unique exit block without having any
11377d523365SDimitry Andric     // side-effects.  If so, determine the value of Cond that causes
11387d523365SDimitry Andric     // it to do this.
11397d523365SDimitry Andric     if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
11407d523365SDimitry Andric                                              BI->getSuccessor(0)))) {
11417d523365SDimitry Andric       CondVal = ConstantInt::getTrue(Context);
11427d523365SDimitry Andric     } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
11437d523365SDimitry Andric                                                     BI->getSuccessor(1)))) {
11447d523365SDimitry Andric       CondVal = ConstantInt::getFalse(Context);
11457d523365SDimitry Andric     }
11467d523365SDimitry Andric 
11477d523365SDimitry Andric     // If we didn't find a single unique LoopExit block, or if the loop exit
11487d523365SDimitry Andric     // block contains phi nodes, this isn't trivial.
11497d523365SDimitry Andric     if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
11507d523365SDimitry Andric       return false;   // Can't handle this.
11517d523365SDimitry Andric 
11522cab237bSDimitry Andric     if (EqualityPropUnSafe(*LoopCond))
11532cab237bSDimitry Andric       return false;
11542cab237bSDimitry Andric 
11557d523365SDimitry Andric     UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
11567d523365SDimitry Andric                              CurrentTerm);
11577d523365SDimitry Andric     ++NumBranches;
11587d523365SDimitry Andric     return true;
11597d523365SDimitry Andric   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
11607d523365SDimitry Andric     // If this isn't switching on an invariant condition, we can't unswitch it.
11617d523365SDimitry Andric     Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
11627a7e6055SDimitry Andric                                            currentLoop, Changed).first;
11637d523365SDimitry Andric 
11647d523365SDimitry Andric     // Unswitch only if the trivial condition itself is an LIV (not
11657d523365SDimitry Andric     // partial LIV which could occur in and/or)
11667d523365SDimitry Andric     if (!LoopCond || LoopCond != SI->getCondition())
11677d523365SDimitry Andric       return false;
11687d523365SDimitry Andric 
11697d523365SDimitry Andric     // Check to see if a successor of the switch is guaranteed to go to the
11707d523365SDimitry Andric     // latch block or exit through a one exit block without having any
11717d523365SDimitry Andric     // side-effects.  If so, determine the value of Cond that causes it to do
11727d523365SDimitry Andric     // this.
11737d523365SDimitry Andric     // Note that we can't trivially unswitch on the default case or
11747d523365SDimitry Andric     // on already unswitched cases.
11757a7e6055SDimitry Andric     for (auto Case : SI->cases()) {
11767d523365SDimitry Andric       BasicBlock *LoopExitCandidate;
11777a7e6055SDimitry Andric       if ((LoopExitCandidate =
11787a7e6055SDimitry Andric                isTrivialLoopExitBlock(currentLoop, Case.getCaseSuccessor()))) {
11797d523365SDimitry Andric         // Okay, we found a trivial case, remember the value that is trivial.
11807a7e6055SDimitry Andric         ConstantInt *CaseVal = Case.getCaseValue();
11817d523365SDimitry Andric 
11827d523365SDimitry Andric         // Check that it was not unswitched before, since already unswitched
11837d523365SDimitry Andric         // trivial vals are looks trivial too.
11847d523365SDimitry Andric         if (BranchesInfo.isUnswitched(SI, CaseVal))
11857d523365SDimitry Andric           continue;
11867d523365SDimitry Andric         LoopExitBB = LoopExitCandidate;
11877d523365SDimitry Andric         CondVal = CaseVal;
11887d523365SDimitry Andric         break;
11897d523365SDimitry Andric       }
11907d523365SDimitry Andric     }
11917d523365SDimitry Andric 
11927d523365SDimitry Andric     // If we didn't find a single unique LoopExit block, or if the loop exit
11937d523365SDimitry Andric     // block contains phi nodes, this isn't trivial.
11947d523365SDimitry Andric     if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
11957d523365SDimitry Andric       return false;   // Can't handle this.
11967d523365SDimitry Andric 
11977d523365SDimitry Andric     UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
11987d523365SDimitry Andric                              nullptr);
11997a7e6055SDimitry Andric 
12007a7e6055SDimitry Andric     // We are only unswitching full LIV.
12017a7e6055SDimitry Andric     BranchesInfo.setUnswitched(SI, CondVal);
12027d523365SDimitry Andric     ++NumSwitches;
12037d523365SDimitry Andric     return true;
12047d523365SDimitry Andric   }
12057d523365SDimitry Andric   return false;
12067d523365SDimitry Andric }
12077d523365SDimitry Andric 
12087d523365SDimitry Andric /// Split all of the edges from inside the loop to their exit blocks.
12097d523365SDimitry Andric /// Update the appropriate Phi nodes as we do so.
SplitExitEdges(Loop * L,const SmallVectorImpl<BasicBlock * > & ExitBlocks)1210f22ef01cSRoman Divacky void LoopUnswitch::SplitExitEdges(Loop *L,
1211f785676fSDimitry Andric                                const SmallVectorImpl<BasicBlock *> &ExitBlocks){
1212f22ef01cSRoman Divacky 
1213f22ef01cSRoman Divacky   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
1214f22ef01cSRoman Divacky     BasicBlock *ExitBlock = ExitBlocks[i];
1215f22ef01cSRoman Divacky     SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
1216f22ef01cSRoman Divacky                                        pred_end(ExitBlock));
12176122f3e6SDimitry Andric 
1218bd5abe19SDimitry Andric     // Although SplitBlockPredecessors doesn't preserve loop-simplify in
1219bd5abe19SDimitry Andric     // general, if we call it on all predecessors of all exits then it does.
1220*b5893f02SDimitry Andric     SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", DT, LI, MSSAU.get(),
1221ff0cc061SDimitry Andric                            /*PreserveLCSSA*/ true);
1222f22ef01cSRoman Divacky   }
1223f22ef01cSRoman Divacky }
1224f22ef01cSRoman Divacky 
12257d523365SDimitry Andric /// We determined that the loop is profitable to unswitch when LIC equal Val.
12267d523365SDimitry Andric /// Split it into loop versions and test the condition outside of either loop.
12277d523365SDimitry Andric /// Return the loops created as Out1/Out2.
UnswitchNontrivialCondition(Value * LIC,Constant * Val,Loop * L,Instruction * TI)1228f22ef01cSRoman Divacky void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
1229*b5893f02SDimitry Andric                                                Loop *L, Instruction *TI) {
1230f22ef01cSRoman Divacky   Function *F = loopHeader->getParent();
12314ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
1232f22ef01cSRoman Divacky                     << loopHeader->getName() << " [" << L->getBlocks().size()
12334ba319b5SDimitry Andric                     << " blocks] in Function " << F->getName() << " when '"
12344ba319b5SDimitry Andric                     << *Val << "' == " << *LIC << "\n");
1235f22ef01cSRoman Divacky 
12364ba319b5SDimitry Andric   // We are going to make essential changes to CFG. This may invalidate cached
12374ba319b5SDimitry Andric   // information for L or one of its parent loops in SCEV.
12387d523365SDimitry Andric   if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
12394ba319b5SDimitry Andric     SEWP->getSE().forgetTopmostLoop(L);
12402754fe60SDimitry Andric 
1241f22ef01cSRoman Divacky   LoopBlocks.clear();
1242f22ef01cSRoman Divacky   NewBlocks.clear();
1243f22ef01cSRoman Divacky 
1244f22ef01cSRoman Divacky   // First step, split the preheader and exit blocks, and add these blocks to
1245f22ef01cSRoman Divacky   // the LoopBlocks list.
1246*b5893f02SDimitry Andric   BasicBlock *NewPreheader =
1247*b5893f02SDimitry Andric       SplitEdge(loopPreheader, loopHeader, DT, LI, MSSAU.get());
1248f22ef01cSRoman Divacky   LoopBlocks.push_back(NewPreheader);
1249f22ef01cSRoman Divacky 
1250f22ef01cSRoman Divacky   // We want the loop to come after the preheader, but before the exit blocks.
1251f22ef01cSRoman Divacky   LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
1252f22ef01cSRoman Divacky 
1253f22ef01cSRoman Divacky   SmallVector<BasicBlock*, 8> ExitBlocks;
1254f22ef01cSRoman Divacky   L->getUniqueExitBlocks(ExitBlocks);
1255f22ef01cSRoman Divacky 
1256f22ef01cSRoman Divacky   // Split all of the edges from inside the loop to their exit blocks.  Update
1257f22ef01cSRoman Divacky   // the appropriate Phi nodes as we do so.
1258f22ef01cSRoman Divacky   SplitExitEdges(L, ExitBlocks);
1259f22ef01cSRoman Divacky 
1260f22ef01cSRoman Divacky   // The exit blocks may have been changed due to edge splitting, recompute.
1261f22ef01cSRoman Divacky   ExitBlocks.clear();
1262f22ef01cSRoman Divacky   L->getUniqueExitBlocks(ExitBlocks);
1263f22ef01cSRoman Divacky 
1264f22ef01cSRoman Divacky   // Add exit blocks to the loop blocks.
1265f22ef01cSRoman Divacky   LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
1266f22ef01cSRoman Divacky 
1267f22ef01cSRoman Divacky   // Next step, clone all of the basic blocks that make up the loop (including
1268f22ef01cSRoman Divacky   // the loop preheader and exit blocks), keeping track of the mapping between
1269f22ef01cSRoman Divacky   // the instructions and blocks.
1270f22ef01cSRoman Divacky   NewBlocks.reserve(LoopBlocks.size());
12712754fe60SDimitry Andric   ValueToValueMapTy VMap;
1272f22ef01cSRoman Divacky   for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
1273ffd1746dSEd Schouten     BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
1274dff0c46cSDimitry Andric 
1275f22ef01cSRoman Divacky     NewBlocks.push_back(NewBB);
1276ffd1746dSEd Schouten     VMap[LoopBlocks[i]] = NewBB;  // Keep the BB mapping.
1277f22ef01cSRoman Divacky     LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
1278f22ef01cSRoman Divacky   }
1279f22ef01cSRoman Divacky 
1280f22ef01cSRoman Divacky   // Splice the newly inserted blocks into the function right before the
1281f22ef01cSRoman Divacky   // original preheader.
12827d523365SDimitry Andric   F->getBasicBlockList().splice(NewPreheader->getIterator(),
12837d523365SDimitry Andric                                 F->getBasicBlockList(),
12847d523365SDimitry Andric                                 NewBlocks[0]->getIterator(), F->end());
1285f22ef01cSRoman Divacky 
1286f22ef01cSRoman Divacky   // Now we create the new Loop object for the versioned loop.
1287ffd1746dSEd Schouten   Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
1288dff0c46cSDimitry Andric 
1289dff0c46cSDimitry Andric   // Recalculate unswitching quota, inherit simplified switches info for NewBB,
1290dff0c46cSDimitry Andric   // Probably clone more loop-unswitch related loop properties.
1291dff0c46cSDimitry Andric   BranchesInfo.cloneData(NewLoop, L, VMap);
1292dff0c46cSDimitry Andric 
1293f22ef01cSRoman Divacky   Loop *ParentLoop = L->getParentLoop();
1294f22ef01cSRoman Divacky   if (ParentLoop) {
1295f22ef01cSRoman Divacky     // Make sure to add the cloned preheader and exit blocks to the parent loop
1296f22ef01cSRoman Divacky     // as well.
1297ff0cc061SDimitry Andric     ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
1298f22ef01cSRoman Divacky   }
1299f22ef01cSRoman Divacky 
1300f22ef01cSRoman Divacky   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
1301ffd1746dSEd Schouten     BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
1302f22ef01cSRoman Divacky     // The new exit block should be in the same loop as the old one.
1303f22ef01cSRoman Divacky     if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
1304ff0cc061SDimitry Andric       ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
1305f22ef01cSRoman Divacky 
1306f22ef01cSRoman Divacky     assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
1307f22ef01cSRoman Divacky            "Exit block should have been split to have one successor!");
1308f22ef01cSRoman Divacky     BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
1309f22ef01cSRoman Divacky 
1310f22ef01cSRoman Divacky     // If the successor of the exit block had PHI nodes, add an entry for
1311f22ef01cSRoman Divacky     // NewExit.
131230785c0eSDimitry Andric     for (PHINode &PN : ExitSucc->phis()) {
131330785c0eSDimitry Andric       Value *V = PN.getIncomingValueForBlock(ExitBlocks[i]);
13142754fe60SDimitry Andric       ValueToValueMapTy::iterator It = VMap.find(V);
1315ffd1746dSEd Schouten       if (It != VMap.end()) V = It->second;
131630785c0eSDimitry Andric       PN.addIncoming(V, NewExit);
1317f22ef01cSRoman Divacky     }
13186122f3e6SDimitry Andric 
13196122f3e6SDimitry Andric     if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
1320f785676fSDimitry Andric       PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
13217d523365SDimitry Andric                                     &*ExitSucc->getFirstInsertionPt());
13226122f3e6SDimitry Andric 
13236122f3e6SDimitry Andric       for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
13246122f3e6SDimitry Andric            I != E; ++I) {
13256122f3e6SDimitry Andric         BasicBlock *BB = *I;
13266122f3e6SDimitry Andric         LandingPadInst *LPI = BB->getLandingPadInst();
13276122f3e6SDimitry Andric         LPI->replaceAllUsesWith(PN);
13286122f3e6SDimitry Andric         PN->addIncoming(LPI, BB);
13296122f3e6SDimitry Andric       }
13306122f3e6SDimitry Andric     }
1331f22ef01cSRoman Divacky   }
1332f22ef01cSRoman Divacky 
1333f22ef01cSRoman Divacky   // Rewrite the code to refer to itself.
1334d88c1a5aSDimitry Andric   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
1335d88c1a5aSDimitry Andric     for (Instruction &I : *NewBlocks[i]) {
13363ca95b02SDimitry Andric       RemapInstruction(&I, VMap,
13373ca95b02SDimitry Andric                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1338d88c1a5aSDimitry Andric       if (auto *II = dyn_cast<IntrinsicInst>(&I))
1339d88c1a5aSDimitry Andric         if (II->getIntrinsicID() == Intrinsic::assume)
1340d88c1a5aSDimitry Andric           AC->registerAssumption(II);
1341d88c1a5aSDimitry Andric     }
1342d88c1a5aSDimitry Andric   }
1343f22ef01cSRoman Divacky 
1344f22ef01cSRoman Divacky   // Rewrite the original preheader to select between versions of the loop.
1345f22ef01cSRoman Divacky   BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
1346f22ef01cSRoman Divacky   assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
1347f22ef01cSRoman Divacky          "Preheader splitting did not work correctly!");
1348f22ef01cSRoman Divacky 
1349*b5893f02SDimitry Andric   if (MSSAU) {
1350*b5893f02SDimitry Andric     // Update MemorySSA after cloning, and before splitting to unreachables,
1351*b5893f02SDimitry Andric     // since that invalidates the 1:1 mapping of clones in VMap.
1352*b5893f02SDimitry Andric     LoopBlocksRPO LBRPO(L);
1353*b5893f02SDimitry Andric     LBRPO.perform(LI);
1354*b5893f02SDimitry Andric     MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, VMap);
1355*b5893f02SDimitry Andric   }
1356*b5893f02SDimitry Andric 
1357f22ef01cSRoman Divacky   // Emit the new branch that selects between the two versions of this loop.
13583dac3a9bSDimitry Andric   EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
13593dac3a9bSDimitry Andric                                  TI);
1360f22ef01cSRoman Divacky   LPM->deleteSimpleAnalysisValue(OldBR, L);
1361*b5893f02SDimitry Andric   if (MSSAU) {
1362*b5893f02SDimitry Andric     // Update MemoryPhis in Exit blocks.
1363*b5893f02SDimitry Andric     MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMap, *DT);
1364*b5893f02SDimitry Andric     if (VerifyMemorySSA)
1365*b5893f02SDimitry Andric       MSSA->verifyMemorySSA();
1366*b5893f02SDimitry Andric   }
13672cab237bSDimitry Andric 
13682cab237bSDimitry Andric   // The OldBr was replaced by a new one and removed (but not erased) by
13692cab237bSDimitry Andric   // EmitPreheaderBranchOnCondition. It is no longer needed, so delete it.
13702cab237bSDimitry Andric   delete OldBR;
1371f22ef01cSRoman Divacky 
1372f22ef01cSRoman Divacky   LoopProcessWorklist.push_back(NewLoop);
1373f22ef01cSRoman Divacky   redoLoop = true;
1374f22ef01cSRoman Divacky 
1375f37b6182SDimitry Andric   // Keep a WeakTrackingVH holding onto LIC.  If the first call to
1376f37b6182SDimitry Andric   // RewriteLoopBody
1377f22ef01cSRoman Divacky   // deletes the instruction (for example by simplifying a PHI that feeds into
1378f22ef01cSRoman Divacky   // the condition that we're unswitching on), we don't rewrite the second
1379f22ef01cSRoman Divacky   // iteration.
1380f37b6182SDimitry Andric   WeakTrackingVH LICHandle(LIC);
1381f22ef01cSRoman Divacky 
1382f22ef01cSRoman Divacky   // Now we rewrite the original code to know that the condition is true and the
1383f22ef01cSRoman Divacky   // new code to know that the condition is false.
1384f22ef01cSRoman Divacky   RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
1385f22ef01cSRoman Divacky 
1386f22ef01cSRoman Divacky   // It's possible that simplifying one loop could cause the other to be
1387f22ef01cSRoman Divacky   // changed to another value or a constant.  If its a constant, don't simplify
1388f22ef01cSRoman Divacky   // it.
1389f22ef01cSRoman Divacky   if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
1390f22ef01cSRoman Divacky       LICHandle && !isa<Constant>(LICHandle))
1391f22ef01cSRoman Divacky     RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
1392*b5893f02SDimitry Andric 
1393*b5893f02SDimitry Andric   if (MSSA && VerifyMemorySSA)
1394*b5893f02SDimitry Andric     MSSA->verifyMemorySSA();
1395f22ef01cSRoman Divacky }
1396f22ef01cSRoman Divacky 
13977d523365SDimitry Andric /// Remove all instances of I from the worklist vector specified.
RemoveFromWorklist(Instruction * I,std::vector<Instruction * > & Worklist)1398f22ef01cSRoman Divacky static void RemoveFromWorklist(Instruction *I,
1399f22ef01cSRoman Divacky                                std::vector<Instruction*> &Worklist) {
14003861d79fSDimitry Andric 
14013861d79fSDimitry Andric   Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
14023861d79fSDimitry Andric                  Worklist.end());
1403f22ef01cSRoman Divacky }
1404f22ef01cSRoman Divacky 
14057d523365SDimitry Andric /// When we find that I really equals V, remove I from the
1406f22ef01cSRoman Divacky /// program, replacing all uses with V and update the worklist.
ReplaceUsesOfWith(Instruction * I,Value * V,std::vector<Instruction * > & Worklist,Loop * L,LPPassManager * LPM)1407f22ef01cSRoman Divacky static void ReplaceUsesOfWith(Instruction *I, Value *V,
1408f22ef01cSRoman Divacky                               std::vector<Instruction*> &Worklist,
1409f22ef01cSRoman Divacky                               Loop *L, LPPassManager *LPM) {
14104ba319b5SDimitry Andric   LLVM_DEBUG(dbgs() << "Replace with '" << *V << "': " << *I << "\n");
1411f22ef01cSRoman Divacky 
1412f22ef01cSRoman Divacky   // Add uses to the worklist, which may be dead now.
1413f22ef01cSRoman Divacky   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1414f22ef01cSRoman Divacky     if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1415f22ef01cSRoman Divacky       Worklist.push_back(Use);
1416f22ef01cSRoman Divacky 
1417f22ef01cSRoman Divacky   // Add users to the worklist which may be simplified now.
141891bc56edSDimitry Andric   for (User *U : I->users())
141991bc56edSDimitry Andric     Worklist.push_back(cast<Instruction>(U));
1420f22ef01cSRoman Divacky   LPM->deleteSimpleAnalysisValue(I, L);
1421f22ef01cSRoman Divacky   RemoveFromWorklist(I, Worklist);
1422f22ef01cSRoman Divacky   I->replaceAllUsesWith(V);
1423f37b6182SDimitry Andric   if (!I->mayHaveSideEffects())
1424f22ef01cSRoman Divacky     I->eraseFromParent();
1425f22ef01cSRoman Divacky   ++NumSimplify;
1426f22ef01cSRoman Divacky }
1427f22ef01cSRoman Divacky 
14287d523365SDimitry Andric /// We know either that the value LIC has the value specified by Val in the
14297d523365SDimitry Andric /// specified loop, or we know it does NOT have that value.
14307d523365SDimitry Andric /// Rewrite any uses of LIC or of properties correlated to it.
RewriteLoopBodyWithConditionConstant(Loop * L,Value * LIC,Constant * Val,bool IsEqual)1431f22ef01cSRoman Divacky void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
1432f22ef01cSRoman Divacky                                                         Constant *Val,
1433f22ef01cSRoman Divacky                                                         bool IsEqual) {
1434f22ef01cSRoman Divacky   assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
1435f22ef01cSRoman Divacky 
1436f22ef01cSRoman Divacky   // FIXME: Support correlated properties, like:
1437f22ef01cSRoman Divacky   //  for (...)
1438f22ef01cSRoman Divacky   //    if (li1 < li2)
1439f22ef01cSRoman Divacky   //      ...
1440f22ef01cSRoman Divacky   //    if (li1 > li2)
1441f22ef01cSRoman Divacky   //      ...
1442f22ef01cSRoman Divacky 
1443f22ef01cSRoman Divacky   // FOLD boolean conditions (X|LIC), (X&LIC).  Fold conditional branches,
1444f22ef01cSRoman Divacky   // selects, switches.
1445f22ef01cSRoman Divacky   std::vector<Instruction*> Worklist;
1446f22ef01cSRoman Divacky   LLVMContext &Context = Val->getContext();
1447f22ef01cSRoman Divacky 
1448f22ef01cSRoman Divacky   // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1449f22ef01cSRoman Divacky   // in the loop with the appropriate one directly.
1450f22ef01cSRoman Divacky   if (IsEqual || (isa<ConstantInt>(Val) &&
1451f22ef01cSRoman Divacky       Val->getType()->isIntegerTy(1))) {
1452f22ef01cSRoman Divacky     Value *Replacement;
1453f22ef01cSRoman Divacky     if (IsEqual)
1454f22ef01cSRoman Divacky       Replacement = Val;
1455f22ef01cSRoman Divacky     else
1456f22ef01cSRoman Divacky       Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
1457f22ef01cSRoman Divacky                                      !cast<ConstantInt>(Val)->getZExtValue());
1458f22ef01cSRoman Divacky 
145991bc56edSDimitry Andric     for (User *U : LIC->users()) {
146091bc56edSDimitry Andric       Instruction *UI = dyn_cast<Instruction>(U);
146191bc56edSDimitry Andric       if (!UI || !L->contains(UI))
1462f22ef01cSRoman Divacky         continue;
146391bc56edSDimitry Andric       Worklist.push_back(UI);
1464f22ef01cSRoman Divacky     }
1465dff0c46cSDimitry Andric 
14663ca95b02SDimitry Andric     for (Instruction *UI : Worklist)
14673ca95b02SDimitry Andric       UI->replaceUsesOfWith(LIC, Replacement);
1468dff0c46cSDimitry Andric 
1469f22ef01cSRoman Divacky     SimplifyCode(Worklist, L);
1470f22ef01cSRoman Divacky     return;
1471f22ef01cSRoman Divacky   }
1472f22ef01cSRoman Divacky 
1473f22ef01cSRoman Divacky   // Otherwise, we don't know the precise value of LIC, but we do know that it
1474f22ef01cSRoman Divacky   // is certainly NOT "Val".  As such, simplify any uses in the loop that we
1475f22ef01cSRoman Divacky   // can.  This case occurs when we unswitch switch statements.
147691bc56edSDimitry Andric   for (User *U : LIC->users()) {
147791bc56edSDimitry Andric     Instruction *UI = dyn_cast<Instruction>(U);
147891bc56edSDimitry Andric     if (!UI || !L->contains(UI))
1479f22ef01cSRoman Divacky       continue;
1480f22ef01cSRoman Divacky 
14817a7e6055SDimitry Andric     // At this point, we know LIC is definitely not Val. Try to use some simple
14827a7e6055SDimitry Andric     // logic to simplify the user w.r.t. to the context.
14837a7e6055SDimitry Andric     if (Value *Replacement = SimplifyInstructionWithNotEqual(UI, LIC, Val)) {
14847a7e6055SDimitry Andric       if (LI->replacementPreservesLCSSAForm(UI, Replacement)) {
14857a7e6055SDimitry Andric         // This in-loop instruction has been simplified w.r.t. its context,
14867a7e6055SDimitry Andric         // i.e. LIC != Val, make sure we propagate its replacement value to
14877a7e6055SDimitry Andric         // all its users.
14887a7e6055SDimitry Andric         //
14897a7e6055SDimitry Andric         // We can not yet delete UI, the LIC user, yet, because that would invalidate
14907a7e6055SDimitry Andric         // the LIC->users() iterator !. However, we can make this instruction
14917a7e6055SDimitry Andric         // dead by replacing all its users and push it onto the worklist so that
14927a7e6055SDimitry Andric         // it can be properly deleted and its operands simplified.
14937a7e6055SDimitry Andric         UI->replaceAllUsesWith(Replacement);
14947a7e6055SDimitry Andric       }
14957a7e6055SDimitry Andric     }
1496f22ef01cSRoman Divacky 
14977a7e6055SDimitry Andric     // This is a LIC user, push it into the worklist so that SimplifyCode can
14987a7e6055SDimitry Andric     // attempt to simplify it.
14997a7e6055SDimitry Andric     Worklist.push_back(UI);
1500f22ef01cSRoman Divacky 
1501f22ef01cSRoman Divacky     // If we know that LIC is not Val, use this info to simplify code.
150291bc56edSDimitry Andric     SwitchInst *SI = dyn_cast<SwitchInst>(UI);
150391bc56edSDimitry Andric     if (!SI || !isa<ConstantInt>(Val)) continue;
1504f22ef01cSRoman Divacky 
15057a7e6055SDimitry Andric     // NOTE: if a case value for the switch is unswitched out, we record it
15067a7e6055SDimitry Andric     // after the unswitch finishes. We can not record it here as the switch
15077a7e6055SDimitry Andric     // is not a direct user of the partial LIV.
15087a7e6055SDimitry Andric     SwitchInst::CaseHandle DeadCase =
15097a7e6055SDimitry Andric         *SI->findCaseValue(cast<ConstantInt>(Val));
1510dff0c46cSDimitry Andric     // Default case is live for multiple values.
15117a7e6055SDimitry Andric     if (DeadCase == *SI->case_default())
15127a7e6055SDimitry Andric       continue;
1513f22ef01cSRoman Divacky 
1514f22ef01cSRoman Divacky     // Found a dead case value.  Don't remove PHI nodes in the
1515f22ef01cSRoman Divacky     // successor if they become single-entry, those PHI nodes may
1516f22ef01cSRoman Divacky     // be in the Users list.
1517f22ef01cSRoman Divacky 
1518bd5abe19SDimitry Andric     BasicBlock *Switch = SI->getParent();
1519dff0c46cSDimitry Andric     BasicBlock *SISucc = DeadCase.getCaseSuccessor();
1520bd5abe19SDimitry Andric     BasicBlock *Latch = L->getLoopLatch();
1521dff0c46cSDimitry Andric 
1522bd5abe19SDimitry Andric     if (!SI->findCaseDest(SISucc)) continue;  // Edge is critical.
1523bd5abe19SDimitry Andric     // If the DeadCase successor dominates the loop latch, then the
1524bd5abe19SDimitry Andric     // transformation isn't safe since it will delete the sole predecessor edge
1525bd5abe19SDimitry Andric     // to the latch.
1526bd5abe19SDimitry Andric     if (Latch && DT->dominates(SISucc, Latch))
1527bd5abe19SDimitry Andric       continue;
1528bd5abe19SDimitry Andric 
1529f22ef01cSRoman Divacky     // FIXME: This is a hack.  We need to keep the successor around
1530f22ef01cSRoman Divacky     // and hooked up so as to preserve the loop structure, because
1531f22ef01cSRoman Divacky     // trying to update it is complicated.  So instead we preserve the
1532f22ef01cSRoman Divacky     // loop structure and put the block on a dead code path.
1533*b5893f02SDimitry Andric     SplitEdge(Switch, SISucc, DT, LI, MSSAU.get());
1534f22ef01cSRoman Divacky     // Compute the successors instead of relying on the return value
1535f22ef01cSRoman Divacky     // of SplitEdge, since it may have split the switch successor
1536f22ef01cSRoman Divacky     // after PHI nodes.
1537dff0c46cSDimitry Andric     BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
1538f22ef01cSRoman Divacky     BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1539f22ef01cSRoman Divacky     // Create an "unreachable" destination.
1540f22ef01cSRoman Divacky     BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1541f22ef01cSRoman Divacky                                            Switch->getParent(),
1542f22ef01cSRoman Divacky                                            OldSISucc);
1543f22ef01cSRoman Divacky     new UnreachableInst(Context, Abort);
1544f22ef01cSRoman Divacky     // Force the new case destination to branch to the "unreachable"
1545f22ef01cSRoman Divacky     // block while maintaining a (dead) CFG edge to the old block.
1546f22ef01cSRoman Divacky     NewSISucc->getTerminator()->eraseFromParent();
1547f22ef01cSRoman Divacky     BranchInst::Create(Abort, OldSISucc,
1548f22ef01cSRoman Divacky                        ConstantInt::getTrue(Context), NewSISucc);
1549f22ef01cSRoman Divacky     // Release the PHI operands for this edge.
155030785c0eSDimitry Andric     for (PHINode &PN : NewSISucc->phis())
155130785c0eSDimitry Andric       PN.setIncomingValue(PN.getBasicBlockIndex(Switch),
155230785c0eSDimitry Andric                           UndefValue::get(PN.getType()));
1553f22ef01cSRoman Divacky     // Tell the domtree about the new block. We don't fully update the
1554f22ef01cSRoman Divacky     // domtree here -- instead we force it to do a full recomputation
1555f22ef01cSRoman Divacky     // after the pass is complete -- but we do need to inform it of
1556f22ef01cSRoman Divacky     // new blocks.
1557f22ef01cSRoman Divacky     DT->addNewBlock(Abort, NewSISucc);
1558f22ef01cSRoman Divacky   }
1559f22ef01cSRoman Divacky 
1560f22ef01cSRoman Divacky   SimplifyCode(Worklist, L);
1561f22ef01cSRoman Divacky }
1562f22ef01cSRoman Divacky 
15637d523365SDimitry Andric /// Now that we have simplified some instructions in the loop, walk over it and
15647d523365SDimitry Andric /// constant prop, dce, and fold control flow where possible. Note that this is
15657d523365SDimitry Andric /// effectively a very simple loop-structure-aware optimizer. During processing
15667d523365SDimitry Andric /// of this loop, L could very well be deleted, so it must not be used.
1567f22ef01cSRoman Divacky ///
1568f22ef01cSRoman Divacky /// FIXME: When the loop optimizer is more mature, separate this out to a new
1569f22ef01cSRoman Divacky /// pass.
1570f22ef01cSRoman Divacky ///
SimplifyCode(std::vector<Instruction * > & Worklist,Loop * L)1571f22ef01cSRoman Divacky void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
1572ff0cc061SDimitry Andric   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
1573f22ef01cSRoman Divacky   while (!Worklist.empty()) {
1574f22ef01cSRoman Divacky     Instruction *I = Worklist.back();
1575f22ef01cSRoman Divacky     Worklist.pop_back();
1576f22ef01cSRoman Divacky 
1577f22ef01cSRoman Divacky     // Simple DCE.
1578f22ef01cSRoman Divacky     if (isInstructionTriviallyDead(I)) {
15794ba319b5SDimitry Andric       LLVM_DEBUG(dbgs() << "Remove dead instruction '" << *I << "\n");
1580f22ef01cSRoman Divacky 
1581f22ef01cSRoman Divacky       // Add uses to the worklist, which may be dead now.
1582f22ef01cSRoman Divacky       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1583f22ef01cSRoman Divacky         if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1584f22ef01cSRoman Divacky           Worklist.push_back(Use);
1585f22ef01cSRoman Divacky       LPM->deleteSimpleAnalysisValue(I, L);
1586f22ef01cSRoman Divacky       RemoveFromWorklist(I, Worklist);
1587*b5893f02SDimitry Andric       if (MSSAU)
1588*b5893f02SDimitry Andric         MSSAU->removeMemoryAccess(I);
1589f22ef01cSRoman Divacky       I->eraseFromParent();
1590f22ef01cSRoman Divacky       ++NumSimplify;
1591f22ef01cSRoman Divacky       continue;
1592f22ef01cSRoman Divacky     }
1593f22ef01cSRoman Divacky 
1594f22ef01cSRoman Divacky     // See if instruction simplification can hack this up.  This is common for
1595f22ef01cSRoman Divacky     // things like "select false, X, Y" after unswitching made the condition be
15967ae0e2c9SDimitry Andric     // 'false'.  TODO: update the domtree properly so we can pass it here.
1597ff0cc061SDimitry Andric     if (Value *V = SimplifyInstruction(I, DL))
15982754fe60SDimitry Andric       if (LI->replacementPreservesLCSSAForm(I, V)) {
1599f22ef01cSRoman Divacky         ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1600f22ef01cSRoman Divacky         continue;
1601f22ef01cSRoman Divacky       }
1602f22ef01cSRoman Divacky 
1603f22ef01cSRoman Divacky     // Special case hacks that appear commonly in unswitched code.
1604f22ef01cSRoman Divacky     if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1605f22ef01cSRoman Divacky       if (BI->isUnconditional()) {
1606f22ef01cSRoman Divacky         // If BI's parent is the only pred of the successor, fold the two blocks
1607f22ef01cSRoman Divacky         // together.
1608f22ef01cSRoman Divacky         BasicBlock *Pred = BI->getParent();
1609f22ef01cSRoman Divacky         BasicBlock *Succ = BI->getSuccessor(0);
1610f22ef01cSRoman Divacky         BasicBlock *SinglePred = Succ->getSinglePredecessor();
1611f22ef01cSRoman Divacky         if (!SinglePred) continue;  // Nothing to do.
1612f22ef01cSRoman Divacky         assert(SinglePred == Pred && "CFG broken");
1613f22ef01cSRoman Divacky 
16144ba319b5SDimitry Andric         LLVM_DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
1615f22ef01cSRoman Divacky                           << Succ->getName() << "\n");
1616f22ef01cSRoman Divacky 
1617f22ef01cSRoman Divacky         // Resolve any single entry PHI nodes in Succ.
1618f22ef01cSRoman Divacky         while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1619f22ef01cSRoman Divacky           ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
1620f22ef01cSRoman Divacky 
162117a519f9SDimitry Andric         // If Succ has any successors with PHI nodes, update them to have
162217a519f9SDimitry Andric         // entries coming from Pred instead of Succ.
162317a519f9SDimitry Andric         Succ->replaceAllUsesWith(Pred);
162417a519f9SDimitry Andric 
1625f22ef01cSRoman Divacky         // Move all of the successor contents from Succ to Pred.
16267d523365SDimitry Andric         Pred->getInstList().splice(BI->getIterator(), Succ->getInstList(),
16277d523365SDimitry Andric                                    Succ->begin(), Succ->end());
1628*b5893f02SDimitry Andric         if (MSSAU)
1629*b5893f02SDimitry Andric           MSSAU->moveAllAfterMergeBlocks(Succ, Pred, BI);
1630f22ef01cSRoman Divacky         LPM->deleteSimpleAnalysisValue(BI, L);
1631f22ef01cSRoman Divacky         RemoveFromWorklist(BI, Worklist);
163224e2fe98SDimitry Andric         BI->eraseFromParent();
1633f22ef01cSRoman Divacky 
1634f22ef01cSRoman Divacky         // Remove Succ from the loop tree.
1635f22ef01cSRoman Divacky         LI->removeBlock(Succ);
1636f22ef01cSRoman Divacky         LPM->deleteSimpleAnalysisValue(Succ, L);
1637f22ef01cSRoman Divacky         Succ->eraseFromParent();
1638f22ef01cSRoman Divacky         ++NumSimplify;
1639f22ef01cSRoman Divacky         continue;
1640f22ef01cSRoman Divacky       }
1641f22ef01cSRoman Divacky 
1642f22ef01cSRoman Divacky       continue;
1643f22ef01cSRoman Divacky     }
1644f22ef01cSRoman Divacky   }
1645f22ef01cSRoman Divacky }
16467a7e6055SDimitry Andric 
16477a7e6055SDimitry Andric /// Simple simplifications we can do given the information that Cond is
16487a7e6055SDimitry Andric /// definitely not equal to Val.
SimplifyInstructionWithNotEqual(Instruction * Inst,Value * Invariant,Constant * Val)16497a7e6055SDimitry Andric Value *LoopUnswitch::SimplifyInstructionWithNotEqual(Instruction *Inst,
16507a7e6055SDimitry Andric                                                      Value *Invariant,
16517a7e6055SDimitry Andric                                                      Constant *Val) {
16527a7e6055SDimitry Andric   // icmp eq cond, val -> false
16537a7e6055SDimitry Andric   ICmpInst *CI = dyn_cast<ICmpInst>(Inst);
16547a7e6055SDimitry Andric   if (CI && CI->isEquality()) {
16557a7e6055SDimitry Andric     Value *Op0 = CI->getOperand(0);
16567a7e6055SDimitry Andric     Value *Op1 = CI->getOperand(1);
16577a7e6055SDimitry Andric     if ((Op0 == Invariant && Op1 == Val) || (Op0 == Val && Op1 == Invariant)) {
16587a7e6055SDimitry Andric       LLVMContext &Ctx = Inst->getContext();
16597a7e6055SDimitry Andric       if (CI->getPredicate() == CmpInst::ICMP_EQ)
16607a7e6055SDimitry Andric         return ConstantInt::getFalse(Ctx);
16617a7e6055SDimitry Andric       else
16627a7e6055SDimitry Andric         return ConstantInt::getTrue(Ctx);
16637a7e6055SDimitry Andric      }
16647a7e6055SDimitry Andric   }
16657a7e6055SDimitry Andric 
16667a7e6055SDimitry Andric   // FIXME: there may be other opportunities, e.g. comparison with floating
16677a7e6055SDimitry Andric   // point, or Invariant - Val != 0, etc.
16687a7e6055SDimitry Andric   return nullptr;
16697a7e6055SDimitry Andric }
1670