LLVM API Documentation

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 #include "llvm/Transforms/Scalar.h"
00030 #include "llvm/ADT/STLExtras.h"
00031 #include "llvm/ADT/SmallPtrSet.h"
00032 #include "llvm/ADT/Statistic.h"
00033 #include "llvm/Analysis/AssumptionCache.h"
00034 #include "llvm/Analysis/CodeMetrics.h"
00035 #include "llvm/Analysis/InstructionSimplify.h"
00036 #include "llvm/Analysis/LoopInfo.h"
00037 #include "llvm/Analysis/LoopPass.h"
00038 #include "llvm/Analysis/ScalarEvolution.h"
00039 #include "llvm/Analysis/TargetTransformInfo.h"
00040 #include "llvm/IR/Constants.h"
00041 #include "llvm/IR/DerivedTypes.h"
00042 #include "llvm/IR/Dominators.h"
00043 #include "llvm/IR/Function.h"
00044 #include "llvm/IR/Instructions.h"
00045 #include "llvm/Support/CommandLine.h"
00046 #include "llvm/Support/Debug.h"
00047 #include "llvm/Support/raw_ostream.h"
00048 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00049 #include "llvm/Transforms/Utils/Cloning.h"
00050 #include "llvm/Transforms/Utils/Local.h"
00051 #include <algorithm>
00052 #include <map>
00053 #include <set>
00054 using namespace llvm;
00055 
00056 #define DEBUG_TYPE "loop-unswitch"
00057 
00058 STATISTIC(NumBranches, "Number of branches unswitched");
00059 STATISTIC(NumSwitches, "Number of switches unswitched");
00060 STATISTIC(NumSelects , "Number of selects unswitched");
00061 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
00062 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
00063 STATISTIC(TotalInsts,  "Total number of instructions analyzed");
00064 
00065 // The specific value of 100 here was chosen based only on intuition and a
00066 // few specific examples.
00067 static cl::opt<unsigned>
00068 Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
00069           cl::init(100), cl::Hidden);
00070 
00071 namespace {
00072 
00073   class LUAnalysisCache {
00074 
00075     typedef DenseMap<const SwitchInst*, SmallPtrSet<const Value *, 8> >
00076       UnswitchedValsMap;
00077 
00078     typedef UnswitchedValsMap::iterator UnswitchedValsIt;
00079 
00080     struct LoopProperties {
00081       unsigned CanBeUnswitchedCount;
00082       unsigned SizeEstimation;
00083       UnswitchedValsMap UnswitchedVals;
00084     };
00085 
00086     // Here we use std::map instead of DenseMap, since we need to keep valid
00087     // LoopProperties pointer for current loop for better performance.
00088     typedef std::map<const Loop*, LoopProperties> LoopPropsMap;
00089     typedef LoopPropsMap::iterator LoopPropsMapIt;
00090 
00091     LoopPropsMap LoopsProperties;
00092     UnswitchedValsMap *CurLoopInstructions;
00093     LoopProperties *CurrentLoopProperties;
00094 
00095     // Max size of code we can produce on remained iterations.
00096     unsigned MaxSize;
00097 
00098     public:
00099 
00100       LUAnalysisCache() :
00101         CurLoopInstructions(nullptr), CurrentLoopProperties(nullptr),
00102         MaxSize(Threshold)
00103       {}
00104 
00105       // Analyze loop. Check its size, calculate is it possible to unswitch
00106       // it. Returns true if we can unswitch this loop.
00107       bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
00108                      AssumptionCache *AC);
00109 
00110       // Clean all data related to given loop.
00111       void forgetLoop(const Loop *L);
00112 
00113       // Mark case value as unswitched.
00114       // Since SI instruction can be partly unswitched, in order to avoid
00115       // extra unswitching in cloned loops keep track all unswitched values.
00116       void setUnswitched(const SwitchInst *SI, const Value *V);
00117 
00118       // Check was this case value unswitched before or not.
00119       bool isUnswitched(const SwitchInst *SI, const Value *V);
00120 
00121       // Clone all loop-unswitch related loop properties.
00122       // Redistribute unswitching quotas.
00123       // Note, that new loop data is stored inside the VMap.
00124       void cloneData(const Loop *NewLoop, const Loop *OldLoop,
00125                      const ValueToValueMapTy &VMap);
00126   };
00127 
00128   class LoopUnswitch : public LoopPass {
00129     LoopInfo *LI;  // Loop information
00130     LPPassManager *LPM;
00131     AssumptionCache *AC;
00132 
00133     // LoopProcessWorklist - Used to check if second loop needs processing
00134     // after RewriteLoopBodyWithConditionConstant rewrites first loop.
00135     std::vector<Loop*> LoopProcessWorklist;
00136 
00137     LUAnalysisCache BranchesInfo;
00138 
00139     bool OptimizeForSize;
00140     bool redoLoop;
00141 
00142     Loop *currentLoop;
00143     DominatorTree *DT;
00144     BasicBlock *loopHeader;
00145     BasicBlock *loopPreheader;
00146 
00147     // LoopBlocks contains all of the basic blocks of the loop, including the
00148     // preheader of the loop, the body of the loop, and the exit blocks of the
00149     // loop, in that order.
00150     std::vector<BasicBlock*> LoopBlocks;
00151     // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
00152     std::vector<BasicBlock*> NewBlocks;
00153 
00154   public:
00155     static char ID; // Pass ID, replacement for typeid
00156     explicit LoopUnswitch(bool Os = false) :
00157       LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
00158       currentLoop(nullptr), DT(nullptr), loopHeader(nullptr),
00159       loopPreheader(nullptr) {
00160         initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
00161       }
00162 
00163     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
00164     bool processCurrentLoop();
00165 
00166     /// This transformation requires natural loop information & requires that
00167     /// loop preheaders be inserted into the CFG.
00168     ///
00169     void getAnalysisUsage(AnalysisUsage &AU) const override {
00170       AU.addRequired<AssumptionCacheTracker>();
00171       AU.addRequiredID(LoopSimplifyID);
00172       AU.addPreservedID(LoopSimplifyID);
00173       AU.addRequired<LoopInfoWrapperPass>();
00174       AU.addPreserved<LoopInfoWrapperPass>();
00175       AU.addRequiredID(LCSSAID);
00176       AU.addPreservedID(LCSSAID);
00177       AU.addPreserved<DominatorTreeWrapperPass>();
00178       AU.addPreserved<ScalarEvolution>();
00179       AU.addRequired<TargetTransformInfo>();
00180     }
00181 
00182   private:
00183 
00184     void releaseMemory() override {
00185       BranchesInfo.forgetLoop(currentLoop);
00186     }
00187 
00188     void initLoopData() {
00189       loopHeader = currentLoop->getHeader();
00190       loopPreheader = currentLoop->getLoopPreheader();
00191     }
00192 
00193     /// Split all of the edges from inside the loop to their exit blocks.
00194     /// Update the appropriate Phi nodes as we do so.
00195     void SplitExitEdges(Loop *L, const SmallVectorImpl<BasicBlock *> &ExitBlocks);
00196 
00197     bool UnswitchIfProfitable(Value *LoopCond, Constant *Val);
00198     void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
00199                                   BasicBlock *ExitBlock);
00200     void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
00201 
00202     void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
00203                                               Constant *Val, bool isEqual);
00204 
00205     void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
00206                                         BasicBlock *TrueDest,
00207                                         BasicBlock *FalseDest,
00208                                         Instruction *InsertPt);
00209 
00210     void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
00211     bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = nullptr,
00212                                     BasicBlock **LoopExit = nullptr);
00213 
00214   };
00215 }
00216 
00217 // Analyze loop. Check its size, calculate is it possible to unswitch
00218 // it. Returns true if we can unswitch this loop.
00219 bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
00220                                 AssumptionCache *AC) {
00221 
00222   LoopPropsMapIt PropsIt;
00223   bool Inserted;
00224   std::tie(PropsIt, Inserted) =
00225       LoopsProperties.insert(std::make_pair(L, LoopProperties()));
00226 
00227   LoopProperties &Props = PropsIt->second;
00228 
00229   if (Inserted) {
00230     // New loop.
00231 
00232     // Limit the number of instructions to avoid causing significant code
00233     // expansion, and the number of basic blocks, to avoid loops with
00234     // large numbers of branches which cause loop unswitching to go crazy.
00235     // This is a very ad-hoc heuristic.
00236 
00237     SmallPtrSet<const Value *, 32> EphValues;
00238     CodeMetrics::collectEphemeralValues(L, AC, EphValues);
00239 
00240     // FIXME: This is overly conservative because it does not take into
00241     // consideration code simplification opportunities and code that can
00242     // be shared by the resultant unswitched loops.
00243     CodeMetrics Metrics;
00244     for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
00245          I != E; ++I)
00246       Metrics.analyzeBasicBlock(*I, TTI, EphValues);
00247 
00248     Props.SizeEstimation = std::min(Metrics.NumInsts, Metrics.NumBlocks * 5);
00249     Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
00250     MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
00251 
00252     if (Metrics.notDuplicatable) {
00253       DEBUG(dbgs() << "NOT unswitching loop %"
00254                    << L->getHeader()->getName() << ", contents cannot be "
00255                    << "duplicated!\n");
00256       return false;
00257     }
00258   }
00259 
00260   if (!Props.CanBeUnswitchedCount) {
00261     DEBUG(dbgs() << "NOT unswitching loop %"
00262                  << L->getHeader()->getName() << ", cost too high: "
00263                  << L->getBlocks().size() << "\n");
00264     return false;
00265   }
00266 
00267   // Be careful. This links are good only before new loop addition.
00268   CurrentLoopProperties = &Props;
00269   CurLoopInstructions = &Props.UnswitchedVals;
00270 
00271   return true;
00272 }
00273 
00274 // Clean all data related to given loop.
00275 void LUAnalysisCache::forgetLoop(const Loop *L) {
00276 
00277   LoopPropsMapIt LIt = LoopsProperties.find(L);
00278 
00279   if (LIt != LoopsProperties.end()) {
00280     LoopProperties &Props = LIt->second;
00281     MaxSize += Props.CanBeUnswitchedCount * Props.SizeEstimation;
00282     LoopsProperties.erase(LIt);
00283   }
00284 
00285   CurrentLoopProperties = nullptr;
00286   CurLoopInstructions = nullptr;
00287 }
00288 
00289 // Mark case value as unswitched.
00290 // Since SI instruction can be partly unswitched, in order to avoid
00291 // extra unswitching in cloned loops keep track all unswitched values.
00292 void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
00293   (*CurLoopInstructions)[SI].insert(V);
00294 }
00295 
00296 // Check was this case value unswitched before or not.
00297 bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
00298   return (*CurLoopInstructions)[SI].count(V);
00299 }
00300 
00301 // Clone all loop-unswitch related loop properties.
00302 // Redistribute unswitching quotas.
00303 // Note, that new loop data is stored inside the VMap.
00304 void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
00305                                 const ValueToValueMapTy &VMap) {
00306 
00307   LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
00308   LoopProperties &OldLoopProps = *CurrentLoopProperties;
00309   UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
00310 
00311   // Reallocate "can-be-unswitched quota"
00312 
00313   --OldLoopProps.CanBeUnswitchedCount;
00314   unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
00315   NewLoopProps.CanBeUnswitchedCount = Quota / 2;
00316   OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
00317 
00318   NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
00319 
00320   // Clone unswitched values info:
00321   // for new loop switches we clone info about values that was
00322   // already unswitched and has redundant successors.
00323   for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
00324     const SwitchInst *OldInst = I->first;
00325     Value *NewI = VMap.lookup(OldInst);
00326     const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
00327     assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
00328 
00329     NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
00330   }
00331 }
00332 
00333 char LoopUnswitch::ID = 0;
00334 INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
00335                       false, false)
00336 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
00337 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
00338 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
00339 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
00340 INITIALIZE_PASS_DEPENDENCY(LCSSA)
00341 INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
00342                       false, false)
00343 
00344 Pass *llvm::createLoopUnswitchPass(bool Os) {
00345   return new LoopUnswitch(Os);
00346 }
00347 
00348 /// FindLIVLoopCondition - Cond is a condition that occurs in L.  If it is
00349 /// invariant in the loop, or has an invariant piece, return the invariant.
00350 /// Otherwise, return null.
00351 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
00352 
00353   // We started analyze new instruction, increment scanned instructions counter.
00354   ++TotalInsts;
00355 
00356   // We can never unswitch on vector conditions.
00357   if (Cond->getType()->isVectorTy())
00358     return nullptr;
00359 
00360   // Constants should be folded, not unswitched on!
00361   if (isa<Constant>(Cond)) return nullptr;
00362 
00363   // TODO: Handle: br (VARIANT|INVARIANT).
00364 
00365   // Hoist simple values out.
00366   if (L->makeLoopInvariant(Cond, Changed))
00367     return Cond;
00368 
00369   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
00370     if (BO->getOpcode() == Instruction::And ||
00371         BO->getOpcode() == Instruction::Or) {
00372       // If either the left or right side is invariant, we can unswitch on this,
00373       // which will cause the branch to go away in one loop and the condition to
00374       // simplify in the other one.
00375       if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
00376         return LHS;
00377       if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
00378         return RHS;
00379     }
00380 
00381   return nullptr;
00382 }
00383 
00384 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
00385   if (skipOptnoneFunction(L))
00386     return false;
00387 
00388   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
00389       *L->getHeader()->getParent());
00390   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
00391   LPM = &LPM_Ref;
00392   DominatorTreeWrapperPass *DTWP =
00393       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
00394   DT = DTWP ? &DTWP->getDomTree() : nullptr;
00395   currentLoop = L;
00396   Function *F = currentLoop->getHeader()->getParent();
00397   bool Changed = false;
00398   do {
00399     assert(currentLoop->isLCSSAForm(*DT));
00400     redoLoop = false;
00401     Changed |= processCurrentLoop();
00402   } while(redoLoop);
00403 
00404   if (Changed) {
00405     // FIXME: Reconstruct dom info, because it is not preserved properly.
00406     if (DT)
00407       DT->recalculate(*F);
00408   }
00409   return Changed;
00410 }
00411 
00412 /// processCurrentLoop - Do actual work and unswitch loop if possible
00413 /// and profitable.
00414 bool LoopUnswitch::processCurrentLoop() {
00415   bool Changed = false;
00416 
00417   initLoopData();
00418 
00419   // If LoopSimplify was unable to form a preheader, don't do any unswitching.
00420   if (!loopPreheader)
00421     return false;
00422 
00423   // Loops with indirectbr cannot be cloned.
00424   if (!currentLoop->isSafeToClone())
00425     return false;
00426 
00427   // Without dedicated exits, splitting the exit edge may fail.
00428   if (!currentLoop->hasDedicatedExits())
00429     return false;
00430 
00431   LLVMContext &Context = loopHeader->getContext();
00432 
00433   // Probably we reach the quota of branches for this loop. If so
00434   // stop unswitching.
00435   if (!BranchesInfo.countLoop(currentLoop, getAnalysis<TargetTransformInfo>(),
00436                               AC))
00437     return false;
00438 
00439   // Loop over all of the basic blocks in the loop.  If we find an interior
00440   // block that is branching on a loop-invariant condition, we can unswitch this
00441   // loop.
00442   for (Loop::block_iterator I = currentLoop->block_begin(),
00443          E = currentLoop->block_end(); I != E; ++I) {
00444     TerminatorInst *TI = (*I)->getTerminator();
00445     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
00446       // If this isn't branching on an invariant condition, we can't unswitch
00447       // it.
00448       if (BI->isConditional()) {
00449         // See if this, or some part of it, is loop invariant.  If so, we can
00450         // unswitch on it if we desire.
00451         Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
00452                                                currentLoop, Changed);
00453         if (LoopCond && UnswitchIfProfitable(LoopCond,
00454                                              ConstantInt::getTrue(Context))) {
00455           ++NumBranches;
00456           return true;
00457         }
00458       }
00459     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
00460       Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
00461                                              currentLoop, Changed);
00462       unsigned NumCases = SI->getNumCases();
00463       if (LoopCond && NumCases) {
00464         // Find a value to unswitch on:
00465         // FIXME: this should chose the most expensive case!
00466         // FIXME: scan for a case with a non-critical edge?
00467         Constant *UnswitchVal = nullptr;
00468 
00469         // Do not process same value again and again.
00470         // At this point we have some cases already unswitched and
00471         // some not yet unswitched. Let's find the first not yet unswitched one.
00472         for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
00473              i != e; ++i) {
00474           Constant *UnswitchValCandidate = i.getCaseValue();
00475           if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
00476             UnswitchVal = UnswitchValCandidate;
00477             break;
00478           }
00479         }
00480 
00481         if (!UnswitchVal)
00482           continue;
00483 
00484         if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
00485           ++NumSwitches;
00486           return true;
00487         }
00488       }
00489     }
00490 
00491     // Scan the instructions to check for unswitchable values.
00492     for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
00493          BBI != E; ++BBI)
00494       if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
00495         Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
00496                                                currentLoop, Changed);
00497         if (LoopCond && UnswitchIfProfitable(LoopCond,
00498                                              ConstantInt::getTrue(Context))) {
00499           ++NumSelects;
00500           return true;
00501         }
00502       }
00503   }
00504   return Changed;
00505 }
00506 
00507 /// isTrivialLoopExitBlock - Check to see if all paths from BB exit the
00508 /// loop with no side effects (including infinite loops).
00509 ///
00510 /// If true, we return true and set ExitBB to the block we
00511 /// exit through.
00512 ///
00513 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
00514                                          BasicBlock *&ExitBB,
00515                                          std::set<BasicBlock*> &Visited) {
00516   if (!Visited.insert(BB).second) {
00517     // Already visited. Without more analysis, this could indicate an infinite
00518     // loop.
00519     return false;
00520   }
00521   if (!L->contains(BB)) {
00522     // Otherwise, this is a loop exit, this is fine so long as this is the
00523     // first exit.
00524     if (ExitBB) return false;
00525     ExitBB = BB;
00526     return true;
00527   }
00528 
00529   // Otherwise, this is an unvisited intra-loop node.  Check all successors.
00530   for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
00531     // Check to see if the successor is a trivial loop exit.
00532     if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
00533       return false;
00534   }
00535 
00536   // Okay, everything after this looks good, check to make sure that this block
00537   // doesn't include any side effects.
00538   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00539     if (I->mayHaveSideEffects())
00540       return false;
00541 
00542   return true;
00543 }
00544 
00545 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
00546 /// leads to an exit from the specified loop, and has no side-effects in the
00547 /// process.  If so, return the block that is exited to, otherwise return null.
00548 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
00549   std::set<BasicBlock*> Visited;
00550   Visited.insert(L->getHeader());  // Branches to header make infinite loops.
00551   BasicBlock *ExitBB = nullptr;
00552   if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
00553     return ExitBB;
00554   return nullptr;
00555 }
00556 
00557 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
00558 /// trivial: that is, that the condition controls whether or not the loop does
00559 /// anything at all.  If this is a trivial condition, unswitching produces no
00560 /// code duplications (equivalently, it produces a simpler loop and a new empty
00561 /// loop, which gets deleted).
00562 ///
00563 /// If this is a trivial condition, return true, otherwise return false.  When
00564 /// returning true, this sets Cond and Val to the condition that controls the
00565 /// trivial condition: when Cond dynamically equals Val, the loop is known to
00566 /// exit.  Finally, this sets LoopExit to the BB that the loop exits to when
00567 /// Cond == Val.
00568 ///
00569 bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
00570                                        BasicBlock **LoopExit) {
00571   BasicBlock *Header = currentLoop->getHeader();
00572   TerminatorInst *HeaderTerm = Header->getTerminator();
00573   LLVMContext &Context = Header->getContext();
00574 
00575   BasicBlock *LoopExitBB = nullptr;
00576   if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
00577     // If the header block doesn't end with a conditional branch on Cond, we
00578     // can't handle it.
00579     if (!BI->isConditional() || BI->getCondition() != Cond)
00580       return false;
00581 
00582     // Check to see if a successor of the branch is guaranteed to
00583     // exit through a unique exit block without having any
00584     // side-effects.  If so, determine the value of Cond that causes it to do
00585     // this.
00586     if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
00587                                              BI->getSuccessor(0)))) {
00588       if (Val) *Val = ConstantInt::getTrue(Context);
00589     } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
00590                                                     BI->getSuccessor(1)))) {
00591       if (Val) *Val = ConstantInt::getFalse(Context);
00592     }
00593   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
00594     // If this isn't a switch on Cond, we can't handle it.
00595     if (SI->getCondition() != Cond) return false;
00596 
00597     // Check to see if a successor of the switch is guaranteed to go to the
00598     // latch block or exit through a one exit block without having any
00599     // side-effects.  If so, determine the value of Cond that causes it to do
00600     // this.
00601     // Note that we can't trivially unswitch on the default case or
00602     // on already unswitched cases.
00603     for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
00604          i != e; ++i) {
00605       BasicBlock *LoopExitCandidate;
00606       if ((LoopExitCandidate = isTrivialLoopExitBlock(currentLoop,
00607                                                i.getCaseSuccessor()))) {
00608         // Okay, we found a trivial case, remember the value that is trivial.
00609         ConstantInt *CaseVal = i.getCaseValue();
00610 
00611         // Check that it was not unswitched before, since already unswitched
00612         // trivial vals are looks trivial too.
00613         if (BranchesInfo.isUnswitched(SI, CaseVal))
00614           continue;
00615         LoopExitBB = LoopExitCandidate;
00616         if (Val) *Val = CaseVal;
00617         break;
00618       }
00619     }
00620   }
00621 
00622   // If we didn't find a single unique LoopExit block, or if the loop exit block
00623   // contains phi nodes, this isn't trivial.
00624   if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
00625     return false;   // Can't handle this.
00626 
00627   if (LoopExit) *LoopExit = LoopExitBB;
00628 
00629   // We already know that nothing uses any scalar values defined inside of this
00630   // loop.  As such, we just have to check to see if this loop will execute any
00631   // side-effecting instructions (e.g. stores, calls, volatile loads) in the
00632   // part of the loop that the code *would* execute.  We already checked the
00633   // tail, check the header now.
00634   for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
00635     if (I->mayHaveSideEffects())
00636       return false;
00637   return true;
00638 }
00639 
00640 /// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
00641 /// LoopCond == Val to simplify the loop.  If we decide that this is profitable,
00642 /// unswitch the loop, reprocess the pieces, then return true.
00643 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val) {
00644   Function *F = loopHeader->getParent();
00645   Constant *CondVal = nullptr;
00646   BasicBlock *ExitBlock = nullptr;
00647 
00648   if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
00649     // If the condition is trivial, always unswitch. There is no code growth
00650     // for this case.
00651     UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock);
00652     return true;
00653   }
00654 
00655   // Check to see if it would be profitable to unswitch current loop.
00656 
00657   // Do not do non-trivial unswitch while optimizing for size.
00658   if (OptimizeForSize ||
00659       F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
00660                                       Attribute::OptimizeForSize))
00661     return false;
00662 
00663   UnswitchNontrivialCondition(LoopCond, Val, currentLoop);
00664   return true;
00665 }
00666 
00667 /// CloneLoop - Recursively clone the specified loop and all of its children,
00668 /// mapping the blocks with the specified map.
00669 static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
00670                        LoopInfo *LI, LPPassManager *LPM) {
00671   Loop *New = new Loop();
00672   LPM->insertLoop(New, PL);
00673 
00674   // Add all of the blocks in L to the new loop.
00675   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
00676        I != E; ++I)
00677     if (LI->getLoopFor(*I) == L)
00678       New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
00679 
00680   // Add all of the subloops to the new loop.
00681   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
00682     CloneLoop(*I, New, VM, LI, LPM);
00683 
00684   return New;
00685 }
00686 
00687 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
00688 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest.  Insert the
00689 /// code immediately before InsertPt.
00690 void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
00691                                                   BasicBlock *TrueDest,
00692                                                   BasicBlock *FalseDest,
00693                                                   Instruction *InsertPt) {
00694   // Insert a conditional branch on LIC to the two preheaders.  The original
00695   // code is the true version and the new code is the false version.
00696   Value *BranchVal = LIC;
00697   if (!isa<ConstantInt>(Val) ||
00698       Val->getType() != Type::getInt1Ty(LIC->getContext()))
00699     BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val);
00700   else if (Val != ConstantInt::getTrue(Val->getContext()))
00701     // We want to enter the new loop when the condition is true.
00702     std::swap(TrueDest, FalseDest);
00703 
00704   // Insert the new branch.
00705   BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
00706 
00707   // If either edge is critical, split it. This helps preserve LoopSimplify
00708   // form for enclosing loops.
00709   auto Options = CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA();
00710   SplitCriticalEdge(BI, 0, Options);
00711   SplitCriticalEdge(BI, 1, Options);
00712 }
00713 
00714 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
00715 /// condition in it (a cond branch from its header block to its latch block,
00716 /// where the path through the loop that doesn't execute its body has no
00717 /// side-effects), unswitch it.  This doesn't involve any code duplication, just
00718 /// moving the conditional branch outside of the loop and updating loop info.
00719 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond,
00720                                             Constant *Val,
00721                                             BasicBlock *ExitBlock) {
00722   DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
00723         << loopHeader->getName() << " [" << L->getBlocks().size()
00724         << " blocks] in Function " << L->getHeader()->getParent()->getName()
00725         << " on cond: " << *Val << " == " << *Cond << "\n");
00726 
00727   // First step, split the preheader, so that we know that there is a safe place
00728   // to insert the conditional branch.  We will change loopPreheader to have a
00729   // conditional branch on Cond.
00730   BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, DT, LI);
00731 
00732   // Now that we have a place to insert the conditional branch, create a place
00733   // to branch to: this is the exit block out of the loop that we should
00734   // short-circuit to.
00735 
00736   // Split this block now, so that the loop maintains its exit block, and so
00737   // that the jump from the preheader can execute the contents of the exit block
00738   // without actually branching to it (the exit block should be dominated by the
00739   // loop header, not the preheader).
00740   assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
00741   BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), DT, LI);
00742 
00743   // Okay, now we have a position to branch from and a position to branch to,
00744   // insert the new conditional branch.
00745   EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
00746                                  loopPreheader->getTerminator());
00747   LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
00748   loopPreheader->getTerminator()->eraseFromParent();
00749 
00750   // We need to reprocess this loop, it could be unswitched again.
00751   redoLoop = true;
00752 
00753   // Now that we know that the loop is never entered when this condition is a
00754   // particular value, rewrite the loop with this info.  We know that this will
00755   // at least eliminate the old branch.
00756   RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
00757   ++NumTrivial;
00758 }
00759 
00760 /// SplitExitEdges - Split all of the edges from inside the loop to their exit
00761 /// blocks.  Update the appropriate Phi nodes as we do so.
00762 void LoopUnswitch::SplitExitEdges(Loop *L,
00763                                const SmallVectorImpl<BasicBlock *> &ExitBlocks){
00764 
00765   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
00766     BasicBlock *ExitBlock = ExitBlocks[i];
00767     SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
00768                                        pred_end(ExitBlock));
00769 
00770     // Although SplitBlockPredecessors doesn't preserve loop-simplify in
00771     // general, if we call it on all predecessors of all exits then it does.
00772     if (!ExitBlock->isLandingPad()) {
00773       SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa",
00774                              /*AliasAnalysis*/ nullptr, DT, LI,
00775                              /*PreserveLCSSA*/ true);
00776     } else {
00777       SmallVector<BasicBlock*, 2> NewBBs;
00778       SplitLandingPadPredecessors(ExitBlock, Preds, ".us-lcssa", ".us-lcssa",
00779                                   NewBBs, /*AliasAnalysis*/ nullptr, DT, LI,
00780                                   /*PreserveLCSSA*/ true);
00781     }
00782   }
00783 }
00784 
00785 /// UnswitchNontrivialCondition - We determined that the loop is profitable
00786 /// to unswitch when LIC equal Val.  Split it into loop versions and test the
00787 /// condition outside of either loop.  Return the loops created as Out1/Out2.
00788 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
00789                                                Loop *L) {
00790   Function *F = loopHeader->getParent();
00791   DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
00792         << loopHeader->getName() << " [" << L->getBlocks().size()
00793         << " blocks] in Function " << F->getName()
00794         << " when '" << *Val << "' == " << *LIC << "\n");
00795 
00796   if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
00797     SE->forgetLoop(L);
00798 
00799   LoopBlocks.clear();
00800   NewBlocks.clear();
00801 
00802   // First step, split the preheader and exit blocks, and add these blocks to
00803   // the LoopBlocks list.
00804   BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, DT, LI);
00805   LoopBlocks.push_back(NewPreheader);
00806 
00807   // We want the loop to come after the preheader, but before the exit blocks.
00808   LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
00809 
00810   SmallVector<BasicBlock*, 8> ExitBlocks;
00811   L->getUniqueExitBlocks(ExitBlocks);
00812 
00813   // Split all of the edges from inside the loop to their exit blocks.  Update
00814   // the appropriate Phi nodes as we do so.
00815   SplitExitEdges(L, ExitBlocks);
00816 
00817   // The exit blocks may have been changed due to edge splitting, recompute.
00818   ExitBlocks.clear();
00819   L->getUniqueExitBlocks(ExitBlocks);
00820 
00821   // Add exit blocks to the loop blocks.
00822   LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
00823 
00824   // Next step, clone all of the basic blocks that make up the loop (including
00825   // the loop preheader and exit blocks), keeping track of the mapping between
00826   // the instructions and blocks.
00827   NewBlocks.reserve(LoopBlocks.size());
00828   ValueToValueMapTy VMap;
00829   for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
00830     BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
00831 
00832     NewBlocks.push_back(NewBB);
00833     VMap[LoopBlocks[i]] = NewBB;  // Keep the BB mapping.
00834     LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
00835   }
00836 
00837   // Splice the newly inserted blocks into the function right before the
00838   // original preheader.
00839   F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
00840                                 NewBlocks[0], F->end());
00841 
00842   // FIXME: We could register any cloned assumptions instead of clearing the
00843   // whole function's cache.
00844   AC->clear();
00845 
00846   // Now we create the new Loop object for the versioned loop.
00847   Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
00848 
00849   // Recalculate unswitching quota, inherit simplified switches info for NewBB,
00850   // Probably clone more loop-unswitch related loop properties.
00851   BranchesInfo.cloneData(NewLoop, L, VMap);
00852 
00853   Loop *ParentLoop = L->getParentLoop();
00854   if (ParentLoop) {
00855     // Make sure to add the cloned preheader and exit blocks to the parent loop
00856     // as well.
00857     ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
00858   }
00859 
00860   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
00861     BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
00862     // The new exit block should be in the same loop as the old one.
00863     if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
00864       ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
00865 
00866     assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
00867            "Exit block should have been split to have one successor!");
00868     BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
00869 
00870     // If the successor of the exit block had PHI nodes, add an entry for
00871     // NewExit.
00872     for (BasicBlock::iterator I = ExitSucc->begin();
00873          PHINode *PN = dyn_cast<PHINode>(I); ++I) {
00874       Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
00875       ValueToValueMapTy::iterator It = VMap.find(V);
00876       if (It != VMap.end()) V = It->second;
00877       PN->addIncoming(V, NewExit);
00878     }
00879 
00880     if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
00881       PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
00882                                     ExitSucc->getFirstInsertionPt());
00883 
00884       for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
00885            I != E; ++I) {
00886         BasicBlock *BB = *I;
00887         LandingPadInst *LPI = BB->getLandingPadInst();
00888         LPI->replaceAllUsesWith(PN);
00889         PN->addIncoming(LPI, BB);
00890       }
00891     }
00892   }
00893 
00894   // Rewrite the code to refer to itself.
00895   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
00896     for (BasicBlock::iterator I = NewBlocks[i]->begin(),
00897            E = NewBlocks[i]->end(); I != E; ++I)
00898       RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
00899 
00900   // Rewrite the original preheader to select between versions of the loop.
00901   BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
00902   assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
00903          "Preheader splitting did not work correctly!");
00904 
00905   // Emit the new branch that selects between the two versions of this loop.
00906   EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
00907   LPM->deleteSimpleAnalysisValue(OldBR, L);
00908   OldBR->eraseFromParent();
00909 
00910   LoopProcessWorklist.push_back(NewLoop);
00911   redoLoop = true;
00912 
00913   // Keep a WeakVH holding onto LIC.  If the first call to RewriteLoopBody
00914   // deletes the instruction (for example by simplifying a PHI that feeds into
00915   // the condition that we're unswitching on), we don't rewrite the second
00916   // iteration.
00917   WeakVH LICHandle(LIC);
00918 
00919   // Now we rewrite the original code to know that the condition is true and the
00920   // new code to know that the condition is false.
00921   RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
00922 
00923   // It's possible that simplifying one loop could cause the other to be
00924   // changed to another value or a constant.  If its a constant, don't simplify
00925   // it.
00926   if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
00927       LICHandle && !isa<Constant>(LICHandle))
00928     RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
00929 }
00930 
00931 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
00932 /// specified.
00933 static void RemoveFromWorklist(Instruction *I,
00934                                std::vector<Instruction*> &Worklist) {
00935 
00936   Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
00937                  Worklist.end());
00938 }
00939 
00940 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
00941 /// program, replacing all uses with V and update the worklist.
00942 static void ReplaceUsesOfWith(Instruction *I, Value *V,
00943                               std::vector<Instruction*> &Worklist,
00944                               Loop *L, LPPassManager *LPM) {
00945   DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
00946 
00947   // Add uses to the worklist, which may be dead now.
00948   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
00949     if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
00950       Worklist.push_back(Use);
00951 
00952   // Add users to the worklist which may be simplified now.
00953   for (User *U : I->users())
00954     Worklist.push_back(cast<Instruction>(U));
00955   LPM->deleteSimpleAnalysisValue(I, L);
00956   RemoveFromWorklist(I, Worklist);
00957   I->replaceAllUsesWith(V);
00958   I->eraseFromParent();
00959   ++NumSimplify;
00960 }
00961 
00962 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
00963 // the value specified by Val in the specified loop, or we know it does NOT have
00964 // that value.  Rewrite any uses of LIC or of properties correlated to it.
00965 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
00966                                                         Constant *Val,
00967                                                         bool IsEqual) {
00968   assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
00969 
00970   // FIXME: Support correlated properties, like:
00971   //  for (...)
00972   //    if (li1 < li2)
00973   //      ...
00974   //    if (li1 > li2)
00975   //      ...
00976 
00977   // FOLD boolean conditions (X|LIC), (X&LIC).  Fold conditional branches,
00978   // selects, switches.
00979   std::vector<Instruction*> Worklist;
00980   LLVMContext &Context = Val->getContext();
00981 
00982   // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
00983   // in the loop with the appropriate one directly.
00984   if (IsEqual || (isa<ConstantInt>(Val) &&
00985       Val->getType()->isIntegerTy(1))) {
00986     Value *Replacement;
00987     if (IsEqual)
00988       Replacement = Val;
00989     else
00990       Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
00991                                      !cast<ConstantInt>(Val)->getZExtValue());
00992 
00993     for (User *U : LIC->users()) {
00994       Instruction *UI = dyn_cast<Instruction>(U);
00995       if (!UI || !L->contains(UI))
00996         continue;
00997       Worklist.push_back(UI);
00998     }
00999 
01000     for (std::vector<Instruction*>::iterator UI = Worklist.begin(),
01001          UE = Worklist.end(); UI != UE; ++UI)
01002       (*UI)->replaceUsesOfWith(LIC, Replacement);
01003 
01004     SimplifyCode(Worklist, L);
01005     return;
01006   }
01007 
01008   // Otherwise, we don't know the precise value of LIC, but we do know that it
01009   // is certainly NOT "Val".  As such, simplify any uses in the loop that we
01010   // can.  This case occurs when we unswitch switch statements.
01011   for (User *U : LIC->users()) {
01012     Instruction *UI = dyn_cast<Instruction>(U);
01013     if (!UI || !L->contains(UI))
01014       continue;
01015 
01016     Worklist.push_back(UI);
01017 
01018     // TODO: We could do other simplifications, for example, turning
01019     // 'icmp eq LIC, Val' -> false.
01020 
01021     // If we know that LIC is not Val, use this info to simplify code.
01022     SwitchInst *SI = dyn_cast<SwitchInst>(UI);
01023     if (!SI || !isa<ConstantInt>(Val)) continue;
01024 
01025     SwitchInst::CaseIt DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
01026     // Default case is live for multiple values.
01027     if (DeadCase == SI->case_default()) continue;
01028 
01029     // Found a dead case value.  Don't remove PHI nodes in the
01030     // successor if they become single-entry, those PHI nodes may
01031     // be in the Users list.
01032 
01033     BasicBlock *Switch = SI->getParent();
01034     BasicBlock *SISucc = DeadCase.getCaseSuccessor();
01035     BasicBlock *Latch = L->getLoopLatch();
01036 
01037     BranchesInfo.setUnswitched(SI, Val);
01038 
01039     if (!SI->findCaseDest(SISucc)) continue;  // Edge is critical.
01040     // If the DeadCase successor dominates the loop latch, then the
01041     // transformation isn't safe since it will delete the sole predecessor edge
01042     // to the latch.
01043     if (Latch && DT->dominates(SISucc, Latch))
01044       continue;
01045 
01046     // FIXME: This is a hack.  We need to keep the successor around
01047     // and hooked up so as to preserve the loop structure, because
01048     // trying to update it is complicated.  So instead we preserve the
01049     // loop structure and put the block on a dead code path.
01050     SplitEdge(Switch, SISucc, DT, LI);
01051     // Compute the successors instead of relying on the return value
01052     // of SplitEdge, since it may have split the switch successor
01053     // after PHI nodes.
01054     BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
01055     BasicBlock *OldSISucc = *succ_begin(NewSISucc);
01056     // Create an "unreachable" destination.
01057     BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
01058                                            Switch->getParent(),
01059                                            OldSISucc);
01060     new UnreachableInst(Context, Abort);
01061     // Force the new case destination to branch to the "unreachable"
01062     // block while maintaining a (dead) CFG edge to the old block.
01063     NewSISucc->getTerminator()->eraseFromParent();
01064     BranchInst::Create(Abort, OldSISucc,
01065                        ConstantInt::getTrue(Context), NewSISucc);
01066     // Release the PHI operands for this edge.
01067     for (BasicBlock::iterator II = NewSISucc->begin();
01068          PHINode *PN = dyn_cast<PHINode>(II); ++II)
01069       PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
01070                            UndefValue::get(PN->getType()));
01071     // Tell the domtree about the new block. We don't fully update the
01072     // domtree here -- instead we force it to do a full recomputation
01073     // after the pass is complete -- but we do need to inform it of
01074     // new blocks.
01075     if (DT)
01076       DT->addNewBlock(Abort, NewSISucc);
01077   }
01078 
01079   SimplifyCode(Worklist, L);
01080 }
01081 
01082 /// SimplifyCode - Okay, now that we have simplified some instructions in the
01083 /// loop, walk over it and constant prop, dce, and fold control flow where
01084 /// possible.  Note that this is effectively a very simple loop-structure-aware
01085 /// optimizer.  During processing of this loop, L could very well be deleted, so
01086 /// it must not be used.
01087 ///
01088 /// FIXME: When the loop optimizer is more mature, separate this out to a new
01089 /// pass.
01090 ///
01091 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
01092   while (!Worklist.empty()) {
01093     Instruction *I = Worklist.back();
01094     Worklist.pop_back();
01095 
01096     // Simple DCE.
01097     if (isInstructionTriviallyDead(I)) {
01098       DEBUG(dbgs() << "Remove dead instruction '" << *I);
01099 
01100       // Add uses to the worklist, which may be dead now.
01101       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
01102         if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
01103           Worklist.push_back(Use);
01104       LPM->deleteSimpleAnalysisValue(I, L);
01105       RemoveFromWorklist(I, Worklist);
01106       I->eraseFromParent();
01107       ++NumSimplify;
01108       continue;
01109     }
01110 
01111     // See if instruction simplification can hack this up.  This is common for
01112     // things like "select false, X, Y" after unswitching made the condition be
01113     // 'false'.  TODO: update the domtree properly so we can pass it here.
01114     if (Value *V = SimplifyInstruction(I))
01115       if (LI->replacementPreservesLCSSAForm(I, V)) {
01116         ReplaceUsesOfWith(I, V, Worklist, L, LPM);
01117         continue;
01118       }
01119 
01120     // Special case hacks that appear commonly in unswitched code.
01121     if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
01122       if (BI->isUnconditional()) {
01123         // If BI's parent is the only pred of the successor, fold the two blocks
01124         // together.
01125         BasicBlock *Pred = BI->getParent();
01126         BasicBlock *Succ = BI->getSuccessor(0);
01127         BasicBlock *SinglePred = Succ->getSinglePredecessor();
01128         if (!SinglePred) continue;  // Nothing to do.
01129         assert(SinglePred == Pred && "CFG broken");
01130 
01131         DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
01132               << Succ->getName() << "\n");
01133 
01134         // Resolve any single entry PHI nodes in Succ.
01135         while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
01136           ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
01137 
01138         // If Succ has any successors with PHI nodes, update them to have
01139         // entries coming from Pred instead of Succ.
01140         Succ->replaceAllUsesWith(Pred);
01141 
01142         // Move all of the successor contents from Succ to Pred.
01143         Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
01144                                    Succ->end());
01145         LPM->deleteSimpleAnalysisValue(BI, L);
01146         BI->eraseFromParent();
01147         RemoveFromWorklist(BI, Worklist);
01148 
01149         // Remove Succ from the loop tree.
01150         LI->removeBlock(Succ);
01151         LPM->deleteSimpleAnalysisValue(Succ, L);
01152         Succ->eraseFromParent();
01153         ++NumSimplify;
01154         continue;
01155       }
01156 
01157       continue;
01158     }
01159   }
01160 }