LoopUnswitch.cpp revision 508955156a25a9abc470a29e1760aa176d341cf9
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#define DEBUG_TYPE "loop-unswitch"
30#include "llvm/Transforms/Scalar.h"
31#include "llvm/Constants.h"
32#include "llvm/DerivedTypes.h"
33#include "llvm/Function.h"
34#include "llvm/Instructions.h"
35#include "llvm/LLVMContext.h"
36#include "llvm/Analysis/ConstantFolding.h"
37#include "llvm/Analysis/LoopInfo.h"
38#include "llvm/Analysis/LoopPass.h"
39#include "llvm/Analysis/Dominators.h"
40#include "llvm/Transforms/Utils/Cloning.h"
41#include "llvm/Transforms/Utils/Local.h"
42#include "llvm/Transforms/Utils/BasicBlockUtils.h"
43#include "llvm/ADT/Statistic.h"
44#include "llvm/ADT/SmallPtrSet.h"
45#include "llvm/ADT/STLExtras.h"
46#include "llvm/Support/CommandLine.h"
47#include "llvm/Support/Compiler.h"
48#include "llvm/Support/Debug.h"
49#include <algorithm>
50#include <set>
51using namespace llvm;
52
53STATISTIC(NumBranches, "Number of branches unswitched");
54STATISTIC(NumSwitches, "Number of switches unswitched");
55STATISTIC(NumSelects , "Number of selects unswitched");
56STATISTIC(NumTrivial , "Number of unswitches that are trivial");
57STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
58
59static cl::opt<unsigned>
60Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
61          cl::init(10), cl::Hidden);
62
63namespace {
64  class VISIBILITY_HIDDEN LoopUnswitch : public LoopPass {
65    LoopInfo *LI;  // Loop information
66    LPPassManager *LPM;
67
68    // LoopProcessWorklist - Used to check if second loop needs processing
69    // after RewriteLoopBodyWithConditionConstant rewrites first loop.
70    std::vector<Loop*> LoopProcessWorklist;
71    SmallPtrSet<Value *,8> UnswitchedVals;
72
73    bool OptimizeForSize;
74    bool redoLoop;
75
76    Loop *currentLoop;
77    DominanceFrontier *DF;
78    DominatorTree *DT;
79    BasicBlock *loopHeader;
80    BasicBlock *loopPreheader;
81
82    // LoopBlocks contains all of the basic blocks of the loop, including the
83    // preheader of the loop, the body of the loop, and the exit blocks of the
84    // loop, in that order.
85    std::vector<BasicBlock*> LoopBlocks;
86    // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
87    std::vector<BasicBlock*> NewBlocks;
88
89  public:
90    static char ID; // Pass ID, replacement for typeid
91    explicit LoopUnswitch(bool Os = false) :
92      LoopPass(&ID), OptimizeForSize(Os), redoLoop(false),
93      currentLoop(NULL), DF(NULL), DT(NULL), loopHeader(NULL),
94      loopPreheader(NULL) {}
95
96    bool runOnLoop(Loop *L, LPPassManager &LPM);
97    bool processCurrentLoop();
98
99    /// This transformation requires natural loop information & requires that
100    /// loop preheaders be inserted into the CFG...
101    ///
102    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
103      AU.addRequiredID(LoopSimplifyID);
104      AU.addPreservedID(LoopSimplifyID);
105      AU.addRequired<LoopInfo>();
106      AU.addPreserved<LoopInfo>();
107      AU.addRequiredID(LCSSAID);
108      AU.addPreservedID(LCSSAID);
109      AU.addPreserved<DominatorTree>();
110      AU.addPreserved<DominanceFrontier>();
111    }
112
113  private:
114
115    /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
116    /// remove it.
117    void RemoveLoopFromWorklist(Loop *L) {
118      std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
119                                                 LoopProcessWorklist.end(), L);
120      if (I != LoopProcessWorklist.end())
121        LoopProcessWorklist.erase(I);
122    }
123
124    void initLoopData() {
125      loopHeader = currentLoop->getHeader();
126      loopPreheader = currentLoop->getLoopPreheader();
127    }
128
129    /// Split all of the edges from inside the loop to their exit blocks.
130    /// Update the appropriate Phi nodes as we do so.
131    void SplitExitEdges(Loop *L, const SmallVector<BasicBlock *, 8> &ExitBlocks);
132
133    bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
134    unsigned getLoopUnswitchCost(Value *LIC);
135    void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
136                                  BasicBlock *ExitBlock);
137    void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
138
139    void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
140                                              Constant *Val, bool isEqual);
141
142    void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
143                                        BasicBlock *TrueDest,
144                                        BasicBlock *FalseDest,
145                                        Instruction *InsertPt);
146
147    void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
148    void RemoveBlockIfDead(BasicBlock *BB,
149                           std::vector<Instruction*> &Worklist, Loop *l);
150    void RemoveLoopFromHierarchy(Loop *L);
151    bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = 0,
152                                    BasicBlock **LoopExit = 0);
153
154  };
155}
156char LoopUnswitch::ID = 0;
157static RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
158
159Pass *llvm::createLoopUnswitchPass(bool Os) {
160  return new LoopUnswitch(Os);
161}
162
163/// FindLIVLoopCondition - Cond is a condition that occurs in L.  If it is
164/// invariant in the loop, or has an invariant piece, return the invariant.
165/// Otherwise, return null.
166static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
167  // Constants should be folded, not unswitched on!
168  if (isa<Constant>(Cond)) return 0;
169
170  // TODO: Handle: br (VARIANT|INVARIANT).
171  // TODO: Hoist simple expressions out of loops.
172  if (L->isLoopInvariant(Cond)) return Cond;
173
174  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
175    if (BO->getOpcode() == Instruction::And ||
176        BO->getOpcode() == Instruction::Or) {
177      // If either the left or right side is invariant, we can unswitch on this,
178      // which will cause the branch to go away in one loop and the condition to
179      // simplify in the other one.
180      if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
181        return LHS;
182      if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
183        return RHS;
184    }
185
186  return 0;
187}
188
189bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
190  LI = &getAnalysis<LoopInfo>();
191  LPM = &LPM_Ref;
192  DF = getAnalysisIfAvailable<DominanceFrontier>();
193  DT = getAnalysisIfAvailable<DominatorTree>();
194  currentLoop = L;
195  Function *F = currentLoop->getHeader()->getParent();
196  bool Changed = false;
197  do {
198    assert(currentLoop->isLCSSAForm());
199    redoLoop = false;
200    Changed |= processCurrentLoop();
201  } while(redoLoop);
202
203  if (Changed) {
204    // FIXME: Reconstruct dom info, because it is not preserved properly.
205    if (DT)
206      DT->runOnFunction(*F);
207    if (DF)
208      DF->runOnFunction(*F);
209  }
210  return Changed;
211}
212
213/// processCurrentLoop - Do actual work and unswitch loop if possible
214/// and profitable.
215bool LoopUnswitch::processCurrentLoop() {
216  bool Changed = false;
217
218  // Loop over all of the basic blocks in the loop.  If we find an interior
219  // block that is branching on a loop-invariant condition, we can unswitch this
220  // loop.
221  for (Loop::block_iterator I = currentLoop->block_begin(),
222         E = currentLoop->block_end();
223       I != E; ++I) {
224    TerminatorInst *TI = (*I)->getTerminator();
225    if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
226      // If this isn't branching on an invariant condition, we can't unswitch
227      // it.
228      if (BI->isConditional()) {
229        // See if this, or some part of it, is loop invariant.  If so, we can
230        // unswitch on it if we desire.
231        Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
232                                               currentLoop, Changed);
233        if (LoopCond && UnswitchIfProfitable(LoopCond,
234                                             Context->getConstantIntTrue())) {
235          ++NumBranches;
236          return true;
237        }
238      }
239    } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
240      Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
241                                             currentLoop, Changed);
242      if (LoopCond && SI->getNumCases() > 1) {
243        // Find a value to unswitch on:
244        // FIXME: this should chose the most expensive case!
245        Constant *UnswitchVal = SI->getCaseValue(1);
246        // Do not process same value again and again.
247        if (!UnswitchedVals.insert(UnswitchVal))
248          continue;
249
250        if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
251          ++NumSwitches;
252          return true;
253        }
254      }
255    }
256
257    // Scan the instructions to check for unswitchable values.
258    for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
259         BBI != E; ++BBI)
260      if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
261        Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
262                                               currentLoop, Changed);
263        if (LoopCond && UnswitchIfProfitable(LoopCond,
264                                             Context->getConstantIntTrue())) {
265          ++NumSelects;
266          return true;
267        }
268      }
269  }
270  return Changed;
271}
272
273/// isTrivialLoopExitBlock - Check to see if all paths from BB either:
274///   1. Exit the loop with no side effects.
275///   2. Branch to the latch block with no side-effects.
276///
277/// If these conditions are true, we return true and set ExitBB to the block we
278/// exit through.
279///
280static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
281                                         BasicBlock *&ExitBB,
282                                         std::set<BasicBlock*> &Visited) {
283  if (!Visited.insert(BB).second) {
284    // Already visited and Ok, end of recursion.
285    return true;
286  } else if (!L->contains(BB)) {
287    // Otherwise, this is a loop exit, this is fine so long as this is the
288    // first exit.
289    if (ExitBB != 0) return false;
290    ExitBB = BB;
291    return true;
292  }
293
294  // Otherwise, this is an unvisited intra-loop node.  Check all successors.
295  for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
296    // Check to see if the successor is a trivial loop exit.
297    if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
298      return false;
299  }
300
301  // Okay, everything after this looks good, check to make sure that this block
302  // doesn't include any side effects.
303  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
304    if (I->mayHaveSideEffects())
305      return false;
306
307  return true;
308}
309
310/// isTrivialLoopExitBlock - Return true if the specified block unconditionally
311/// leads to an exit from the specified loop, and has no side-effects in the
312/// process.  If so, return the block that is exited to, otherwise return null.
313static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
314  std::set<BasicBlock*> Visited;
315  Visited.insert(L->getHeader());  // Branches to header are ok.
316  BasicBlock *ExitBB = 0;
317  if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
318    return ExitBB;
319  return 0;
320}
321
322/// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
323/// trivial: that is, that the condition controls whether or not the loop does
324/// anything at all.  If this is a trivial condition, unswitching produces no
325/// code duplications (equivalently, it produces a simpler loop and a new empty
326/// loop, which gets deleted).
327///
328/// If this is a trivial condition, return true, otherwise return false.  When
329/// returning true, this sets Cond and Val to the condition that controls the
330/// trivial condition: when Cond dynamically equals Val, the loop is known to
331/// exit.  Finally, this sets LoopExit to the BB that the loop exits to when
332/// Cond == Val.
333///
334bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
335                                       BasicBlock **LoopExit) {
336  BasicBlock *Header = currentLoop->getHeader();
337  TerminatorInst *HeaderTerm = Header->getTerminator();
338
339  BasicBlock *LoopExitBB = 0;
340  if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
341    // If the header block doesn't end with a conditional branch on Cond, we
342    // can't handle it.
343    if (!BI->isConditional() || BI->getCondition() != Cond)
344      return false;
345
346    // Check to see if a successor of the branch is guaranteed to go to the
347    // latch block or exit through a one exit block without having any
348    // side-effects.  If so, determine the value of Cond that causes it to do
349    // this.
350    if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
351                                             BI->getSuccessor(0)))) {
352      if (Val) *Val = Context->getConstantIntTrue();
353    } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
354                                                    BI->getSuccessor(1)))) {
355      if (Val) *Val = Context->getConstantIntFalse();
356    }
357  } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
358    // If this isn't a switch on Cond, we can't handle it.
359    if (SI->getCondition() != Cond) return false;
360
361    // Check to see if a successor of the switch is guaranteed to go to the
362    // latch block or exit through a one exit block without having any
363    // side-effects.  If so, determine the value of Cond that causes it to do
364    // this.  Note that we can't trivially unswitch on the default case.
365    for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
366      if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
367                                               SI->getSuccessor(i)))) {
368        // Okay, we found a trivial case, remember the value that is trivial.
369        if (Val) *Val = SI->getCaseValue(i);
370        break;
371      }
372  }
373
374  // If we didn't find a single unique LoopExit block, or if the loop exit block
375  // contains phi nodes, this isn't trivial.
376  if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
377    return false;   // Can't handle this.
378
379  if (LoopExit) *LoopExit = LoopExitBB;
380
381  // We already know that nothing uses any scalar values defined inside of this
382  // loop.  As such, we just have to check to see if this loop will execute any
383  // side-effecting instructions (e.g. stores, calls, volatile loads) in the
384  // part of the loop that the code *would* execute.  We already checked the
385  // tail, check the header now.
386  for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
387    if (I->mayHaveSideEffects())
388      return false;
389  return true;
390}
391
392/// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
393/// we choose to unswitch current loop on the specified value.
394///
395unsigned LoopUnswitch::getLoopUnswitchCost(Value *LIC) {
396  // If the condition is trivial, always unswitch.  There is no code growth for
397  // this case.
398  if (IsTrivialUnswitchCondition(LIC))
399    return 0;
400
401  // FIXME: This is really overly conservative.  However, more liberal
402  // estimations have thus far resulted in excessive unswitching, which is bad
403  // both in compile time and in code size.  This should be replaced once
404  // someone figures out how a good estimation.
405  return currentLoop->getBlocks().size();
406
407  unsigned Cost = 0;
408  // FIXME: this is brain dead.  It should take into consideration code
409  // shrinkage.
410  for (Loop::block_iterator I = currentLoop->block_begin(),
411         E = currentLoop->block_end();
412       I != E; ++I) {
413    BasicBlock *BB = *I;
414    // Do not include empty blocks in the cost calculation.  This happen due to
415    // loop canonicalization and will be removed.
416    if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
417      continue;
418
419    // Count basic blocks.
420    ++Cost;
421  }
422
423  return Cost;
424}
425
426/// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
427/// LoopCond == Val to simplify the loop.  If we decide that this is profitable,
428/// unswitch the loop, reprocess the pieces, then return true.
429bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val){
430
431  initLoopData();
432  Function *F = loopHeader->getParent();
433
434
435  // Check to see if it would be profitable to unswitch current loop.
436  unsigned Cost = getLoopUnswitchCost(LoopCond);
437
438  // Do not do non-trivial unswitch while optimizing for size.
439  if (Cost && OptimizeForSize)
440    return false;
441  if (Cost && !F->isDeclaration() && F->hasFnAttr(Attribute::OptimizeForSize))
442    return false;
443
444  if (Cost > Threshold) {
445    // FIXME: this should estimate growth by the amount of code shared by the
446    // resultant unswitched loops.
447    //
448    DOUT << "NOT unswitching loop %"
449         << currentLoop->getHeader()->getName() << ", cost too high: "
450         << currentLoop->getBlocks().size() << "\n";
451    return false;
452  }
453
454  Constant *CondVal;
455  BasicBlock *ExitBlock;
456  if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
457    UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
458  } else {
459    UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
460  }
461
462  return true;
463}
464
465// RemapInstruction - Convert the instruction operands from referencing the
466// current values into those specified by ValueMap.
467//
468static inline void RemapInstruction(Instruction *I,
469                                    DenseMap<const Value *, Value*> &ValueMap) {
470  for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
471    Value *Op = I->getOperand(op);
472    DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
473    if (It != ValueMap.end()) Op = It->second;
474    I->setOperand(op, Op);
475  }
476}
477
478/// CloneLoop - Recursively clone the specified loop and all of its children,
479/// mapping the blocks with the specified map.
480static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
481                       LoopInfo *LI, LPPassManager *LPM) {
482  Loop *New = new Loop();
483
484  LPM->insertLoop(New, PL);
485
486  // Add all of the blocks in L to the new loop.
487  for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
488       I != E; ++I)
489    if (LI->getLoopFor(*I) == L)
490      New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
491
492  // Add all of the subloops to the new loop.
493  for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
494    CloneLoop(*I, New, VM, LI, LPM);
495
496  return New;
497}
498
499/// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
500/// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest.  Insert the
501/// code immediately before InsertPt.
502void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
503                                                  BasicBlock *TrueDest,
504                                                  BasicBlock *FalseDest,
505                                                  Instruction *InsertPt) {
506  // Insert a conditional branch on LIC to the two preheaders.  The original
507  // code is the true version and the new code is the false version.
508  Value *BranchVal = LIC;
509  if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
510    BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
511  else if (Val != Context->getConstantIntTrue())
512    // We want to enter the new loop when the condition is true.
513    std::swap(TrueDest, FalseDest);
514
515  // Insert the new branch.
516  BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
517}
518
519/// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
520/// condition in it (a cond branch from its header block to its latch block,
521/// where the path through the loop that doesn't execute its body has no
522/// side-effects), unswitch it.  This doesn't involve any code duplication, just
523/// moving the conditional branch outside of the loop and updating loop info.
524void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
525                                            Constant *Val,
526                                            BasicBlock *ExitBlock) {
527  DOUT << "loop-unswitch: Trivial-Unswitch loop %"
528       << loopHeader->getName() << " [" << L->getBlocks().size()
529       << " blocks] in Function " << L->getHeader()->getParent()->getName()
530       << " on cond: " << *Val << " == " << *Cond << "\n";
531
532  // First step, split the preheader, so that we know that there is a safe place
533  // to insert the conditional branch.  We will change loopPreheader to have a
534  // conditional branch on Cond.
535  BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
536
537  // Now that we have a place to insert the conditional branch, create a place
538  // to branch to: this is the exit block out of the loop that we should
539  // short-circuit to.
540
541  // Split this block now, so that the loop maintains its exit block, and so
542  // that the jump from the preheader can execute the contents of the exit block
543  // without actually branching to it (the exit block should be dominated by the
544  // loop header, not the preheader).
545  assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
546  BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
547
548  // Okay, now we have a position to branch from and a position to branch to,
549  // insert the new conditional branch.
550  EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
551                                 loopPreheader->getTerminator());
552  LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
553  loopPreheader->getTerminator()->eraseFromParent();
554
555  // We need to reprocess this loop, it could be unswitched again.
556  redoLoop = true;
557
558  // Now that we know that the loop is never entered when this condition is a
559  // particular value, rewrite the loop with this info.  We know that this will
560  // at least eliminate the old branch.
561  RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
562  ++NumTrivial;
563}
564
565/// SplitExitEdges - Split all of the edges from inside the loop to their exit
566/// blocks.  Update the appropriate Phi nodes as we do so.
567void LoopUnswitch::SplitExitEdges(Loop *L,
568                                const SmallVector<BasicBlock *, 8> &ExitBlocks)
569{
570
571  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
572    BasicBlock *ExitBlock = ExitBlocks[i];
573    std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
574
575    for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
576      BasicBlock* NewExitBlock = SplitEdge(Preds[j], ExitBlock, this);
577      BasicBlock* StartBlock = Preds[j];
578      BasicBlock* EndBlock;
579      if (NewExitBlock->getSinglePredecessor() == ExitBlock) {
580        EndBlock = NewExitBlock;
581        NewExitBlock = EndBlock->getSinglePredecessor();
582      } else {
583        EndBlock = ExitBlock;
584      }
585
586      std::set<PHINode*> InsertedPHIs;
587      PHINode* OldLCSSA = 0;
588      for (BasicBlock::iterator I = EndBlock->begin();
589           (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
590        Value* OldValue = OldLCSSA->getIncomingValueForBlock(NewExitBlock);
591        PHINode* NewLCSSA = PHINode::Create(OldLCSSA->getType(),
592                                            OldLCSSA->getName() + ".us-lcssa",
593                                            NewExitBlock->getTerminator());
594        NewLCSSA->addIncoming(OldValue, StartBlock);
595        OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(NewExitBlock),
596                                   NewLCSSA);
597        InsertedPHIs.insert(NewLCSSA);
598      }
599
600      BasicBlock::iterator InsertPt = EndBlock->getFirstNonPHI();
601      for (BasicBlock::iterator I = NewExitBlock->begin();
602         (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
603         ++I) {
604        PHINode *NewLCSSA = PHINode::Create(OldLCSSA->getType(),
605                                            OldLCSSA->getName() + ".us-lcssa",
606                                            InsertPt);
607        OldLCSSA->replaceAllUsesWith(NewLCSSA);
608        NewLCSSA->addIncoming(OldLCSSA, NewExitBlock);
609      }
610
611    }
612  }
613
614}
615
616/// UnswitchNontrivialCondition - We determined that the loop is profitable
617/// to unswitch when LIC equal Val.  Split it into loop versions and test the
618/// condition outside of either loop.  Return the loops created as Out1/Out2.
619void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
620                                               Loop *L) {
621  Function *F = loopHeader->getParent();
622  DOUT << "loop-unswitch: Unswitching loop %"
623       << loopHeader->getName() << " [" << L->getBlocks().size()
624       << " blocks] in Function " << F->getName()
625       << " when '" << *Val << "' == " << *LIC << "\n";
626
627  LoopBlocks.clear();
628  NewBlocks.clear();
629
630  // First step, split the preheader and exit blocks, and add these blocks to
631  // the LoopBlocks list.
632  BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
633  LoopBlocks.push_back(NewPreheader);
634
635  // We want the loop to come after the preheader, but before the exit blocks.
636  LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
637
638  SmallVector<BasicBlock*, 8> ExitBlocks;
639  L->getUniqueExitBlocks(ExitBlocks);
640
641  // Split all of the edges from inside the loop to their exit blocks.  Update
642  // the appropriate Phi nodes as we do so.
643  SplitExitEdges(L, ExitBlocks);
644
645  // The exit blocks may have been changed due to edge splitting, recompute.
646  ExitBlocks.clear();
647  L->getUniqueExitBlocks(ExitBlocks);
648
649  // Add exit blocks to the loop blocks.
650  LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
651
652  // Next step, clone all of the basic blocks that make up the loop (including
653  // the loop preheader and exit blocks), keeping track of the mapping between
654  // the instructions and blocks.
655  NewBlocks.reserve(LoopBlocks.size());
656  DenseMap<const Value*, Value*> ValueMap;
657  for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
658    BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
659    NewBlocks.push_back(New);
660    ValueMap[LoopBlocks[i]] = New;  // Keep the BB mapping.
661    LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], New, L);
662  }
663
664  // Splice the newly inserted blocks into the function right before the
665  // original preheader.
666  F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
667                                NewBlocks[0], F->end());
668
669  // Now we create the new Loop object for the versioned loop.
670  Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
671  Loop *ParentLoop = L->getParentLoop();
672  if (ParentLoop) {
673    // Make sure to add the cloned preheader and exit blocks to the parent loop
674    // as well.
675    ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
676  }
677
678  for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
679    BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
680    // The new exit block should be in the same loop as the old one.
681    if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
682      ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
683
684    assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
685           "Exit block should have been split to have one successor!");
686    BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
687
688    // If the successor of the exit block had PHI nodes, add an entry for
689    // NewExit.
690    PHINode *PN;
691    for (BasicBlock::iterator I = ExitSucc->begin();
692         (PN = dyn_cast<PHINode>(I)); ++I) {
693      Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
694      DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
695      if (It != ValueMap.end()) V = It->second;
696      PN->addIncoming(V, NewExit);
697    }
698  }
699
700  // Rewrite the code to refer to itself.
701  for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
702    for (BasicBlock::iterator I = NewBlocks[i]->begin(),
703           E = NewBlocks[i]->end(); I != E; ++I)
704      RemapInstruction(I, ValueMap);
705
706  // Rewrite the original preheader to select between versions of the loop.
707  BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
708  assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
709         "Preheader splitting did not work correctly!");
710
711  // Emit the new branch that selects between the two versions of this loop.
712  EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
713  LPM->deleteSimpleAnalysisValue(OldBR, L);
714  OldBR->eraseFromParent();
715
716  LoopProcessWorklist.push_back(NewLoop);
717  redoLoop = true;
718
719  // Now we rewrite the original code to know that the condition is true and the
720  // new code to know that the condition is false.
721  RewriteLoopBodyWithConditionConstant(L      , LIC, Val, false);
722
723  // It's possible that simplifying one loop could cause the other to be
724  // deleted.  If so, don't simplify it.
725  if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
726    RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
727
728}
729
730/// RemoveFromWorklist - Remove all instances of I from the worklist vector
731/// specified.
732static void RemoveFromWorklist(Instruction *I,
733                               std::vector<Instruction*> &Worklist) {
734  std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
735                                                     Worklist.end(), I);
736  while (WI != Worklist.end()) {
737    unsigned Offset = WI-Worklist.begin();
738    Worklist.erase(WI);
739    WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
740  }
741}
742
743/// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
744/// program, replacing all uses with V and update the worklist.
745static void ReplaceUsesOfWith(Instruction *I, Value *V,
746                              std::vector<Instruction*> &Worklist,
747                              Loop *L, LPPassManager *LPM) {
748  DOUT << "Replace with '" << *V << "': " << *I;
749
750  // Add uses to the worklist, which may be dead now.
751  for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
752    if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
753      Worklist.push_back(Use);
754
755  // Add users to the worklist which may be simplified now.
756  for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
757       UI != E; ++UI)
758    Worklist.push_back(cast<Instruction>(*UI));
759  LPM->deleteSimpleAnalysisValue(I, L);
760  RemoveFromWorklist(I, Worklist);
761  I->replaceAllUsesWith(V);
762  I->eraseFromParent();
763  ++NumSimplify;
764}
765
766/// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
767/// information, and remove any dead successors it has.
768///
769void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
770                                     std::vector<Instruction*> &Worklist,
771                                     Loop *L) {
772  if (pred_begin(BB) != pred_end(BB)) {
773    // This block isn't dead, since an edge to BB was just removed, see if there
774    // are any easy simplifications we can do now.
775    if (BasicBlock *Pred = BB->getSinglePredecessor()) {
776      // If it has one pred, fold phi nodes in BB.
777      while (isa<PHINode>(BB->begin()))
778        ReplaceUsesOfWith(BB->begin(),
779                          cast<PHINode>(BB->begin())->getIncomingValue(0),
780                          Worklist, L, LPM);
781
782      // If this is the header of a loop and the only pred is the latch, we now
783      // have an unreachable loop.
784      if (Loop *L = LI->getLoopFor(BB))
785        if (loopHeader == BB && L->contains(Pred)) {
786          // Remove the branch from the latch to the header block, this makes
787          // the header dead, which will make the latch dead (because the header
788          // dominates the latch).
789          LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
790          Pred->getTerminator()->eraseFromParent();
791          new UnreachableInst(Pred);
792
793          // The loop is now broken, remove it from LI.
794          RemoveLoopFromHierarchy(L);
795
796          // Reprocess the header, which now IS dead.
797          RemoveBlockIfDead(BB, Worklist, L);
798          return;
799        }
800
801      // If pred ends in a uncond branch, add uncond branch to worklist so that
802      // the two blocks will get merged.
803      if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
804        if (BI->isUnconditional())
805          Worklist.push_back(BI);
806    }
807    return;
808  }
809
810  DOUT << "Nuking dead block: " << *BB;
811
812  // Remove the instructions in the basic block from the worklist.
813  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
814    RemoveFromWorklist(I, Worklist);
815
816    // Anything that uses the instructions in this basic block should have their
817    // uses replaced with undefs.
818    if (!I->use_empty())
819      I->replaceAllUsesWith(Context->getUndef(I->getType()));
820  }
821
822  // If this is the edge to the header block for a loop, remove the loop and
823  // promote all subloops.
824  if (Loop *BBLoop = LI->getLoopFor(BB)) {
825    if (BBLoop->getLoopLatch() == BB)
826      RemoveLoopFromHierarchy(BBLoop);
827  }
828
829  // Remove the block from the loop info, which removes it from any loops it
830  // was in.
831  LI->removeBlock(BB);
832
833
834  // Remove phi node entries in successors for this block.
835  TerminatorInst *TI = BB->getTerminator();
836  SmallVector<BasicBlock*, 4> Succs;
837  for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
838    Succs.push_back(TI->getSuccessor(i));
839    TI->getSuccessor(i)->removePredecessor(BB);
840  }
841
842  // Unique the successors, remove anything with multiple uses.
843  array_pod_sort(Succs.begin(), Succs.end());
844  Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
845
846  // Remove the basic block, including all of the instructions contained in it.
847  LPM->deleteSimpleAnalysisValue(BB, L);
848  BB->eraseFromParent();
849  // Remove successor blocks here that are not dead, so that we know we only
850  // have dead blocks in this list.  Nondead blocks have a way of becoming dead,
851  // then getting removed before we revisit them, which is badness.
852  //
853  for (unsigned i = 0; i != Succs.size(); ++i)
854    if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
855      // One exception is loop headers.  If this block was the preheader for a
856      // loop, then we DO want to visit the loop so the loop gets deleted.
857      // We know that if the successor is a loop header, that this loop had to
858      // be the preheader: the case where this was the latch block was handled
859      // above and headers can only have two predecessors.
860      if (!LI->isLoopHeader(Succs[i])) {
861        Succs.erase(Succs.begin()+i);
862        --i;
863      }
864    }
865
866  for (unsigned i = 0, e = Succs.size(); i != e; ++i)
867    RemoveBlockIfDead(Succs[i], Worklist, L);
868}
869
870/// RemoveLoopFromHierarchy - We have discovered that the specified loop has
871/// become unwrapped, either because the backedge was deleted, or because the
872/// edge into the header was removed.  If the edge into the header from the
873/// latch block was removed, the loop is unwrapped but subloops are still alive,
874/// so they just reparent loops.  If the loops are actually dead, they will be
875/// removed later.
876void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
877  LPM->deleteLoopFromQueue(L);
878  RemoveLoopFromWorklist(L);
879}
880
881// RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
882// the value specified by Val in the specified loop, or we know it does NOT have
883// that value.  Rewrite any uses of LIC or of properties correlated to it.
884void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
885                                                        Constant *Val,
886                                                        bool IsEqual) {
887  assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
888
889  // FIXME: Support correlated properties, like:
890  //  for (...)
891  //    if (li1 < li2)
892  //      ...
893  //    if (li1 > li2)
894  //      ...
895
896  // FOLD boolean conditions (X|LIC), (X&LIC).  Fold conditional branches,
897  // selects, switches.
898  std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
899  std::vector<Instruction*> Worklist;
900
901  // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
902  // in the loop with the appropriate one directly.
903  if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
904    Value *Replacement;
905    if (IsEqual)
906      Replacement = Val;
907    else
908      Replacement = Context->getConstantInt(Type::Int1Ty,
909                                     !cast<ConstantInt>(Val)->getZExtValue());
910
911    for (unsigned i = 0, e = Users.size(); i != e; ++i)
912      if (Instruction *U = cast<Instruction>(Users[i])) {
913        if (!L->contains(U->getParent()))
914          continue;
915        U->replaceUsesOfWith(LIC, Replacement);
916        Worklist.push_back(U);
917      }
918  } else {
919    // Otherwise, we don't know the precise value of LIC, but we do know that it
920    // is certainly NOT "Val".  As such, simplify any uses in the loop that we
921    // can.  This case occurs when we unswitch switch statements.
922    for (unsigned i = 0, e = Users.size(); i != e; ++i)
923      if (Instruction *U = cast<Instruction>(Users[i])) {
924        if (!L->contains(U->getParent()))
925          continue;
926
927        Worklist.push_back(U);
928
929        // If we know that LIC is not Val, use this info to simplify code.
930        if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
931          for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
932            if (SI->getCaseValue(i) == Val) {
933              // Found a dead case value.  Don't remove PHI nodes in the
934              // successor if they become single-entry, those PHI nodes may
935              // be in the Users list.
936
937              // FIXME: This is a hack.  We need to keep the successor around
938              // and hooked up so as to preserve the loop structure, because
939              // trying to update it is complicated.  So instead we preserve the
940              // loop structure and put the block on an dead code path.
941
942              BasicBlock *SISucc = SI->getSuccessor(i);
943              BasicBlock* Old = SI->getParent();
944              BasicBlock* Split = SplitBlock(Old, SI, this);
945
946              Instruction* OldTerm = Old->getTerminator();
947              BranchInst::Create(Split, SISucc,
948                                 Context->getConstantIntTrue(), OldTerm);
949
950              LPM->deleteSimpleAnalysisValue(Old->getTerminator(), L);
951              Old->getTerminator()->eraseFromParent();
952
953              PHINode *PN;
954              for (BasicBlock::iterator II = SISucc->begin();
955                   (PN = dyn_cast<PHINode>(II)); ++II) {
956                Value *InVal = PN->removeIncomingValue(Split, false);
957                PN->addIncoming(InVal, Old);
958              }
959
960              SI->removeCase(i);
961              break;
962            }
963          }
964        }
965
966        // TODO: We could do other simplifications, for example, turning
967        // LIC == Val -> false.
968      }
969  }
970
971  SimplifyCode(Worklist, L);
972}
973
974/// SimplifyCode - Okay, now that we have simplified some instructions in the
975/// loop, walk over it and constant prop, dce, and fold control flow where
976/// possible.  Note that this is effectively a very simple loop-structure-aware
977/// optimizer.  During processing of this loop, L could very well be deleted, so
978/// it must not be used.
979///
980/// FIXME: When the loop optimizer is more mature, separate this out to a new
981/// pass.
982///
983void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
984  while (!Worklist.empty()) {
985    Instruction *I = Worklist.back();
986    Worklist.pop_back();
987
988    // Simple constant folding.
989    if (Constant *C = ConstantFoldInstruction(I, Context)) {
990      ReplaceUsesOfWith(I, C, Worklist, L, LPM);
991      continue;
992    }
993
994    // Simple DCE.
995    if (isInstructionTriviallyDead(I)) {
996      DOUT << "Remove dead instruction '" << *I;
997
998      // Add uses to the worklist, which may be dead now.
999      for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1000        if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1001          Worklist.push_back(Use);
1002      LPM->deleteSimpleAnalysisValue(I, L);
1003      RemoveFromWorklist(I, Worklist);
1004      I->eraseFromParent();
1005      ++NumSimplify;
1006      continue;
1007    }
1008
1009    // Special case hacks that appear commonly in unswitched code.
1010    switch (I->getOpcode()) {
1011    case Instruction::Select:
1012      if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
1013        ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist, L,
1014                          LPM);
1015        continue;
1016      }
1017      break;
1018    case Instruction::And:
1019      if (isa<ConstantInt>(I->getOperand(0)) &&
1020          I->getOperand(0)->getType() == Type::Int1Ty)   // constant -> RHS
1021        cast<BinaryOperator>(I)->swapOperands();
1022      if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1023        if (CB->getType() == Type::Int1Ty) {
1024          if (CB->isOne())      // X & 1 -> X
1025            ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
1026          else                  // X & 0 -> 0
1027            ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
1028          continue;
1029        }
1030      break;
1031    case Instruction::Or:
1032      if (isa<ConstantInt>(I->getOperand(0)) &&
1033          I->getOperand(0)->getType() == Type::Int1Ty)   // constant -> RHS
1034        cast<BinaryOperator>(I)->swapOperands();
1035      if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1036        if (CB->getType() == Type::Int1Ty) {
1037          if (CB->isOne())   // X | 1 -> 1
1038            ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
1039          else                  // X | 0 -> X
1040            ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
1041          continue;
1042        }
1043      break;
1044    case Instruction::Br: {
1045      BranchInst *BI = cast<BranchInst>(I);
1046      if (BI->isUnconditional()) {
1047        // If BI's parent is the only pred of the successor, fold the two blocks
1048        // together.
1049        BasicBlock *Pred = BI->getParent();
1050        BasicBlock *Succ = BI->getSuccessor(0);
1051        BasicBlock *SinglePred = Succ->getSinglePredecessor();
1052        if (!SinglePred) continue;  // Nothing to do.
1053        assert(SinglePred == Pred && "CFG broken");
1054
1055        DOUT << "Merging blocks: " << Pred->getName() << " <- "
1056             << Succ->getName() << "\n";
1057
1058        // Resolve any single entry PHI nodes in Succ.
1059        while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1060          ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
1061
1062        // Move all of the successor contents from Succ to Pred.
1063        Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1064                                   Succ->end());
1065        LPM->deleteSimpleAnalysisValue(BI, L);
1066        BI->eraseFromParent();
1067        RemoveFromWorklist(BI, Worklist);
1068
1069        // If Succ has any successors with PHI nodes, update them to have
1070        // entries coming from Pred instead of Succ.
1071        Succ->replaceAllUsesWith(Pred);
1072
1073        // Remove Succ from the loop tree.
1074        LI->removeBlock(Succ);
1075        LPM->deleteSimpleAnalysisValue(Succ, L);
1076        Succ->eraseFromParent();
1077        ++NumSimplify;
1078      } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
1079        // Conditional branch.  Turn it into an unconditional branch, then
1080        // remove dead blocks.
1081        break;  // FIXME: Enable.
1082
1083        DOUT << "Folded branch: " << *BI;
1084        BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1085        BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
1086        DeadSucc->removePredecessor(BI->getParent(), true);
1087        Worklist.push_back(BranchInst::Create(LiveSucc, BI));
1088        LPM->deleteSimpleAnalysisValue(BI, L);
1089        BI->eraseFromParent();
1090        RemoveFromWorklist(BI, Worklist);
1091        ++NumSimplify;
1092
1093        RemoveBlockIfDead(DeadSucc, Worklist, L);
1094      }
1095      break;
1096    }
1097    }
1098  }
1099}
1100