LLVM API Documentation

Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members | Related Pages

LoopUnswitch.cpp

Go to the documentation of this file.
00001 //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass transforms loops that contain branches on loop-invariant conditions
00011 // to have multiple loops.  For example, it turns the left into the right code:
00012 //
00013 //  for (...)                  if (lic)
00014 //    A                          for (...)
00015 //    if (lic)                     A; B; C
00016 //      B                      else
00017 //    C                          for (...)
00018 //                                 A; C
00019 //
00020 // This can increase the size of the code exponentially (doubling it every time
00021 // a loop is unswitched) so we only unswitch if the resultant code will be
00022 // smaller than a threshold.
00023 //
00024 // This pass expects LICM to be run before it to hoist invariant conditions out
00025 // of the loop, to make the unswitching opportunity obvious.
00026 //
00027 //===----------------------------------------------------------------------===//
00028 
00029 #define DEBUG_TYPE "loop-unswitch"
00030 #include "llvm/Transforms/Scalar.h"
00031 #include "llvm/Constants.h"
00032 #include "llvm/DerivedTypes.h"
00033 #include "llvm/Function.h"
00034 #include "llvm/Instructions.h"
00035 #include "llvm/Analysis/ConstantFolding.h"
00036 #include "llvm/Analysis/LoopInfo.h"
00037 #include "llvm/Analysis/LoopPass.h"
00038 #include "llvm/Analysis/Dominators.h"
00039 #include "llvm/Transforms/Utils/Cloning.h"
00040 #include "llvm/Transforms/Utils/Local.h"
00041 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00042 #include "llvm/ADT/Statistic.h"
00043 #include "llvm/ADT/SmallPtrSet.h"
00044 #include "llvm/Support/CommandLine.h"
00045 #include "llvm/Support/Compiler.h"
00046 #include "llvm/Support/Debug.h"
00047 #include <algorithm>
00048 #include <set>
00049 using namespace llvm;
00050 
00051 STATISTIC(NumBranches, "Number of branches unswitched");
00052 STATISTIC(NumSwitches, "Number of switches unswitched");
00053 STATISTIC(NumSelects , "Number of selects unswitched");
00054 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
00055 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
00056 
00057 static cl::opt<unsigned>
00058 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
00059           cl::init(10), cl::Hidden);
00060   
00061 namespace {
00062   class VISIBILITY_HIDDEN LoopUnswitch : public LoopPass {
00063     LoopInfo *LI;  // Loop information
00064     LPPassManager *LPM;
00065 
00066     // LoopProcessWorklist - Used to check if second loop needs processing
00067     // after RewriteLoopBodyWithConditionConstant rewrites first loop.
00068     std::vector<Loop*> LoopProcessWorklist;
00069     SmallPtrSet<Value *,8> UnswitchedVals;
00070     
00071     bool OptimizeForSize;
00072     bool redoLoop;
00073 
00074     Loop *currentLoop;
00075     DominanceFrontier *DF;
00076     DominatorTree *DT;
00077     BasicBlock *loopHeader;
00078     BasicBlock *loopPreheader;
00079     
00080     // LoopBlocks contains all of the basic blocks of the loop, including the
00081     // preheader of the loop, the body of the loop, and the exit blocks of the 
00082     // loop, in that order.
00083     std::vector<BasicBlock*> LoopBlocks;
00084     // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
00085     std::vector<BasicBlock*> NewBlocks;
00086 
00087   public:
00088     static char ID; // Pass ID, replacement for typeid
00089     explicit LoopUnswitch(bool Os = false) : 
00090       LoopPass((intptr_t)&ID), OptimizeForSize(Os), redoLoop(false), 
00091       currentLoop(NULL), DF(NULL), DT(NULL), loopHeader(NULL),
00092       loopPreheader(NULL) {}
00093 
00094     bool runOnLoop(Loop *L, LPPassManager &LPM);
00095     bool processCurrentLoop();
00096 
00097     /// This transformation requires natural loop information & requires that
00098     /// loop preheaders be inserted into the CFG...
00099     ///
00100     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00101       AU.addRequiredID(LoopSimplifyID);
00102       AU.addPreservedID(LoopSimplifyID);
00103       AU.addRequired<LoopInfo>();
00104       AU.addPreserved<LoopInfo>();
00105       AU.addRequiredID(LCSSAID);
00106       AU.addPreservedID(LCSSAID);
00107       AU.addPreserved<DominatorTree>();
00108       AU.addPreserved<DominanceFrontier>();
00109     }
00110 
00111   private:
00112 
00113     /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
00114     /// remove it.
00115     void RemoveLoopFromWorklist(Loop *L) {
00116       std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
00117                                                  LoopProcessWorklist.end(), L);
00118       if (I != LoopProcessWorklist.end())
00119         LoopProcessWorklist.erase(I);
00120     }
00121 
00122     void initLoopData() {
00123       loopHeader = currentLoop->getHeader();
00124       loopPreheader = currentLoop->getLoopPreheader();
00125     }
00126 
00127     /// Split all of the edges from inside the loop to their exit blocks.
00128     /// Update the appropriate Phi nodes as we do so.
00129     void SplitExitEdges(Loop *L, const SmallVector<BasicBlock *, 8> &ExitBlocks);
00130 
00131     bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
00132     unsigned getLoopUnswitchCost(Value *LIC);
00133     void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
00134                                   BasicBlock *ExitBlock);
00135     void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
00136 
00137     void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
00138                                               Constant *Val, bool isEqual);
00139 
00140     void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
00141                                         BasicBlock *TrueDest, 
00142                                         BasicBlock *FalseDest,
00143                                         Instruction *InsertPt);
00144 
00145     void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
00146     void RemoveBlockIfDead(BasicBlock *BB,
00147                            std::vector<Instruction*> &Worklist, Loop *l);
00148     void RemoveLoopFromHierarchy(Loop *L);
00149     bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = 0,
00150                                     BasicBlock **LoopExit = 0);
00151 
00152   };
00153 }
00154 char LoopUnswitch::ID = 0;
00155 static RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
00156 
00157 LoopPass *llvm::createLoopUnswitchPass(bool Os) { 
00158   return new LoopUnswitch(Os); 
00159 }
00160 
00161 /// FindLIVLoopCondition - Cond is a condition that occurs in L.  If it is
00162 /// invariant in the loop, or has an invariant piece, return the invariant.
00163 /// Otherwise, return null.
00164 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
00165   // Constants should be folded, not unswitched on!
00166   if (isa<Constant>(Cond)) return false;
00167 
00168   // TODO: Handle: br (VARIANT|INVARIANT).
00169   // TODO: Hoist simple expressions out of loops.
00170   if (L->isLoopInvariant(Cond)) return Cond;
00171   
00172   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
00173     if (BO->getOpcode() == Instruction::And ||
00174         BO->getOpcode() == Instruction::Or) {
00175       // If either the left or right side is invariant, we can unswitch on this,
00176       // which will cause the branch to go away in one loop and the condition to
00177       // simplify in the other one.
00178       if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
00179         return LHS;
00180       if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
00181         return RHS;
00182     }
00183   
00184   return 0;
00185 }
00186 
00187 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
00188   LI = &getAnalysis<LoopInfo>();
00189   LPM = &LPM_Ref;
00190   DF = getAnalysisToUpdate<DominanceFrontier>();
00191   DT = getAnalysisToUpdate<DominatorTree>();
00192   currentLoop = L;
00193   bool Changed = false;
00194   do {
00195     assert(currentLoop->isLCSSAForm());
00196     redoLoop = false;
00197     Changed |= processCurrentLoop();
00198   } while(redoLoop);
00199 
00200   return Changed;
00201 }
00202 
00203 /// processCurrentLoop - Do actual work and unswitch loop if possible 
00204 /// and profitable.
00205 bool LoopUnswitch::processCurrentLoop() {
00206   bool Changed = false;
00207 
00208   // Loop over all of the basic blocks in the loop.  If we find an interior
00209   // block that is branching on a loop-invariant condition, we can unswitch this
00210   // loop.
00211   for (Loop::block_iterator I = currentLoop->block_begin(), 
00212          E = currentLoop->block_end();
00213        I != E; ++I) {
00214     TerminatorInst *TI = (*I)->getTerminator();
00215     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
00216       // If this isn't branching on an invariant condition, we can't unswitch
00217       // it.
00218       if (BI->isConditional()) {
00219         // See if this, or some part of it, is loop invariant.  If so, we can
00220         // unswitch on it if we desire.
00221         Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), 
00222                                                currentLoop, Changed);
00223         if (LoopCond && UnswitchIfProfitable(LoopCond, 
00224                                              ConstantInt::getTrue())) {
00225           ++NumBranches;
00226           return true;
00227         }
00228       }      
00229     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
00230       Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), 
00231                                              currentLoop, Changed);
00232       if (LoopCond && SI->getNumCases() > 1) {
00233         // Find a value to unswitch on:
00234         // FIXME: this should chose the most expensive case!
00235         Constant *UnswitchVal = SI->getCaseValue(1);
00236         // Do not process same value again and again.
00237         if (!UnswitchedVals.insert(UnswitchVal))
00238           continue;
00239 
00240         if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
00241           ++NumSwitches;
00242           return true;
00243         }
00244       }
00245     }
00246     
00247     // Scan the instructions to check for unswitchable values.
00248     for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end(); 
00249          BBI != E; ++BBI)
00250       if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
00251         Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), 
00252                                                currentLoop, Changed);
00253         if (LoopCond && UnswitchIfProfitable(LoopCond, 
00254                                              ConstantInt::getTrue())) {
00255           ++NumSelects;
00256           return true;
00257         }
00258       }
00259   }
00260   return Changed;
00261 }
00262 
00263 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
00264 ///   1. Exit the loop with no side effects.
00265 ///   2. Branch to the latch block with no side-effects.
00266 ///
00267 /// If these conditions are true, we return true and set ExitBB to the block we
00268 /// exit through.
00269 ///
00270 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
00271                                          BasicBlock *&ExitBB,
00272                                          std::set<BasicBlock*> &Visited) {
00273   if (!Visited.insert(BB).second) {
00274     // Already visited and Ok, end of recursion.
00275     return true;
00276   } else if (!L->contains(BB)) {
00277     // Otherwise, this is a loop exit, this is fine so long as this is the
00278     // first exit.
00279     if (ExitBB != 0) return false;
00280     ExitBB = BB;
00281     return true;
00282   }
00283   
00284   // Otherwise, this is an unvisited intra-loop node.  Check all successors.
00285   for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
00286     // Check to see if the successor is a trivial loop exit.
00287     if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
00288       return false;
00289   }
00290 
00291   // Okay, everything after this looks good, check to make sure that this block
00292   // doesn't include any side effects.
00293   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00294     if (I->mayWriteToMemory())
00295       return false;
00296   
00297   return true;
00298 }
00299 
00300 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
00301 /// leads to an exit from the specified loop, and has no side-effects in the 
00302 /// process.  If so, return the block that is exited to, otherwise return null.
00303 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
00304   std::set<BasicBlock*> Visited;
00305   Visited.insert(L->getHeader());  // Branches to header are ok.
00306   BasicBlock *ExitBB = 0;
00307   if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
00308     return ExitBB;
00309   return 0;
00310 }
00311 
00312 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
00313 /// trivial: that is, that the condition controls whether or not the loop does
00314 /// anything at all.  If this is a trivial condition, unswitching produces no
00315 /// code duplications (equivalently, it produces a simpler loop and a new empty
00316 /// loop, which gets deleted).
00317 ///
00318 /// If this is a trivial condition, return true, otherwise return false.  When
00319 /// returning true, this sets Cond and Val to the condition that controls the
00320 /// trivial condition: when Cond dynamically equals Val, the loop is known to
00321 /// exit.  Finally, this sets LoopExit to the BB that the loop exits to when
00322 /// Cond == Val.
00323 ///
00324 bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
00325                                        BasicBlock **LoopExit) {
00326   BasicBlock *Header = currentLoop->getHeader();
00327   TerminatorInst *HeaderTerm = Header->getTerminator();
00328   
00329   BasicBlock *LoopExitBB = 0;
00330   if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
00331     // If the header block doesn't end with a conditional branch on Cond, we
00332     // can't handle it.
00333     if (!BI->isConditional() || BI->getCondition() != Cond)
00334       return false;
00335   
00336     // Check to see if a successor of the branch is guaranteed to go to the
00337     // latch block or exit through a one exit block without having any 
00338     // side-effects.  If so, determine the value of Cond that causes it to do
00339     // this.
00340     if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop, 
00341                                              BI->getSuccessor(0)))) {
00342       if (Val) *Val = ConstantInt::getTrue();
00343     } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop, 
00344                                                     BI->getSuccessor(1)))) {
00345       if (Val) *Val = ConstantInt::getFalse();
00346     }
00347   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
00348     // If this isn't a switch on Cond, we can't handle it.
00349     if (SI->getCondition() != Cond) return false;
00350     
00351     // Check to see if a successor of the switch is guaranteed to go to the
00352     // latch block or exit through a one exit block without having any 
00353     // side-effects.  If so, determine the value of Cond that causes it to do
00354     // this.  Note that we can't trivially unswitch on the default case.
00355     for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
00356       if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop, 
00357                                                SI->getSuccessor(i)))) {
00358         // Okay, we found a trivial case, remember the value that is trivial.
00359         if (Val) *Val = SI->getCaseValue(i);
00360         break;
00361       }
00362   }
00363 
00364   // If we didn't find a single unique LoopExit block, or if the loop exit block
00365   // contains phi nodes, this isn't trivial.
00366   if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
00367     return false;   // Can't handle this.
00368   
00369   if (LoopExit) *LoopExit = LoopExitBB;
00370   
00371   // We already know that nothing uses any scalar values defined inside of this
00372   // loop.  As such, we just have to check to see if this loop will execute any
00373   // side-effecting instructions (e.g. stores, calls, volatile loads) in the
00374   // part of the loop that the code *would* execute.  We already checked the
00375   // tail, check the header now.
00376   for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
00377     if (I->mayWriteToMemory())
00378       return false;
00379   return true;
00380 }
00381 
00382 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
00383 /// we choose to unswitch current loop on the specified value.
00384 ///
00385 unsigned LoopUnswitch::getLoopUnswitchCost(Value *LIC) {
00386   // If the condition is trivial, always unswitch.  There is no code growth for
00387   // this case.
00388   if (IsTrivialUnswitchCondition(LIC))
00389     return 0;
00390   
00391   // FIXME: This is really overly conservative.  However, more liberal 
00392   // estimations have thus far resulted in excessive unswitching, which is bad
00393   // both in compile time and in code size.  This should be replaced once
00394   // someone figures out how a good estimation.
00395   return currentLoop->getBlocks().size();
00396   
00397   unsigned Cost = 0;
00398   // FIXME: this is brain dead.  It should take into consideration code
00399   // shrinkage.
00400   for (Loop::block_iterator I = currentLoop->block_begin(), 
00401          E = currentLoop->block_end();
00402        I != E; ++I) {
00403     BasicBlock *BB = *I;
00404     // Do not include empty blocks in the cost calculation.  This happen due to
00405     // loop canonicalization and will be removed.
00406     if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
00407       continue;
00408     
00409     // Count basic blocks.
00410     ++Cost;
00411   }
00412 
00413   return Cost;
00414 }
00415 
00416 /// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
00417 /// LoopCond == Val to simplify the loop.  If we decide that this is profitable,
00418 /// unswitch the loop, reprocess the pieces, then return true.
00419 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val){
00420   // Check to see if it would be profitable to unswitch current loop.
00421   unsigned Cost = getLoopUnswitchCost(LoopCond);
00422 
00423   // Do not do non-trivial unswitch while optimizing for size.
00424   if (Cost && OptimizeForSize)
00425     return false;
00426 
00427   if (Cost > Threshold) {
00428     // FIXME: this should estimate growth by the amount of code shared by the
00429     // resultant unswitched loops.
00430     //
00431     DOUT << "NOT unswitching loop %"
00432          << currentLoop->getHeader()->getName() << ", cost too high: "
00433          << currentLoop->getBlocks().size() << "\n";
00434     return false;
00435   }
00436 
00437   initLoopData();
00438 
00439   Constant *CondVal;
00440   BasicBlock *ExitBlock;
00441   if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
00442     UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
00443   } else {
00444     UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
00445   }
00446 
00447   // FIXME: Reconstruct dom info, because it is not preserved properly.
00448   Function *F = loopHeader->getParent();
00449   if (DT)
00450     DT->runOnFunction(*F);
00451   if (DF)
00452     DF->runOnFunction(*F);
00453   return true;
00454 }
00455 
00456 // RemapInstruction - Convert the instruction operands from referencing the
00457 // current values into those specified by ValueMap.
00458 //
00459 static inline void RemapInstruction(Instruction *I,
00460                                     DenseMap<const Value *, Value*> &ValueMap) {
00461   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
00462     Value *Op = I->getOperand(op);
00463     DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
00464     if (It != ValueMap.end()) Op = It->second;
00465     I->setOperand(op, Op);
00466   }
00467 }
00468 
00469 /// CloneLoop - Recursively clone the specified loop and all of its children,
00470 /// mapping the blocks with the specified map.
00471 static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
00472                        LoopInfo *LI, LPPassManager *LPM) {
00473   Loop *New = new Loop();
00474 
00475   LPM->insertLoop(New, PL);
00476 
00477   // Add all of the blocks in L to the new loop.
00478   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
00479        I != E; ++I)
00480     if (LI->getLoopFor(*I) == L)
00481       New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), LI->getBase());
00482 
00483   // Add all of the subloops to the new loop.
00484   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
00485     CloneLoop(*I, New, VM, LI, LPM);
00486 
00487   return New;
00488 }
00489 
00490 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
00491 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest.  Insert the
00492 /// code immediately before InsertPt.
00493 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
00494                                                   BasicBlock *TrueDest,
00495                                                   BasicBlock *FalseDest,
00496                                                   Instruction *InsertPt) {
00497   // Insert a conditional branch on LIC to the two preheaders.  The original
00498   // code is the true version and the new code is the false version.
00499   Value *BranchVal = LIC;
00500   if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
00501     BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
00502   else if (Val != ConstantInt::getTrue())
00503     // We want to enter the new loop when the condition is true.
00504     std::swap(TrueDest, FalseDest);
00505 
00506   // Insert the new branch.
00507   BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
00508 }
00509 
00510 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
00511 /// condition in it (a cond branch from its header block to its latch block,
00512 /// where the path through the loop that doesn't execute its body has no 
00513 /// side-effects), unswitch it.  This doesn't involve any code duplication, just
00514 /// moving the conditional branch outside of the loop and updating loop info.
00515 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, 
00516                                             Constant *Val, 
00517                                             BasicBlock *ExitBlock) {
00518   DOUT << "loop-unswitch: Trivial-Unswitch loop %"
00519        << loopHeader->getName() << " [" << L->getBlocks().size()
00520        << " blocks] in Function " << L->getHeader()->getParent()->getName()
00521        << " on cond: " << *Val << " == " << *Cond << "\n";
00522   
00523   // First step, split the preheader, so that we know that there is a safe place
00524   // to insert the conditional branch.  We will change loopPreheader to have a
00525   // conditional branch on Cond.
00526   BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, this);
00527 
00528   // Now that we have a place to insert the conditional branch, create a place
00529   // to branch to: this is the exit block out of the loop that we should
00530   // short-circuit to.
00531   
00532   // Split this block now, so that the loop maintains its exit block, and so
00533   // that the jump from the preheader can execute the contents of the exit block
00534   // without actually branching to it (the exit block should be dominated by the
00535   // loop header, not the preheader).
00536   assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
00537   BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), this);
00538     
00539   // Okay, now we have a position to branch from and a position to branch to, 
00540   // insert the new conditional branch.
00541   EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH, 
00542                                  loopPreheader->getTerminator());
00543   LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
00544   loopPreheader->getTerminator()->eraseFromParent();
00545 
00546   // We need to reprocess this loop, it could be unswitched again.
00547   redoLoop = true;
00548   
00549   // Now that we know that the loop is never entered when this condition is a
00550   // particular value, rewrite the loop with this info.  We know that this will
00551   // at least eliminate the old branch.
00552   RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
00553   ++NumTrivial;
00554 }
00555 
00556 /// SplitExitEdges - Split all of the edges from inside the loop to their exit
00557 /// blocks.  Update the appropriate Phi nodes as we do so.
00558 void LoopUnswitch::SplitExitEdges(Loop *L, 
00559                                 const SmallVector<BasicBlock *, 8> &ExitBlocks) 
00560 {
00561 
00562   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
00563     BasicBlock *ExitBlock = ExitBlocks[i];
00564     std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
00565 
00566     for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
00567       BasicBlock* NewExitBlock = SplitEdge(Preds[j], ExitBlock, this);
00568       BasicBlock* StartBlock = Preds[j];
00569       BasicBlock* EndBlock;
00570       if (NewExitBlock->getSinglePredecessor() == ExitBlock) {
00571         EndBlock = NewExitBlock;
00572         NewExitBlock = EndBlock->getSinglePredecessor();;
00573       } else {
00574         EndBlock = ExitBlock;
00575       }
00576       
00577       std::set<PHINode*> InsertedPHIs;
00578       PHINode* OldLCSSA = 0;
00579       for (BasicBlock::iterator I = EndBlock->begin();
00580            (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
00581         Value* OldValue = OldLCSSA->getIncomingValueForBlock(NewExitBlock);
00582         PHINode* NewLCSSA = PHINode::Create(OldLCSSA->getType(),
00583                                             OldLCSSA->getName() + ".us-lcssa",
00584                                             NewExitBlock->getTerminator());
00585         NewLCSSA->addIncoming(OldValue, StartBlock);
00586         OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(NewExitBlock),
00587                                    NewLCSSA);
00588         InsertedPHIs.insert(NewLCSSA);
00589       }
00590 
00591       BasicBlock::iterator InsertPt = EndBlock->getFirstNonPHI();
00592       for (BasicBlock::iterator I = NewExitBlock->begin();
00593          (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
00594          ++I) {
00595         PHINode *NewLCSSA = PHINode::Create(OldLCSSA->getType(),
00596                                             OldLCSSA->getName() + ".us-lcssa",
00597                                             InsertPt);
00598         OldLCSSA->replaceAllUsesWith(NewLCSSA);
00599         NewLCSSA->addIncoming(OldLCSSA, NewExitBlock);
00600       }
00601 
00602     }    
00603   }
00604 
00605 }
00606 
00607 /// UnswitchNontrivialCondition - We determined that the loop is profitable 
00608 /// to unswitch when LIC equal Val.  Split it into loop versions and test the 
00609 /// condition outside of either loop.  Return the loops created as Out1/Out2.
00610 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val, 
00611                                                Loop *L) {
00612   Function *F = loopHeader->getParent();
00613   DOUT << "loop-unswitch: Unswitching loop %"
00614        << loopHeader->getName() << " [" << L->getBlocks().size()
00615        << " blocks] in Function " << F->getName()
00616        << " when '" << *Val << "' == " << *LIC << "\n";
00617 
00618   LoopBlocks.clear();
00619   NewBlocks.clear();
00620 
00621   // First step, split the preheader and exit blocks, and add these blocks to
00622   // the LoopBlocks list.
00623   BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, this);
00624   LoopBlocks.push_back(NewPreheader);
00625 
00626   // We want the loop to come after the preheader, but before the exit blocks.
00627   LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
00628 
00629   SmallVector<BasicBlock*, 8> ExitBlocks;
00630   L->getUniqueExitBlocks(ExitBlocks);
00631 
00632   // Split all of the edges from inside the loop to their exit blocks.  Update
00633   // the appropriate Phi nodes as we do so.
00634   SplitExitEdges(L, ExitBlocks);
00635 
00636   // The exit blocks may have been changed due to edge splitting, recompute.
00637   ExitBlocks.clear();
00638   L->getUniqueExitBlocks(ExitBlocks);
00639 
00640   // Add exit blocks to the loop blocks.
00641   LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
00642 
00643   // Next step, clone all of the basic blocks that make up the loop (including
00644   // the loop preheader and exit blocks), keeping track of the mapping between
00645   // the instructions and blocks.
00646   NewBlocks.reserve(LoopBlocks.size());
00647   DenseMap<const Value*, Value*> ValueMap;
00648   for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
00649     BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
00650     NewBlocks.push_back(New);
00651     ValueMap[LoopBlocks[i]] = New;  // Keep the BB mapping.
00652     LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], New, L);
00653   }
00654 
00655   // Splice the newly inserted blocks into the function right before the
00656   // original preheader.
00657   F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
00658                                 NewBlocks[0], F->end());
00659 
00660   // Now we create the new Loop object for the versioned loop.
00661   Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
00662   Loop *ParentLoop = L->getParentLoop();
00663   if (ParentLoop) {
00664     // Make sure to add the cloned preheader and exit blocks to the parent loop
00665     // as well.
00666     ParentLoop->addBasicBlockToLoop(NewBlocks[0], LI->getBase());
00667   }
00668   
00669   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
00670     BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
00671     // The new exit block should be in the same loop as the old one.
00672     if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
00673       ExitBBLoop->addBasicBlockToLoop(NewExit, LI->getBase());
00674     
00675     assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
00676            "Exit block should have been split to have one successor!");
00677     BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
00678 
00679     // If the successor of the exit block had PHI nodes, add an entry for
00680     // NewExit.
00681     PHINode *PN;
00682     for (BasicBlock::iterator I = ExitSucc->begin();
00683          (PN = dyn_cast<PHINode>(I)); ++I) {
00684       Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
00685       DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
00686       if (It != ValueMap.end()) V = It->second;
00687       PN->addIncoming(V, NewExit);
00688     }
00689   }
00690 
00691   // Rewrite the code to refer to itself.
00692   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
00693     for (BasicBlock::iterator I = NewBlocks[i]->begin(),
00694            E = NewBlocks[i]->end(); I != E; ++I)
00695       RemapInstruction(I, ValueMap);
00696   
00697   // Rewrite the original preheader to select between versions of the loop.
00698   BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
00699   assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
00700          "Preheader splitting did not work correctly!");
00701 
00702   // Emit the new branch that selects between the two versions of this loop.
00703   EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
00704   LPM->deleteSimpleAnalysisValue(OldBR, L);
00705   OldBR->eraseFromParent();
00706 
00707   LoopProcessWorklist.push_back(NewLoop);
00708   redoLoop = true;
00709 
00710   // Now we rewrite the original code to know that the condition is true and the
00711   // new code to know that the condition is false.
00712   RewriteLoopBodyWithConditionConstant(L      , LIC, Val, false);
00713   
00714   // It's possible that simplifying one loop could cause the other to be
00715   // deleted.  If so, don't simplify it.
00716   if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
00717     RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
00718 
00719 }
00720 
00721 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
00722 /// specified.
00723 static void RemoveFromWorklist(Instruction *I, 
00724                                std::vector<Instruction*> &Worklist) {
00725   std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
00726                                                      Worklist.end(), I);
00727   while (WI != Worklist.end()) {
00728     unsigned Offset = WI-Worklist.begin();
00729     Worklist.erase(WI);
00730     WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
00731   }
00732 }
00733 
00734 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
00735 /// program, replacing all uses with V and update the worklist.
00736 static void ReplaceUsesOfWith(Instruction *I, Value *V, 
00737                               std::vector<Instruction*> &Worklist,
00738                               Loop *L, LPPassManager *LPM) {
00739   DOUT << "Replace with '" << *V << "': " << *I;
00740 
00741   // Add uses to the worklist, which may be dead now.
00742   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
00743     if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
00744       Worklist.push_back(Use);
00745 
00746   // Add users to the worklist which may be simplified now.
00747   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
00748        UI != E; ++UI)
00749     Worklist.push_back(cast<Instruction>(*UI));
00750   LPM->deleteSimpleAnalysisValue(I, L);
00751   RemoveFromWorklist(I, Worklist);
00752   I->replaceAllUsesWith(V);
00753   I->eraseFromParent();
00754   ++NumSimplify;
00755 }
00756 
00757 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
00758 /// information, and remove any dead successors it has.
00759 ///
00760 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
00761                                      std::vector<Instruction*> &Worklist,
00762                                      Loop *L) {
00763   if (pred_begin(BB) != pred_end(BB)) {
00764     // This block isn't dead, since an edge to BB was just removed, see if there
00765     // are any easy simplifications we can do now.
00766     if (BasicBlock *Pred = BB->getSinglePredecessor()) {
00767       // If it has one pred, fold phi nodes in BB.
00768       while (isa<PHINode>(BB->begin()))
00769         ReplaceUsesOfWith(BB->begin(), 
00770                           cast<PHINode>(BB->begin())->getIncomingValue(0), 
00771                           Worklist, L, LPM);
00772       
00773       // If this is the header of a loop and the only pred is the latch, we now
00774       // have an unreachable loop.
00775       if (Loop *L = LI->getLoopFor(BB))
00776         if (loopHeader == BB && L->contains(Pred)) {
00777           // Remove the branch from the latch to the header block, this makes
00778           // the header dead, which will make the latch dead (because the header
00779           // dominates the latch).
00780           LPM->deleteSimpleAnalysisValue(Pred->getTerminator(), L);
00781           Pred->getTerminator()->eraseFromParent();
00782           new UnreachableInst(Pred);
00783           
00784           // The loop is now broken, remove it from LI.
00785           RemoveLoopFromHierarchy(L);
00786           
00787           // Reprocess the header, which now IS dead.
00788           RemoveBlockIfDead(BB, Worklist, L);
00789           return;
00790         }
00791       
00792       // If pred ends in a uncond branch, add uncond branch to worklist so that
00793       // the two blocks will get merged.
00794       if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
00795         if (BI->isUnconditional())
00796           Worklist.push_back(BI);
00797     }
00798     return;
00799   }
00800 
00801   DOUT << "Nuking dead block: " << *BB;
00802   
00803   // Remove the instructions in the basic block from the worklist.
00804   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00805     RemoveFromWorklist(I, Worklist);
00806     
00807     // Anything that uses the instructions in this basic block should have their
00808     // uses replaced with undefs.
00809     if (!I->use_empty())
00810       I->replaceAllUsesWith(UndefValue::get(I->getType()));
00811   }
00812   
00813   // If this is the edge to the header block for a loop, remove the loop and
00814   // promote all subloops.
00815   if (Loop *BBLoop = LI->getLoopFor(BB)) {
00816     if (BBLoop->getLoopLatch() == BB)
00817       RemoveLoopFromHierarchy(BBLoop);
00818   }
00819 
00820   // Remove the block from the loop info, which removes it from any loops it
00821   // was in.
00822   LI->removeBlock(BB);
00823   
00824   
00825   // Remove phi node entries in successors for this block.
00826   TerminatorInst *TI = BB->getTerminator();
00827   std::vector<BasicBlock*> Succs;
00828   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
00829     Succs.push_back(TI->getSuccessor(i));
00830     TI->getSuccessor(i)->removePredecessor(BB);
00831   }
00832   
00833   // Unique the successors, remove anything with multiple uses.
00834   std::sort(Succs.begin(), Succs.end());
00835   Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
00836   
00837   // Remove the basic block, including all of the instructions contained in it.
00838   LPM->deleteSimpleAnalysisValue(BB, L);  
00839   BB->eraseFromParent();
00840   // Remove successor blocks here that are not dead, so that we know we only
00841   // have dead blocks in this list.  Nondead blocks have a way of becoming dead,
00842   // then getting removed before we revisit them, which is badness.
00843   //
00844   for (unsigned i = 0; i != Succs.size(); ++i)
00845     if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
00846       // One exception is loop headers.  If this block was the preheader for a
00847       // loop, then we DO want to visit the loop so the loop gets deleted.
00848       // We know that if the successor is a loop header, that this loop had to
00849       // be the preheader: the case where this was the latch block was handled
00850       // above and headers can only have two predecessors.
00851       if (!LI->isLoopHeader(Succs[i])) {
00852         Succs.erase(Succs.begin()+i);
00853         --i;
00854       }
00855     }
00856   
00857   for (unsigned i = 0, e = Succs.size(); i != e; ++i)
00858     RemoveBlockIfDead(Succs[i], Worklist, L);
00859 }
00860 
00861 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
00862 /// become unwrapped, either because the backedge was deleted, or because the
00863 /// edge into the header was removed.  If the edge into the header from the
00864 /// latch block was removed, the loop is unwrapped but subloops are still alive,
00865 /// so they just reparent loops.  If the loops are actually dead, they will be
00866 /// removed later.
00867 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
00868   LPM->deleteLoopFromQueue(L);
00869   RemoveLoopFromWorklist(L);
00870 }
00871 
00872 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
00873 // the value specified by Val in the specified loop, or we know it does NOT have
00874 // that value.  Rewrite any uses of LIC or of properties correlated to it.
00875 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
00876                                                         Constant *Val,
00877                                                         bool IsEqual) {
00878   assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
00879   
00880   // FIXME: Support correlated properties, like:
00881   //  for (...)
00882   //    if (li1 < li2)
00883   //      ...
00884   //    if (li1 > li2)
00885   //      ...
00886   
00887   // FOLD boolean conditions (X|LIC), (X&LIC).  Fold conditional branches,
00888   // selects, switches.
00889   std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
00890   std::vector<Instruction*> Worklist;
00891 
00892   // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
00893   // in the loop with the appropriate one directly.
00894   if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
00895     Value *Replacement;
00896     if (IsEqual)
00897       Replacement = Val;
00898     else
00899       Replacement = ConstantInt::get(Type::Int1Ty, 
00900                                      !cast<ConstantInt>(Val)->getZExtValue());
00901     
00902     for (unsigned i = 0, e = Users.size(); i != e; ++i)
00903       if (Instruction *U = cast<Instruction>(Users[i])) {
00904         if (!L->contains(U->getParent()))
00905           continue;
00906         U->replaceUsesOfWith(LIC, Replacement);
00907         Worklist.push_back(U);
00908       }
00909   } else {
00910     // Otherwise, we don't know the precise value of LIC, but we do know that it
00911     // is certainly NOT "Val".  As such, simplify any uses in the loop that we
00912     // can.  This case occurs when we unswitch switch statements.
00913     for (unsigned i = 0, e = Users.size(); i != e; ++i)
00914       if (Instruction *U = cast<Instruction>(Users[i])) {
00915         if (!L->contains(U->getParent()))
00916           continue;
00917 
00918         Worklist.push_back(U);
00919 
00920         // If we know that LIC is not Val, use this info to simplify code.
00921         if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
00922           for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
00923             if (SI->getCaseValue(i) == Val) {
00924               // Found a dead case value.  Don't remove PHI nodes in the 
00925               // successor if they become single-entry, those PHI nodes may
00926               // be in the Users list.
00927               
00928               // FIXME: This is a hack.  We need to keep the successor around
00929               // and hooked up so as to preserve the loop structure, because
00930               // trying to update it is complicated.  So instead we preserve the
00931               // loop structure and put the block on an dead code path.
00932               
00933               BasicBlock *SISucc = SI->getSuccessor(i);
00934               BasicBlock* Old = SI->getParent();
00935               BasicBlock* Split = SplitBlock(Old, SI, this);
00936               
00937               Instruction* OldTerm = Old->getTerminator();
00938               BranchInst::Create(Split, SISucc,
00939                                  ConstantInt::getTrue(), OldTerm);
00940 
00941               LPM->deleteSimpleAnalysisValue(Old->getTerminator(), L);
00942               Old->getTerminator()->eraseFromParent();
00943               
00944               PHINode *PN;
00945               for (BasicBlock::iterator II = SISucc->begin();
00946                    (PN = dyn_cast<PHINode>(II)); ++II) {
00947                 Value *InVal = PN->removeIncomingValue(Split, false);
00948                 PN->addIncoming(InVal, Old);
00949               }
00950 
00951               SI->removeCase(i);
00952               break;
00953             }
00954           }
00955         }
00956         
00957         // TODO: We could do other simplifications, for example, turning 
00958         // LIC == Val -> false.
00959       }
00960   }
00961   
00962   SimplifyCode(Worklist, L);
00963 }
00964 
00965 /// SimplifyCode - Okay, now that we have simplified some instructions in the 
00966 /// loop, walk over it and constant prop, dce, and fold control flow where
00967 /// possible.  Note that this is effectively a very simple loop-structure-aware
00968 /// optimizer.  During processing of this loop, L could very well be deleted, so
00969 /// it must not be used.
00970 ///
00971 /// FIXME: When the loop optimizer is more mature, separate this out to a new
00972 /// pass.
00973 ///
00974 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
00975   while (!Worklist.empty()) {
00976     Instruction *I = Worklist.back();
00977     Worklist.pop_back();
00978     
00979     // Simple constant folding.
00980     if (Constant *C = ConstantFoldInstruction(I)) {
00981       ReplaceUsesOfWith(I, C, Worklist, L, LPM);
00982       continue;
00983     }
00984     
00985     // Simple DCE.
00986     if (isInstructionTriviallyDead(I)) {
00987       DOUT << "Remove dead instruction '" << *I;
00988       
00989       // Add uses to the worklist, which may be dead now.
00990       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
00991         if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
00992           Worklist.push_back(Use);
00993       LPM->deleteSimpleAnalysisValue(I, L);
00994       RemoveFromWorklist(I, Worklist);
00995       I->eraseFromParent();
00996       ++NumSimplify;
00997       continue;
00998     }
00999     
01000     // Special case hacks that appear commonly in unswitched code.
01001     switch (I->getOpcode()) {
01002     case Instruction::Select:
01003       if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
01004         ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist, L,
01005                           LPM);
01006         continue;
01007       }
01008       break;
01009     case Instruction::And:
01010       if (isa<ConstantInt>(I->getOperand(0)) && 
01011           I->getOperand(0)->getType() == Type::Int1Ty)   // constant -> RHS
01012         cast<BinaryOperator>(I)->swapOperands();
01013       if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1))) 
01014         if (CB->getType() == Type::Int1Ty) {
01015           if (CB->isOne())      // X & 1 -> X
01016             ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
01017           else                  // X & 0 -> 0
01018             ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
01019           continue;
01020         }
01021       break;
01022     case Instruction::Or:
01023       if (isa<ConstantInt>(I->getOperand(0)) &&
01024           I->getOperand(0)->getType() == Type::Int1Ty)   // constant -> RHS
01025         cast<BinaryOperator>(I)->swapOperands();
01026       if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
01027         if (CB->getType() == Type::Int1Ty) {
01028           if (CB->isOne())   // X | 1 -> 1
01029             ReplaceUsesOfWith(I, I->getOperand(1), Worklist, L, LPM);
01030           else                  // X | 0 -> X
01031             ReplaceUsesOfWith(I, I->getOperand(0), Worklist, L, LPM);
01032           continue;
01033         }
01034       break;
01035     case Instruction::Br: {
01036       BranchInst *BI = cast<BranchInst>(I);
01037       if (BI->isUnconditional()) {
01038         // If BI's parent is the only pred of the successor, fold the two blocks
01039         // together.
01040         BasicBlock *Pred = BI->getParent();
01041         BasicBlock *Succ = BI->getSuccessor(0);
01042         BasicBlock *SinglePred = Succ->getSinglePredecessor();
01043         if (!SinglePred) continue;  // Nothing to do.
01044         assert(SinglePred == Pred && "CFG broken");
01045 
01046         DOUT << "Merging blocks: " << Pred->getName() << " <- " 
01047              << Succ->getName() << "\n";
01048         
01049         // Resolve any single entry PHI nodes in Succ.
01050         while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
01051           ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
01052         
01053         // Move all of the successor contents from Succ to Pred.
01054         Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
01055                                    Succ->end());
01056         LPM->deleteSimpleAnalysisValue(BI, L);
01057         BI->eraseFromParent();
01058         RemoveFromWorklist(BI, Worklist);
01059         
01060         // If Succ has any successors with PHI nodes, update them to have
01061         // entries coming from Pred instead of Succ.
01062         Succ->replaceAllUsesWith(Pred);
01063         
01064         // Remove Succ from the loop tree.
01065         LI->removeBlock(Succ);
01066         LPM->deleteSimpleAnalysisValue(Succ, L);
01067         Succ->eraseFromParent();
01068         ++NumSimplify;
01069       } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
01070         // Conditional branch.  Turn it into an unconditional branch, then
01071         // remove dead blocks.
01072         break;  // FIXME: Enable.
01073 
01074         DOUT << "Folded branch: " << *BI;
01075         BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
01076         BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
01077         DeadSucc->removePredecessor(BI->getParent(), true);
01078         Worklist.push_back(BranchInst::Create(LiveSucc, BI));
01079         LPM->deleteSimpleAnalysisValue(BI, L);
01080         BI->eraseFromParent();
01081         RemoveFromWorklist(BI, Worklist);
01082         ++NumSimplify;
01083 
01084         RemoveBlockIfDead(DeadSucc, Worklist, L);
01085       }
01086       break;
01087     }
01088     }
01089   }
01090 }



This web site is hosted by the Computer Science Department at the University of Illinois at Urbana-Champaign.