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