[PM/AA] Remove all of the dead AliasAnalysis pointers being threaded
[oota-llvm.git] / lib / Transforms / Scalar / LoopUnswitch.cpp
1 //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass transforms loops that contain branches on loop-invariant conditions
11 // to have multiple loops.  For example, it turns the left into the right code:
12 //
13 //  for (...)                  if (lic)
14 //    A                          for (...)
15 //    if (lic)                     A; B; C
16 //      B                      else
17 //    C                          for (...)
18 //                                 A; C
19 //
20 // This can increase the size of the code exponentially (doubling it every time
21 // a loop is unswitched) so we only unswitch if the resultant code will be
22 // smaller than a threshold.
23 //
24 // This pass expects LICM to be run before it to hoist invariant conditions out
25 // of the loop, to make the unswitching opportunity obvious.
26 //
27 //===----------------------------------------------------------------------===//
28
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Analysis/AssumptionCache.h"
34 #include "llvm/Analysis/CodeMetrics.h"
35 #include "llvm/Analysis/InstructionSimplify.h"
36 #include "llvm/Analysis/LoopInfo.h"
37 #include "llvm/Analysis/LoopPass.h"
38 #include "llvm/Analysis/ScalarEvolution.h"
39 #include "llvm/Analysis/TargetTransformInfo.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Dominators.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/IR/MDBuilder.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
51 #include "llvm/Transforms/Utils/Cloning.h"
52 #include "llvm/Transforms/Utils/Local.h"
53 #include <algorithm>
54 #include <map>
55 #include <set>
56 using namespace llvm;
57
58 #define DEBUG_TYPE "loop-unswitch"
59
60 STATISTIC(NumBranches, "Number of branches unswitched");
61 STATISTIC(NumSwitches, "Number of switches unswitched");
62 STATISTIC(NumSelects , "Number of selects unswitched");
63 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
64 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
65 STATISTIC(TotalInsts,  "Total number of instructions analyzed");
66
67 // The specific value of 100 here was chosen based only on intuition and a
68 // few specific examples.
69 static cl::opt<unsigned>
70 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
71           cl::init(100), cl::Hidden);
72
73 namespace {
74
75   class LUAnalysisCache {
76
77     typedef DenseMap<const SwitchInst*, SmallPtrSet<const Value *, 8> >
78       UnswitchedValsMap;
79
80     typedef UnswitchedValsMap::iterator UnswitchedValsIt;
81
82     struct LoopProperties {
83       unsigned CanBeUnswitchedCount;
84       unsigned WasUnswitchedCount;
85       unsigned SizeEstimation;
86       UnswitchedValsMap UnswitchedVals;
87     };
88
89     // Here we use std::map instead of DenseMap, since we need to keep valid
90     // LoopProperties pointer for current loop for better performance.
91     typedef std::map<const Loop*, LoopProperties> LoopPropsMap;
92     typedef LoopPropsMap::iterator LoopPropsMapIt;
93
94     LoopPropsMap LoopsProperties;
95     UnswitchedValsMap *CurLoopInstructions;
96     LoopProperties *CurrentLoopProperties;
97
98     // A loop unswitching with an estimated cost above this threshold
99     // is not performed. MaxSize is turned into unswitching quota for
100     // the current loop, and reduced correspondingly, though note that
101     // the quota is returned by releaseMemory() when the loop has been
102     // processed, so that MaxSize will return to its previous
103     // value. So in most cases MaxSize will equal the Threshold flag
104     // when a new loop is processed. An exception to that is that
105     // MaxSize will have a smaller value while processing nested loops
106     // that were introduced due to loop unswitching of an outer loop.
107     //
108     // FIXME: The way that MaxSize works is subtle and depends on the
109     // pass manager processing loops and calling releaseMemory() in a
110     // specific order. It would be good to find a more straightforward
111     // way of doing what MaxSize does.
112     unsigned MaxSize;
113
114   public:
115     LUAnalysisCache()
116         : CurLoopInstructions(nullptr), CurrentLoopProperties(nullptr),
117           MaxSize(Threshold) {}
118
119     // Analyze loop. Check its size, calculate is it possible to unswitch
120     // it. Returns true if we can unswitch this loop.
121     bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
122                    AssumptionCache *AC);
123
124     // Clean all data related to given loop.
125     void forgetLoop(const Loop *L);
126
127     // Mark case value as unswitched.
128     // Since SI instruction can be partly unswitched, in order to avoid
129     // extra unswitching in cloned loops keep track all unswitched values.
130     void setUnswitched(const SwitchInst *SI, const Value *V);
131
132     // Check was this case value unswitched before or not.
133     bool isUnswitched(const SwitchInst *SI, const Value *V);
134
135     // Returns true if another unswitching could be done within the cost
136     // threshold.
137     bool CostAllowsUnswitching();
138
139     // Clone all loop-unswitch related loop properties.
140     // Redistribute unswitching quotas.
141     // Note, that new loop data is stored inside the VMap.
142     void cloneData(const Loop *NewLoop, const Loop *OldLoop,
143                    const ValueToValueMapTy &VMap);
144   };
145
146   class LoopUnswitch : public LoopPass {
147     LoopInfo *LI;  // Loop information
148     LPPassManager *LPM;
149     AssumptionCache *AC;
150
151     // LoopProcessWorklist - Used to check if second loop needs processing
152     // after RewriteLoopBodyWithConditionConstant rewrites first loop.
153     std::vector<Loop*> LoopProcessWorklist;
154
155     LUAnalysisCache BranchesInfo;
156
157     bool OptimizeForSize;
158     bool redoLoop;
159
160     Loop *currentLoop;
161     DominatorTree *DT;
162     BasicBlock *loopHeader;
163     BasicBlock *loopPreheader;
164
165     // LoopBlocks contains all of the basic blocks of the loop, including the
166     // preheader of the loop, the body of the loop, and the exit blocks of the
167     // loop, in that order.
168     std::vector<BasicBlock*> LoopBlocks;
169     // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
170     std::vector<BasicBlock*> NewBlocks;
171
172   public:
173     static char ID; // Pass ID, replacement for typeid
174     explicit LoopUnswitch(bool Os = false) :
175       LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
176       currentLoop(nullptr), DT(nullptr), loopHeader(nullptr),
177       loopPreheader(nullptr) {
178         initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
179       }
180
181     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
182     bool processCurrentLoop();
183
184     /// This transformation requires natural loop information & requires that
185     /// loop preheaders be inserted into the CFG.
186     ///
187     void getAnalysisUsage(AnalysisUsage &AU) const override {
188       AU.addRequired<AssumptionCacheTracker>();
189       AU.addRequiredID(LoopSimplifyID);
190       AU.addPreservedID(LoopSimplifyID);
191       AU.addRequired<LoopInfoWrapperPass>();
192       AU.addPreserved<LoopInfoWrapperPass>();
193       AU.addRequiredID(LCSSAID);
194       AU.addPreservedID(LCSSAID);
195       AU.addPreserved<DominatorTreeWrapperPass>();
196       AU.addPreserved<ScalarEvolution>();
197       AU.addRequired<TargetTransformInfoWrapperPass>();
198     }
199
200   private:
201
202     void releaseMemory() override {
203       BranchesInfo.forgetLoop(currentLoop);
204     }
205
206     void initLoopData() {
207       loopHeader = currentLoop->getHeader();
208       loopPreheader = currentLoop->getLoopPreheader();
209     }
210
211     /// Split all of the edges from inside the loop to their exit blocks.
212     /// Update the appropriate Phi nodes as we do so.
213     void SplitExitEdges(Loop *L, const SmallVectorImpl<BasicBlock *> &ExitBlocks);
214
215     bool TryTrivialLoopUnswitch(bool &Changed);
216
217     bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,
218                               TerminatorInst *TI = nullptr);
219     void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
220                                   BasicBlock *ExitBlock, TerminatorInst *TI);
221     void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L,
222                                      TerminatorInst *TI);
223
224     void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
225                                               Constant *Val, bool isEqual);
226
227     void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
228                                         BasicBlock *TrueDest,
229                                         BasicBlock *FalseDest,
230                                         Instruction *InsertPt,
231                                         TerminatorInst *TI);
232
233     void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
234   };
235 }
236
237 // Analyze loop. Check its size, calculate is it possible to unswitch
238 // it. Returns true if we can unswitch this loop.
239 bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
240                                 AssumptionCache *AC) {
241
242   LoopPropsMapIt PropsIt;
243   bool Inserted;
244   std::tie(PropsIt, Inserted) =
245       LoopsProperties.insert(std::make_pair(L, LoopProperties()));
246
247   LoopProperties &Props = PropsIt->second;
248
249   if (Inserted) {
250     // New loop.
251
252     // Limit the number of instructions to avoid causing significant code
253     // expansion, and the number of basic blocks, to avoid loops with
254     // large numbers of branches which cause loop unswitching to go crazy.
255     // This is a very ad-hoc heuristic.
256
257     SmallPtrSet<const Value *, 32> EphValues;
258     CodeMetrics::collectEphemeralValues(L, AC, EphValues);
259
260     // FIXME: This is overly conservative because it does not take into
261     // consideration code simplification opportunities and code that can
262     // be shared by the resultant unswitched loops.
263     CodeMetrics Metrics;
264     for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
265          ++I)
266       Metrics.analyzeBasicBlock(*I, TTI, EphValues);
267
268     Props.SizeEstimation = Metrics.NumInsts;
269     Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
270     Props.WasUnswitchedCount = 0;
271     MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
272
273     if (Metrics.notDuplicatable) {
274       DEBUG(dbgs() << "NOT unswitching loop %"
275                    << L->getHeader()->getName() << ", contents cannot be "
276                    << "duplicated!\n");
277       return false;
278     }
279   }
280
281   // Be careful. This links are good only before new loop addition.
282   CurrentLoopProperties = &Props;
283   CurLoopInstructions = &Props.UnswitchedVals;
284
285   return true;
286 }
287
288 // Clean all data related to given loop.
289 void LUAnalysisCache::forgetLoop(const Loop *L) {
290
291   LoopPropsMapIt LIt = LoopsProperties.find(L);
292
293   if (LIt != LoopsProperties.end()) {
294     LoopProperties &Props = LIt->second;
295     MaxSize += (Props.CanBeUnswitchedCount + Props.WasUnswitchedCount) *
296                Props.SizeEstimation;
297     LoopsProperties.erase(LIt);
298   }
299
300   CurrentLoopProperties = nullptr;
301   CurLoopInstructions = nullptr;
302 }
303
304 // Mark case value as unswitched.
305 // Since SI instruction can be partly unswitched, in order to avoid
306 // extra unswitching in cloned loops keep track all unswitched values.
307 void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
308   (*CurLoopInstructions)[SI].insert(V);
309 }
310
311 // Check was this case value unswitched before or not.
312 bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
313   return (*CurLoopInstructions)[SI].count(V);
314 }
315
316 bool LUAnalysisCache::CostAllowsUnswitching() {
317   return CurrentLoopProperties->CanBeUnswitchedCount > 0;
318 }
319
320 // Clone all loop-unswitch related loop properties.
321 // Redistribute unswitching quotas.
322 // Note, that new loop data is stored inside the VMap.
323 void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
324                                 const ValueToValueMapTy &VMap) {
325
326   LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
327   LoopProperties &OldLoopProps = *CurrentLoopProperties;
328   UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
329
330   // Reallocate "can-be-unswitched quota"
331
332   --OldLoopProps.CanBeUnswitchedCount;
333   ++OldLoopProps.WasUnswitchedCount;
334   NewLoopProps.WasUnswitchedCount = 0;
335   unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
336   NewLoopProps.CanBeUnswitchedCount = Quota / 2;
337   OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
338
339   NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
340
341   // Clone unswitched values info:
342   // for new loop switches we clone info about values that was
343   // already unswitched and has redundant successors.
344   for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
345     const SwitchInst *OldInst = I->first;
346     Value *NewI = VMap.lookup(OldInst);
347     const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
348     assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
349
350     NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
351   }
352 }
353
354 char LoopUnswitch::ID = 0;
355 INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
356                       false, false)
357 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
358 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
359 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
360 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
361 INITIALIZE_PASS_DEPENDENCY(LCSSA)
362 INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
363                       false, false)
364
365 Pass *llvm::createLoopUnswitchPass(bool Os) {
366   return new LoopUnswitch(Os);
367 }
368
369 /// FindLIVLoopCondition - Cond is a condition that occurs in L.  If it is
370 /// invariant in the loop, or has an invariant piece, return the invariant.
371 /// Otherwise, return null.
372 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
373
374   // We started analyze new instruction, increment scanned instructions counter.
375   ++TotalInsts;
376
377   // We can never unswitch on vector conditions.
378   if (Cond->getType()->isVectorTy())
379     return nullptr;
380
381   // Constants should be folded, not unswitched on!
382   if (isa<Constant>(Cond)) return nullptr;
383
384   // TODO: Handle: br (VARIANT|INVARIANT).
385
386   // Hoist simple values out.
387   if (L->makeLoopInvariant(Cond, Changed))
388     return Cond;
389
390   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
391     if (BO->getOpcode() == Instruction::And ||
392         BO->getOpcode() == Instruction::Or) {
393       // If either the left or right side is invariant, we can unswitch on this,
394       // which will cause the branch to go away in one loop and the condition to
395       // simplify in the other one.
396       if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
397         return LHS;
398       if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
399         return RHS;
400     }
401
402   return nullptr;
403 }
404
405 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
406   if (skipOptnoneFunction(L))
407     return false;
408
409   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
410       *L->getHeader()->getParent());
411   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
412   LPM = &LPM_Ref;
413   DominatorTreeWrapperPass *DTWP =
414       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
415   DT = DTWP ? &DTWP->getDomTree() : nullptr;
416   currentLoop = L;
417   Function *F = currentLoop->getHeader()->getParent();
418   bool Changed = false;
419   do {
420     assert(currentLoop->isLCSSAForm(*DT));
421     redoLoop = false;
422     Changed |= processCurrentLoop();
423   } while(redoLoop);
424
425   if (Changed) {
426     // FIXME: Reconstruct dom info, because it is not preserved properly.
427     if (DT)
428       DT->recalculate(*F);
429   }
430   return Changed;
431 }
432
433 /// processCurrentLoop - Do actual work and unswitch loop if possible
434 /// and profitable.
435 bool LoopUnswitch::processCurrentLoop() {
436   bool Changed = false;
437
438   initLoopData();
439
440   // If LoopSimplify was unable to form a preheader, don't do any unswitching.
441   if (!loopPreheader)
442     return false;
443
444   // Loops with indirectbr cannot be cloned.
445   if (!currentLoop->isSafeToClone())
446     return false;
447
448   // Without dedicated exits, splitting the exit edge may fail.
449   if (!currentLoop->hasDedicatedExits())
450     return false;
451
452   LLVMContext &Context = loopHeader->getContext();
453
454   // Probably we reach the quota of branches for this loop. If so
455   // stop unswitching.
456   if (!BranchesInfo.countLoop(
457           currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
458                            *currentLoop->getHeader()->getParent()),
459           AC))
460     return false;
461
462   // Trivial unswitch condition can only occur at loop header basic block because
463   // that condition needs to control whether or not the loop does anything at all.
464   // Try trivial unswitch first before loop over other basic blocks in the loop.
465   if (TryTrivialLoopUnswitch(Changed)) {
466     return true;
467   }
468
469   // Loop over all of the basic blocks in the loop.  If we find an interior
470   // block that is branching on a loop-invariant condition, we can unswitch this
471   // loop.
472   for (Loop::block_iterator I = currentLoop->block_begin(),
473          E = currentLoop->block_end(); I != E; ++I) {
474     TerminatorInst *TI = (*I)->getTerminator();
475     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
476       // If this isn't branching on an invariant condition, we can't unswitch
477       // it.
478       if (BI->isConditional()) {
479         // See if this, or some part of it, is loop invariant.  If so, we can
480         // unswitch on it if we desire.
481         Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
482                                                currentLoop, Changed);
483         if (LoopCond &&
484             UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context), TI)) {
485           ++NumBranches;
486           return true;
487         }
488       }
489     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
490       Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
491                                              currentLoop, Changed);
492       unsigned NumCases = SI->getNumCases();
493       if (LoopCond && NumCases) {
494         // Find a value to unswitch on:
495         // FIXME: this should chose the most expensive case!
496         // FIXME: scan for a case with a non-critical edge?
497         Constant *UnswitchVal = nullptr;
498
499         // Do not process same value again and again.
500         // At this point we have some cases already unswitched and
501         // some not yet unswitched. Let's find the first not yet unswitched one.
502         for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
503              i != e; ++i) {
504           Constant *UnswitchValCandidate = i.getCaseValue();
505           if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
506             UnswitchVal = UnswitchValCandidate;
507             break;
508           }
509         }
510
511         if (!UnswitchVal)
512           continue;
513
514         if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
515           ++NumSwitches;
516           return true;
517         }
518       }
519     }
520
521     // Scan the instructions to check for unswitchable values.
522     for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
523          BBI != E; ++BBI)
524       if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
525         Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
526                                                currentLoop, Changed);
527         if (LoopCond && UnswitchIfProfitable(LoopCond,
528                                              ConstantInt::getTrue(Context))) {
529           ++NumSelects;
530           return true;
531         }
532       }
533   }
534   return Changed;
535 }
536
537 /// isTrivialLoopExitBlock - Check to see if all paths from BB exit the
538 /// loop with no side effects (including infinite loops).
539 ///
540 /// If true, we return true and set ExitBB to the block we
541 /// exit through.
542 ///
543 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
544                                          BasicBlock *&ExitBB,
545                                          std::set<BasicBlock*> &Visited) {
546   if (!Visited.insert(BB).second) {
547     // Already visited. Without more analysis, this could indicate an infinite
548     // loop.
549     return false;
550   }
551   if (!L->contains(BB)) {
552     // Otherwise, this is a loop exit, this is fine so long as this is the
553     // first exit.
554     if (ExitBB) return false;
555     ExitBB = BB;
556     return true;
557   }
558
559   // Otherwise, this is an unvisited intra-loop node.  Check all successors.
560   for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
561     // Check to see if the successor is a trivial loop exit.
562     if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
563       return false;
564   }
565
566   // Okay, everything after this looks good, check to make sure that this block
567   // doesn't include any side effects.
568   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
569     if (I->mayHaveSideEffects())
570       return false;
571
572   return true;
573 }
574
575 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
576 /// leads to an exit from the specified loop, and has no side-effects in the
577 /// process.  If so, return the block that is exited to, otherwise return null.
578 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
579   std::set<BasicBlock*> Visited;
580   Visited.insert(L->getHeader());  // Branches to header make infinite loops.
581   BasicBlock *ExitBB = nullptr;
582   if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
583     return ExitBB;
584   return nullptr;
585 }
586
587 /// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
588 /// LoopCond == Val to simplify the loop.  If we decide that this is profitable,
589 /// unswitch the loop, reprocess the pieces, then return true.
590 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,
591                                         TerminatorInst *TI) {
592   Function *F = loopHeader->getParent();
593
594   // Check to see if it would be profitable to unswitch current loop.
595   if (!BranchesInfo.CostAllowsUnswitching()) {
596     DEBUG(dbgs() << "NOT unswitching loop %"
597                  << currentLoop->getHeader()->getName()
598                  << " at non-trivial condition '" << *Val
599                  << "' == " << *LoopCond << "\n"
600                  << ". Cost too high.\n");
601     return false;
602   }
603
604   // Do not do non-trivial unswitch while optimizing for size.
605   if (OptimizeForSize || F->hasFnAttribute(Attribute::OptimizeForSize))
606     return false;
607
608   UnswitchNontrivialCondition(LoopCond, Val, currentLoop, TI);
609   return true;
610 }
611
612 /// CloneLoop - Recursively clone the specified loop and all of its children,
613 /// mapping the blocks with the specified map.
614 static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
615                        LoopInfo *LI, LPPassManager *LPM) {
616   Loop *New = new Loop();
617   LPM->insertLoop(New, PL);
618
619   // Add all of the blocks in L to the new loop.
620   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
621        I != E; ++I)
622     if (LI->getLoopFor(*I) == L)
623       New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
624
625   // Add all of the subloops to the new loop.
626   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
627     CloneLoop(*I, New, VM, LI, LPM);
628
629   return New;
630 }
631
632 static void copyMetadata(Instruction *DstInst, const Instruction *SrcInst,
633                          bool Swapped) {
634   if (!SrcInst || !SrcInst->hasMetadata())
635     return;
636
637   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
638   SrcInst->getAllMetadata(MDs);
639   for (auto &MD : MDs) {
640     switch (MD.first) {
641     default:
642       break;
643     case LLVMContext::MD_prof:
644       if (Swapped && MD.second->getNumOperands() == 3 &&
645           isa<MDString>(MD.second->getOperand(0))) {
646         MDString *MDName = cast<MDString>(MD.second->getOperand(0));
647         if (MDName->getString() == "branch_weights") {
648           auto *ValT = cast_or_null<ConstantAsMetadata>(
649                            MD.second->getOperand(1))->getValue();
650           auto *ValF = cast_or_null<ConstantAsMetadata>(
651                            MD.second->getOperand(2))->getValue();
652           assert(ValT && ValF && "Invalid Operands of branch_weights");
653           auto NewMD =
654               MDBuilder(DstInst->getParent()->getContext())
655                   .createBranchWeights(cast<ConstantInt>(ValF)->getZExtValue(),
656                                        cast<ConstantInt>(ValT)->getZExtValue());
657           MD.second = NewMD;
658         }
659       }
660       // fallthrough.
661     case LLVMContext::MD_dbg:
662       DstInst->setMetadata(MD.first, MD.second);
663     }
664   }
665 }
666
667 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
668 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest.  Insert the
669 /// code immediately before InsertPt.
670 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
671                                                   BasicBlock *TrueDest,
672                                                   BasicBlock *FalseDest,
673                                                   Instruction *InsertPt,
674                                                   TerminatorInst *TI) {
675   // Insert a conditional branch on LIC to the two preheaders.  The original
676   // code is the true version and the new code is the false version.
677   Value *BranchVal = LIC;
678   bool Swapped = false;
679   if (!isa<ConstantInt>(Val) ||
680       Val->getType() != Type::getInt1Ty(LIC->getContext()))
681     BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val);
682   else if (Val != ConstantInt::getTrue(Val->getContext())) {
683     // We want to enter the new loop when the condition is true.
684     std::swap(TrueDest, FalseDest);
685     Swapped = true;
686   }
687
688   // Insert the new branch.
689   BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
690   copyMetadata(BI, TI, Swapped);
691
692   // If either edge is critical, split it. This helps preserve LoopSimplify
693   // form for enclosing loops.
694   auto Options = CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA();
695   SplitCriticalEdge(BI, 0, Options);
696   SplitCriticalEdge(BI, 1, Options);
697 }
698
699 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
700 /// condition in it (a cond branch from its header block to its latch block,
701 /// where the path through the loop that doesn't execute its body has no
702 /// side-effects), unswitch it.  This doesn't involve any code duplication, just
703 /// moving the conditional branch outside of the loop and updating loop info.
704 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
705                                             BasicBlock *ExitBlock,
706                                             TerminatorInst *TI) {
707   DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
708                << loopHeader->getName() << " [" << L->getBlocks().size()
709                << " blocks] in Function "
710                << L->getHeader()->getParent()->getName() << " on cond: " << *Val
711                << " == " << *Cond << "\n");
712
713   // First step, split the preheader, so that we know that there is a safe place
714   // to insert the conditional branch.  We will change loopPreheader to have a
715   // conditional branch on Cond.
716   BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, DT, LI);
717
718   // Now that we have a place to insert the conditional branch, create a place
719   // to branch to: this is the exit block out of the loop that we should
720   // short-circuit to.
721
722   // Split this block now, so that the loop maintains its exit block, and so
723   // that the jump from the preheader can execute the contents of the exit block
724   // without actually branching to it (the exit block should be dominated by the
725   // loop header, not the preheader).
726   assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
727   BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), DT, LI);
728
729   // Okay, now we have a position to branch from and a position to branch to,
730   // insert the new conditional branch.
731   EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
732                                  loopPreheader->getTerminator(), TI);
733   LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
734   loopPreheader->getTerminator()->eraseFromParent();
735
736   // We need to reprocess this loop, it could be unswitched again.
737   redoLoop = true;
738
739   // Now that we know that the loop is never entered when this condition is a
740   // particular value, rewrite the loop with this info.  We know that this will
741   // at least eliminate the old branch.
742   RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
743   ++NumTrivial;
744 }
745
746 /// TryTrivialLoopUnswitch - Check if loop header block's terminator is a trivial
747 /// unswitch condition: that is, the condition controls whether or not the loop
748 /// does anything at all (which means it can only occur in loop header). If it is
749 /// a trivial condition, unswitching produces no code duplications (equivalently,
750 /// it produces a simpler loop and a new empty loop, which gets deleted). Therefore
751 /// always unswitch trivial condition.
752 ///
753 bool LoopUnswitch::TryTrivialLoopUnswitch(bool &Changed) {
754   BasicBlock *Header = currentLoop->getHeader();
755   TerminatorInst *HeaderTerm = Header->getTerminator();
756   LLVMContext &Context = Header->getContext();
757
758   // Check if this loop will execute any side-effecting instructions (e.g.
759   // stores, calls, volatile loads) in the part of the loop that the code
760   // *would* execute. Check the header first.
761   for (BasicBlock::iterator I :*Header)
762     if (I->mayHaveSideEffects())
763       return false;
764
765   // CondVal is the condition that controls the trivial condition.
766   // LoopExitBB is the BasicBlock that loop exits when meets trivial condition.
767   Constant *CondVal = nullptr;
768   BasicBlock *LoopExitBB = nullptr;
769
770   if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
771     // If this isn't branching on an invariant condition, we can't unswitch it.
772     if (!BI->isConditional())
773       return false;
774
775     Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
776                                            currentLoop, Changed);
777
778     // Unswitch only if the trivial condition itself is an LIV (not
779     // partial LIV which could occur in and/or)
780     if (!LoopCond || LoopCond != BI->getCondition())
781       return false;
782
783     // Check to see if a successor of the branch is guaranteed to
784     // exit through a unique exit block without having any
785     // side-effects.  If so, determine the value of Cond that causes
786     // it to do this.
787     if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
788                                              BI->getSuccessor(0)))) {
789       CondVal = ConstantInt::getTrue(Context);
790     } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
791                                                     BI->getSuccessor(1)))) {
792       CondVal = ConstantInt::getFalse(Context);
793     }
794
795     // If we didn't find a single unique LoopExit block, or if the loop exit block
796     // contains phi nodes, this isn't trivial.
797     if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
798       return false;   // Can't handle this.
799
800     UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB, HeaderTerm);
801     ++NumBranches;
802     return true;
803   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
804     // If this isn't switching on an invariant condition, we can't unswitch it.
805     Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
806                                            currentLoop, Changed);
807
808     // Unswitch only if the trivial condition itself is an LIV (not
809     // partial LIV which could occur in and/or)
810     if (!LoopCond || LoopCond != SI->getCondition())
811       return false;
812
813     // Check to see if a successor of the switch is guaranteed to go to the
814     // latch block or exit through a one exit block without having any
815     // side-effects.  If so, determine the value of Cond that causes it to do
816     // this.
817     // Note that we can't trivially unswitch on the default case or
818     // on already unswitched cases.
819     for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
820          i != e; ++i) {
821       BasicBlock *LoopExitCandidate;
822       if ((LoopExitCandidate = isTrivialLoopExitBlock(currentLoop,
823                                                i.getCaseSuccessor()))) {
824         // Okay, we found a trivial case, remember the value that is trivial.
825         ConstantInt *CaseVal = i.getCaseValue();
826
827         // Check that it was not unswitched before, since already unswitched
828         // trivial vals are looks trivial too.
829         if (BranchesInfo.isUnswitched(SI, CaseVal))
830           continue;
831         LoopExitBB = LoopExitCandidate;
832         CondVal = CaseVal;
833         break;
834       }
835     }
836
837     // If we didn't find a single unique LoopExit block, or if the loop exit block
838     // contains phi nodes, this isn't trivial.
839     if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
840       return false;   // Can't handle this.
841
842     UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB, nullptr);
843     ++NumSwitches;
844     return true;
845   }
846   return false;
847 }
848
849 /// SplitExitEdges - Split all of the edges from inside the loop to their exit
850 /// blocks.  Update the appropriate Phi nodes as we do so.
851 void LoopUnswitch::SplitExitEdges(Loop *L,
852                                const SmallVectorImpl<BasicBlock *> &ExitBlocks){
853
854   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
855     BasicBlock *ExitBlock = ExitBlocks[i];
856     SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
857                                        pred_end(ExitBlock));
858
859     // Although SplitBlockPredecessors doesn't preserve loop-simplify in
860     // general, if we call it on all predecessors of all exits then it does.
861     SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", DT, LI,
862                            /*PreserveLCSSA*/ true);
863   }
864 }
865
866 /// UnswitchNontrivialCondition - We determined that the loop is profitable
867 /// to unswitch when LIC equal Val.  Split it into loop versions and test the
868 /// condition outside of either loop.  Return the loops created as Out1/Out2.
869 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
870                                                Loop *L, TerminatorInst *TI) {
871   Function *F = loopHeader->getParent();
872   DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
873         << loopHeader->getName() << " [" << L->getBlocks().size()
874         << " blocks] in Function " << F->getName()
875         << " when '" << *Val << "' == " << *LIC << "\n");
876
877   if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
878     SE->forgetLoop(L);
879
880   LoopBlocks.clear();
881   NewBlocks.clear();
882
883   // First step, split the preheader and exit blocks, and add these blocks to
884   // the LoopBlocks list.
885   BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, DT, LI);
886   LoopBlocks.push_back(NewPreheader);
887
888   // We want the loop to come after the preheader, but before the exit blocks.
889   LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
890
891   SmallVector<BasicBlock*, 8> ExitBlocks;
892   L->getUniqueExitBlocks(ExitBlocks);
893
894   // Split all of the edges from inside the loop to their exit blocks.  Update
895   // the appropriate Phi nodes as we do so.
896   SplitExitEdges(L, ExitBlocks);
897
898   // The exit blocks may have been changed due to edge splitting, recompute.
899   ExitBlocks.clear();
900   L->getUniqueExitBlocks(ExitBlocks);
901
902   // Add exit blocks to the loop blocks.
903   LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
904
905   // Next step, clone all of the basic blocks that make up the loop (including
906   // the loop preheader and exit blocks), keeping track of the mapping between
907   // the instructions and blocks.
908   NewBlocks.reserve(LoopBlocks.size());
909   ValueToValueMapTy VMap;
910   for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
911     BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
912
913     NewBlocks.push_back(NewBB);
914     VMap[LoopBlocks[i]] = NewBB;  // Keep the BB mapping.
915     LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
916   }
917
918   // Splice the newly inserted blocks into the function right before the
919   // original preheader.
920   F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
921                                 NewBlocks[0], F->end());
922
923   // FIXME: We could register any cloned assumptions instead of clearing the
924   // whole function's cache.
925   AC->clear();
926
927   // Now we create the new Loop object for the versioned loop.
928   Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
929
930   // Recalculate unswitching quota, inherit simplified switches info for NewBB,
931   // Probably clone more loop-unswitch related loop properties.
932   BranchesInfo.cloneData(NewLoop, L, VMap);
933
934   Loop *ParentLoop = L->getParentLoop();
935   if (ParentLoop) {
936     // Make sure to add the cloned preheader and exit blocks to the parent loop
937     // as well.
938     ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
939   }
940
941   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
942     BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
943     // The new exit block should be in the same loop as the old one.
944     if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
945       ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
946
947     assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
948            "Exit block should have been split to have one successor!");
949     BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
950
951     // If the successor of the exit block had PHI nodes, add an entry for
952     // NewExit.
953     for (BasicBlock::iterator I = ExitSucc->begin();
954          PHINode *PN = dyn_cast<PHINode>(I); ++I) {
955       Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
956       ValueToValueMapTy::iterator It = VMap.find(V);
957       if (It != VMap.end()) V = It->second;
958       PN->addIncoming(V, NewExit);
959     }
960
961     if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
962       PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
963                                     ExitSucc->getFirstInsertionPt());
964
965       for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
966            I != E; ++I) {
967         BasicBlock *BB = *I;
968         LandingPadInst *LPI = BB->getLandingPadInst();
969         LPI->replaceAllUsesWith(PN);
970         PN->addIncoming(LPI, BB);
971       }
972     }
973   }
974
975   // Rewrite the code to refer to itself.
976   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
977     for (BasicBlock::iterator I = NewBlocks[i]->begin(),
978            E = NewBlocks[i]->end(); I != E; ++I)
979       RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
980
981   // Rewrite the original preheader to select between versions of the loop.
982   BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
983   assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
984          "Preheader splitting did not work correctly!");
985
986   // Emit the new branch that selects between the two versions of this loop.
987   EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
988                                  TI);
989   LPM->deleteSimpleAnalysisValue(OldBR, L);
990   OldBR->eraseFromParent();
991
992   LoopProcessWorklist.push_back(NewLoop);
993   redoLoop = true;
994
995   // Keep a WeakVH holding onto LIC.  If the first call to RewriteLoopBody
996   // deletes the instruction (for example by simplifying a PHI that feeds into
997   // the condition that we're unswitching on), we don't rewrite the second
998   // iteration.
999   WeakVH LICHandle(LIC);
1000
1001   // Now we rewrite the original code to know that the condition is true and the
1002   // new code to know that the condition is false.
1003   RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
1004
1005   // It's possible that simplifying one loop could cause the other to be
1006   // changed to another value or a constant.  If its a constant, don't simplify
1007   // it.
1008   if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
1009       LICHandle && !isa<Constant>(LICHandle))
1010     RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
1011 }
1012
1013 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
1014 /// specified.
1015 static void RemoveFromWorklist(Instruction *I,
1016                                std::vector<Instruction*> &Worklist) {
1017
1018   Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
1019                  Worklist.end());
1020 }
1021
1022 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
1023 /// program, replacing all uses with V and update the worklist.
1024 static void ReplaceUsesOfWith(Instruction *I, Value *V,
1025                               std::vector<Instruction*> &Worklist,
1026                               Loop *L, LPPassManager *LPM) {
1027   DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
1028
1029   // Add uses to the worklist, which may be dead now.
1030   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1031     if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1032       Worklist.push_back(Use);
1033
1034   // Add users to the worklist which may be simplified now.
1035   for (User *U : I->users())
1036     Worklist.push_back(cast<Instruction>(U));
1037   LPM->deleteSimpleAnalysisValue(I, L);
1038   RemoveFromWorklist(I, Worklist);
1039   I->replaceAllUsesWith(V);
1040   I->eraseFromParent();
1041   ++NumSimplify;
1042 }
1043
1044 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
1045 // the value specified by Val in the specified loop, or we know it does NOT have
1046 // that value.  Rewrite any uses of LIC or of properties correlated to it.
1047 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
1048                                                         Constant *Val,
1049                                                         bool IsEqual) {
1050   assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
1051
1052   // FIXME: Support correlated properties, like:
1053   //  for (...)
1054   //    if (li1 < li2)
1055   //      ...
1056   //    if (li1 > li2)
1057   //      ...
1058
1059   // FOLD boolean conditions (X|LIC), (X&LIC).  Fold conditional branches,
1060   // selects, switches.
1061   std::vector<Instruction*> Worklist;
1062   LLVMContext &Context = Val->getContext();
1063
1064   // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
1065   // in the loop with the appropriate one directly.
1066   if (IsEqual || (isa<ConstantInt>(Val) &&
1067       Val->getType()->isIntegerTy(1))) {
1068     Value *Replacement;
1069     if (IsEqual)
1070       Replacement = Val;
1071     else
1072       Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
1073                                      !cast<ConstantInt>(Val)->getZExtValue());
1074
1075     for (User *U : LIC->users()) {
1076       Instruction *UI = dyn_cast<Instruction>(U);
1077       if (!UI || !L->contains(UI))
1078         continue;
1079       Worklist.push_back(UI);
1080     }
1081
1082     for (std::vector<Instruction*>::iterator UI = Worklist.begin(),
1083          UE = Worklist.end(); UI != UE; ++UI)
1084       (*UI)->replaceUsesOfWith(LIC, Replacement);
1085
1086     SimplifyCode(Worklist, L);
1087     return;
1088   }
1089
1090   // Otherwise, we don't know the precise value of LIC, but we do know that it
1091   // is certainly NOT "Val".  As such, simplify any uses in the loop that we
1092   // can.  This case occurs when we unswitch switch statements.
1093   for (User *U : LIC->users()) {
1094     Instruction *UI = dyn_cast<Instruction>(U);
1095     if (!UI || !L->contains(UI))
1096       continue;
1097
1098     Worklist.push_back(UI);
1099
1100     // TODO: We could do other simplifications, for example, turning
1101     // 'icmp eq LIC, Val' -> false.
1102
1103     // If we know that LIC is not Val, use this info to simplify code.
1104     SwitchInst *SI = dyn_cast<SwitchInst>(UI);
1105     if (!SI || !isa<ConstantInt>(Val)) continue;
1106
1107     SwitchInst::CaseIt DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
1108     // Default case is live for multiple values.
1109     if (DeadCase == SI->case_default()) continue;
1110
1111     // Found a dead case value.  Don't remove PHI nodes in the
1112     // successor if they become single-entry, those PHI nodes may
1113     // be in the Users list.
1114
1115     BasicBlock *Switch = SI->getParent();
1116     BasicBlock *SISucc = DeadCase.getCaseSuccessor();
1117     BasicBlock *Latch = L->getLoopLatch();
1118
1119     BranchesInfo.setUnswitched(SI, Val);
1120
1121     if (!SI->findCaseDest(SISucc)) continue;  // Edge is critical.
1122     // If the DeadCase successor dominates the loop latch, then the
1123     // transformation isn't safe since it will delete the sole predecessor edge
1124     // to the latch.
1125     if (Latch && DT->dominates(SISucc, Latch))
1126       continue;
1127
1128     // FIXME: This is a hack.  We need to keep the successor around
1129     // and hooked up so as to preserve the loop structure, because
1130     // trying to update it is complicated.  So instead we preserve the
1131     // loop structure and put the block on a dead code path.
1132     SplitEdge(Switch, SISucc, DT, LI);
1133     // Compute the successors instead of relying on the return value
1134     // of SplitEdge, since it may have split the switch successor
1135     // after PHI nodes.
1136     BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
1137     BasicBlock *OldSISucc = *succ_begin(NewSISucc);
1138     // Create an "unreachable" destination.
1139     BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
1140                                            Switch->getParent(),
1141                                            OldSISucc);
1142     new UnreachableInst(Context, Abort);
1143     // Force the new case destination to branch to the "unreachable"
1144     // block while maintaining a (dead) CFG edge to the old block.
1145     NewSISucc->getTerminator()->eraseFromParent();
1146     BranchInst::Create(Abort, OldSISucc,
1147                        ConstantInt::getTrue(Context), NewSISucc);
1148     // Release the PHI operands for this edge.
1149     for (BasicBlock::iterator II = NewSISucc->begin();
1150          PHINode *PN = dyn_cast<PHINode>(II); ++II)
1151       PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
1152                            UndefValue::get(PN->getType()));
1153     // Tell the domtree about the new block. We don't fully update the
1154     // domtree here -- instead we force it to do a full recomputation
1155     // after the pass is complete -- but we do need to inform it of
1156     // new blocks.
1157     if (DT)
1158       DT->addNewBlock(Abort, NewSISucc);
1159   }
1160
1161   SimplifyCode(Worklist, L);
1162 }
1163
1164 /// SimplifyCode - Okay, now that we have simplified some instructions in the
1165 /// loop, walk over it and constant prop, dce, and fold control flow where
1166 /// possible.  Note that this is effectively a very simple loop-structure-aware
1167 /// optimizer.  During processing of this loop, L could very well be deleted, so
1168 /// it must not be used.
1169 ///
1170 /// FIXME: When the loop optimizer is more mature, separate this out to a new
1171 /// pass.
1172 ///
1173 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
1174   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
1175   while (!Worklist.empty()) {
1176     Instruction *I = Worklist.back();
1177     Worklist.pop_back();
1178
1179     // Simple DCE.
1180     if (isInstructionTriviallyDead(I)) {
1181       DEBUG(dbgs() << "Remove dead instruction '" << *I);
1182
1183       // Add uses to the worklist, which may be dead now.
1184       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1185         if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1186           Worklist.push_back(Use);
1187       LPM->deleteSimpleAnalysisValue(I, L);
1188       RemoveFromWorklist(I, Worklist);
1189       I->eraseFromParent();
1190       ++NumSimplify;
1191       continue;
1192     }
1193
1194     // See if instruction simplification can hack this up.  This is common for
1195     // things like "select false, X, Y" after unswitching made the condition be
1196     // 'false'.  TODO: update the domtree properly so we can pass it here.
1197     if (Value *V = SimplifyInstruction(I, DL))
1198       if (LI->replacementPreservesLCSSAForm(I, V)) {
1199         ReplaceUsesOfWith(I, V, Worklist, L, LPM);
1200         continue;
1201       }
1202
1203     // Special case hacks that appear commonly in unswitched code.
1204     if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1205       if (BI->isUnconditional()) {
1206         // If BI's parent is the only pred of the successor, fold the two blocks
1207         // together.
1208         BasicBlock *Pred = BI->getParent();
1209         BasicBlock *Succ = BI->getSuccessor(0);
1210         BasicBlock *SinglePred = Succ->getSinglePredecessor();
1211         if (!SinglePred) continue;  // Nothing to do.
1212         assert(SinglePred == Pred && "CFG broken");
1213
1214         DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
1215               << Succ->getName() << "\n");
1216
1217         // Resolve any single entry PHI nodes in Succ.
1218         while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1219           ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
1220
1221         // If Succ has any successors with PHI nodes, update them to have
1222         // entries coming from Pred instead of Succ.
1223         Succ->replaceAllUsesWith(Pred);
1224
1225         // Move all of the successor contents from Succ to Pred.
1226         Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1227                                    Succ->end());
1228         LPM->deleteSimpleAnalysisValue(BI, L);
1229         BI->eraseFromParent();
1230         RemoveFromWorklist(BI, Worklist);
1231
1232         // Remove Succ from the loop tree.
1233         LI->removeBlock(Succ);
1234         LPM->deleteSimpleAnalysisValue(Succ, L);
1235         Succ->eraseFromParent();
1236         ++NumSimplify;
1237         continue;
1238       }
1239
1240       continue;
1241     }
1242   }
1243 }