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