LLVM API Documentation

IndVarSimplify.cpp
Go to the documentation of this file.
00001 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
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 transformation analyzes and transforms the induction variables (and
00011 // computations derived from them) into simpler forms suitable for subsequent
00012 // analysis and transformation.
00013 //
00014 // If the trip count of a loop is computable, this pass also makes the following
00015 // changes:
00016 //   1. The exit condition for the loop is canonicalized to compare the
00017 //      induction value against the exit value.  This turns loops like:
00018 //        'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
00019 //   2. Any use outside of the loop of an expression derived from the indvar
00020 //      is changed to compute the derived value outside of the loop, eliminating
00021 //      the dependence on the exit value of the induction variable.  If the only
00022 //      purpose of the loop is to compute the exit value of some derived
00023 //      expression, this transformation will make the loop dead.
00024 //
00025 //===----------------------------------------------------------------------===//
00026 
00027 #define DEBUG_TYPE "indvars"
00028 #include "llvm/Transforms/Scalar.h"
00029 #include "llvm/ADT/DenseMap.h"
00030 #include "llvm/ADT/SmallVector.h"
00031 #include "llvm/ADT/Statistic.h"
00032 #include "llvm/Analysis/LoopInfo.h"
00033 #include "llvm/Analysis/LoopPass.h"
00034 #include "llvm/Analysis/ScalarEvolutionExpander.h"
00035 #include "llvm/IR/BasicBlock.h"
00036 #include "llvm/IR/CFG.h"
00037 #include "llvm/IR/Constants.h"
00038 #include "llvm/IR/DataLayout.h"
00039 #include "llvm/IR/Dominators.h"
00040 #include "llvm/IR/Instructions.h"
00041 #include "llvm/IR/IntrinsicInst.h"
00042 #include "llvm/IR/LLVMContext.h"
00043 #include "llvm/IR/Type.h"
00044 #include "llvm/Support/CommandLine.h"
00045 #include "llvm/Support/Debug.h"
00046 #include "llvm/Support/raw_ostream.h"
00047 #include "llvm/Target/TargetLibraryInfo.h"
00048 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00049 #include "llvm/Transforms/Utils/Local.h"
00050 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
00051 using namespace llvm;
00052 
00053 STATISTIC(NumWidened     , "Number of indvars widened");
00054 STATISTIC(NumReplaced    , "Number of exit values replaced");
00055 STATISTIC(NumLFTR        , "Number of loop exit tests replaced");
00056 STATISTIC(NumElimExt     , "Number of IV sign/zero extends eliminated");
00057 STATISTIC(NumElimIV      , "Number of congruent IVs eliminated");
00058 
00059 // Trip count verification can be enabled by default under NDEBUG if we
00060 // implement a strong expression equivalence checker in SCEV. Until then, we
00061 // use the verify-indvars flag, which may assert in some cases.
00062 static cl::opt<bool> VerifyIndvars(
00063   "verify-indvars", cl::Hidden,
00064   cl::desc("Verify the ScalarEvolution result after running indvars"));
00065 
00066 static cl::opt<bool> ReduceLiveIVs("liv-reduce", cl::Hidden,
00067   cl::desc("Reduce live induction variables."));
00068 
00069 namespace {
00070   class IndVarSimplify : public LoopPass {
00071     LoopInfo        *LI;
00072     ScalarEvolution *SE;
00073     DominatorTree   *DT;
00074     const DataLayout *DL;
00075     TargetLibraryInfo *TLI;
00076 
00077     SmallVector<WeakVH, 16> DeadInsts;
00078     bool Changed;
00079   public:
00080 
00081     static char ID; // Pass identification, replacement for typeid
00082     IndVarSimplify() : LoopPass(ID), LI(0), SE(0), DT(0), DL(0),
00083                        Changed(false) {
00084       initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
00085     }
00086 
00087     bool runOnLoop(Loop *L, LPPassManager &LPM) override;
00088 
00089     void getAnalysisUsage(AnalysisUsage &AU) const override {
00090       AU.addRequired<DominatorTreeWrapperPass>();
00091       AU.addRequired<LoopInfo>();
00092       AU.addRequired<ScalarEvolution>();
00093       AU.addRequiredID(LoopSimplifyID);
00094       AU.addRequiredID(LCSSAID);
00095       AU.addPreserved<ScalarEvolution>();
00096       AU.addPreservedID(LoopSimplifyID);
00097       AU.addPreservedID(LCSSAID);
00098       AU.setPreservesCFG();
00099     }
00100 
00101   private:
00102     void releaseMemory() override {
00103       DeadInsts.clear();
00104     }
00105 
00106     bool isValidRewrite(Value *FromVal, Value *ToVal);
00107 
00108     void HandleFloatingPointIV(Loop *L, PHINode *PH);
00109     void RewriteNonIntegerIVs(Loop *L);
00110 
00111     void SimplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LPPassManager &LPM);
00112 
00113     void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
00114 
00115     Value *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
00116                                      PHINode *IndVar, SCEVExpander &Rewriter);
00117 
00118     void SinkUnusedInvariants(Loop *L);
00119   };
00120 }
00121 
00122 char IndVarSimplify::ID = 0;
00123 INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
00124                 "Induction Variable Simplification", false, false)
00125 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00126 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
00127 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
00128 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
00129 INITIALIZE_PASS_DEPENDENCY(LCSSA)
00130 INITIALIZE_PASS_END(IndVarSimplify, "indvars",
00131                 "Induction Variable Simplification", false, false)
00132 
00133 Pass *llvm::createIndVarSimplifyPass() {
00134   return new IndVarSimplify();
00135 }
00136 
00137 /// isValidRewrite - Return true if the SCEV expansion generated by the
00138 /// rewriter can replace the original value. SCEV guarantees that it
00139 /// produces the same value, but the way it is produced may be illegal IR.
00140 /// Ideally, this function will only be called for verification.
00141 bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
00142   // If an SCEV expression subsumed multiple pointers, its expansion could
00143   // reassociate the GEP changing the base pointer. This is illegal because the
00144   // final address produced by a GEP chain must be inbounds relative to its
00145   // underlying object. Otherwise basic alias analysis, among other things,
00146   // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
00147   // producing an expression involving multiple pointers. Until then, we must
00148   // bail out here.
00149   //
00150   // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
00151   // because it understands lcssa phis while SCEV does not.
00152   Value *FromPtr = FromVal;
00153   Value *ToPtr = ToVal;
00154   if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
00155     FromPtr = GEP->getPointerOperand();
00156   }
00157   if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
00158     ToPtr = GEP->getPointerOperand();
00159   }
00160   if (FromPtr != FromVal || ToPtr != ToVal) {
00161     // Quickly check the common case
00162     if (FromPtr == ToPtr)
00163       return true;
00164 
00165     // SCEV may have rewritten an expression that produces the GEP's pointer
00166     // operand. That's ok as long as the pointer operand has the same base
00167     // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
00168     // base of a recurrence. This handles the case in which SCEV expansion
00169     // converts a pointer type recurrence into a nonrecurrent pointer base
00170     // indexed by an integer recurrence.
00171 
00172     // If the GEP base pointer is a vector of pointers, abort.
00173     if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy())
00174       return false;
00175 
00176     const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
00177     const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
00178     if (FromBase == ToBase)
00179       return true;
00180 
00181     DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
00182           << *FromBase << " != " << *ToBase << "\n");
00183 
00184     return false;
00185   }
00186   return true;
00187 }
00188 
00189 /// Determine the insertion point for this user. By default, insert immediately
00190 /// before the user. SCEVExpander or LICM will hoist loop invariants out of the
00191 /// loop. For PHI nodes, there may be multiple uses, so compute the nearest
00192 /// common dominator for the incoming blocks.
00193 static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
00194                                           DominatorTree *DT) {
00195   PHINode *PHI = dyn_cast<PHINode>(User);
00196   if (!PHI)
00197     return User;
00198 
00199   Instruction *InsertPt = 0;
00200   for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
00201     if (PHI->getIncomingValue(i) != Def)
00202       continue;
00203 
00204     BasicBlock *InsertBB = PHI->getIncomingBlock(i);
00205     if (!InsertPt) {
00206       InsertPt = InsertBB->getTerminator();
00207       continue;
00208     }
00209     InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
00210     InsertPt = InsertBB->getTerminator();
00211   }
00212   assert(InsertPt && "Missing phi operand");
00213   assert((!isa<Instruction>(Def) ||
00214           DT->dominates(cast<Instruction>(Def), InsertPt)) &&
00215          "def does not dominate all uses");
00216   return InsertPt;
00217 }
00218 
00219 //===----------------------------------------------------------------------===//
00220 // RewriteNonIntegerIVs and helpers. Prefer integer IVs.
00221 //===----------------------------------------------------------------------===//
00222 
00223 /// ConvertToSInt - Convert APF to an integer, if possible.
00224 static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
00225   bool isExact = false;
00226   // See if we can convert this to an int64_t
00227   uint64_t UIntVal;
00228   if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
00229                            &isExact) != APFloat::opOK || !isExact)
00230     return false;
00231   IntVal = UIntVal;
00232   return true;
00233 }
00234 
00235 /// HandleFloatingPointIV - If the loop has floating induction variable
00236 /// then insert corresponding integer induction variable if possible.
00237 /// For example,
00238 /// for(double i = 0; i < 10000; ++i)
00239 ///   bar(i)
00240 /// is converted into
00241 /// for(int i = 0; i < 10000; ++i)
00242 ///   bar((double)i);
00243 ///
00244 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
00245   unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
00246   unsigned BackEdge     = IncomingEdge^1;
00247 
00248   // Check incoming value.
00249   ConstantFP *InitValueVal =
00250     dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
00251 
00252   int64_t InitValue;
00253   if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
00254     return;
00255 
00256   // Check IV increment. Reject this PN if increment operation is not
00257   // an add or increment value can not be represented by an integer.
00258   BinaryOperator *Incr =
00259     dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
00260   if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
00261 
00262   // If this is not an add of the PHI with a constantfp, or if the constant fp
00263   // is not an integer, bail out.
00264   ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
00265   int64_t IncValue;
00266   if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
00267       !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
00268     return;
00269 
00270   // Check Incr uses. One user is PN and the other user is an exit condition
00271   // used by the conditional terminator.
00272   Value::user_iterator IncrUse = Incr->user_begin();
00273   Instruction *U1 = cast<Instruction>(*IncrUse++);
00274   if (IncrUse == Incr->user_end()) return;
00275   Instruction *U2 = cast<Instruction>(*IncrUse++);
00276   if (IncrUse != Incr->user_end()) return;
00277 
00278   // Find exit condition, which is an fcmp.  If it doesn't exist, or if it isn't
00279   // only used by a branch, we can't transform it.
00280   FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
00281   if (!Compare)
00282     Compare = dyn_cast<FCmpInst>(U2);
00283   if (Compare == 0 || !Compare->hasOneUse() ||
00284       !isa<BranchInst>(Compare->user_back()))
00285     return;
00286 
00287   BranchInst *TheBr = cast<BranchInst>(Compare->user_back());
00288 
00289   // We need to verify that the branch actually controls the iteration count
00290   // of the loop.  If not, the new IV can overflow and no one will notice.
00291   // The branch block must be in the loop and one of the successors must be out
00292   // of the loop.
00293   assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
00294   if (!L->contains(TheBr->getParent()) ||
00295       (L->contains(TheBr->getSuccessor(0)) &&
00296        L->contains(TheBr->getSuccessor(1))))
00297     return;
00298 
00299 
00300   // If it isn't a comparison with an integer-as-fp (the exit value), we can't
00301   // transform it.
00302   ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
00303   int64_t ExitValue;
00304   if (ExitValueVal == 0 ||
00305       !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
00306     return;
00307 
00308   // Find new predicate for integer comparison.
00309   CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
00310   switch (Compare->getPredicate()) {
00311   default: return;  // Unknown comparison.
00312   case CmpInst::FCMP_OEQ:
00313   case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
00314   case CmpInst::FCMP_ONE:
00315   case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
00316   case CmpInst::FCMP_OGT:
00317   case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
00318   case CmpInst::FCMP_OGE:
00319   case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
00320   case CmpInst::FCMP_OLT:
00321   case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
00322   case CmpInst::FCMP_OLE:
00323   case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
00324   }
00325 
00326   // We convert the floating point induction variable to a signed i32 value if
00327   // we can.  This is only safe if the comparison will not overflow in a way
00328   // that won't be trapped by the integer equivalent operations.  Check for this
00329   // now.
00330   // TODO: We could use i64 if it is native and the range requires it.
00331 
00332   // The start/stride/exit values must all fit in signed i32.
00333   if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
00334     return;
00335 
00336   // If not actually striding (add x, 0.0), avoid touching the code.
00337   if (IncValue == 0)
00338     return;
00339 
00340   // Positive and negative strides have different safety conditions.
00341   if (IncValue > 0) {
00342     // If we have a positive stride, we require the init to be less than the
00343     // exit value.
00344     if (InitValue >= ExitValue)
00345       return;
00346 
00347     uint32_t Range = uint32_t(ExitValue-InitValue);
00348     // Check for infinite loop, either:
00349     // while (i <= Exit) or until (i > Exit)
00350     if (NewPred == CmpInst::ICMP_SLE || NewPred == CmpInst::ICMP_SGT) {
00351       if (++Range == 0) return;  // Range overflows.
00352     }
00353 
00354     unsigned Leftover = Range % uint32_t(IncValue);
00355 
00356     // If this is an equality comparison, we require that the strided value
00357     // exactly land on the exit value, otherwise the IV condition will wrap
00358     // around and do things the fp IV wouldn't.
00359     if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
00360         Leftover != 0)
00361       return;
00362 
00363     // If the stride would wrap around the i32 before exiting, we can't
00364     // transform the IV.
00365     if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
00366       return;
00367 
00368   } else {
00369     // If we have a negative stride, we require the init to be greater than the
00370     // exit value.
00371     if (InitValue <= ExitValue)
00372       return;
00373 
00374     uint32_t Range = uint32_t(InitValue-ExitValue);
00375     // Check for infinite loop, either:
00376     // while (i >= Exit) or until (i < Exit)
00377     if (NewPred == CmpInst::ICMP_SGE || NewPred == CmpInst::ICMP_SLT) {
00378       if (++Range == 0) return;  // Range overflows.
00379     }
00380 
00381     unsigned Leftover = Range % uint32_t(-IncValue);
00382 
00383     // If this is an equality comparison, we require that the strided value
00384     // exactly land on the exit value, otherwise the IV condition will wrap
00385     // around and do things the fp IV wouldn't.
00386     if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
00387         Leftover != 0)
00388       return;
00389 
00390     // If the stride would wrap around the i32 before exiting, we can't
00391     // transform the IV.
00392     if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
00393       return;
00394   }
00395 
00396   IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
00397 
00398   // Insert new integer induction variable.
00399   PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
00400   NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
00401                       PN->getIncomingBlock(IncomingEdge));
00402 
00403   Value *NewAdd =
00404     BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
00405                               Incr->getName()+".int", Incr);
00406   NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
00407 
00408   ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
00409                                       ConstantInt::get(Int32Ty, ExitValue),
00410                                       Compare->getName());
00411 
00412   // In the following deletions, PN may become dead and may be deleted.
00413   // Use a WeakVH to observe whether this happens.
00414   WeakVH WeakPH = PN;
00415 
00416   // Delete the old floating point exit comparison.  The branch starts using the
00417   // new comparison.
00418   NewCompare->takeName(Compare);
00419   Compare->replaceAllUsesWith(NewCompare);
00420   RecursivelyDeleteTriviallyDeadInstructions(Compare, TLI);
00421 
00422   // Delete the old floating point increment.
00423   Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
00424   RecursivelyDeleteTriviallyDeadInstructions(Incr, TLI);
00425 
00426   // If the FP induction variable still has uses, this is because something else
00427   // in the loop uses its value.  In order to canonicalize the induction
00428   // variable, we chose to eliminate the IV and rewrite it in terms of an
00429   // int->fp cast.
00430   //
00431   // We give preference to sitofp over uitofp because it is faster on most
00432   // platforms.
00433   if (WeakPH) {
00434     Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
00435                                  PN->getParent()->getFirstInsertionPt());
00436     PN->replaceAllUsesWith(Conv);
00437     RecursivelyDeleteTriviallyDeadInstructions(PN, TLI);
00438   }
00439   Changed = true;
00440 }
00441 
00442 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
00443   // First step.  Check to see if there are any floating-point recurrences.
00444   // If there are, change them into integer recurrences, permitting analysis by
00445   // the SCEV routines.
00446   //
00447   BasicBlock *Header = L->getHeader();
00448 
00449   SmallVector<WeakVH, 8> PHIs;
00450   for (BasicBlock::iterator I = Header->begin();
00451        PHINode *PN = dyn_cast<PHINode>(I); ++I)
00452     PHIs.push_back(PN);
00453 
00454   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
00455     if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
00456       HandleFloatingPointIV(L, PN);
00457 
00458   // If the loop previously had floating-point IV, ScalarEvolution
00459   // may not have been able to compute a trip count. Now that we've done some
00460   // re-writing, the trip count may be computable.
00461   if (Changed)
00462     SE->forgetLoop(L);
00463 }
00464 
00465 //===----------------------------------------------------------------------===//
00466 // RewriteLoopExitValues - Optimize IV users outside the loop.
00467 // As a side effect, reduces the amount of IV processing within the loop.
00468 //===----------------------------------------------------------------------===//
00469 
00470 /// RewriteLoopExitValues - Check to see if this loop has a computable
00471 /// loop-invariant execution count.  If so, this means that we can compute the
00472 /// final value of any expressions that are recurrent in the loop, and
00473 /// substitute the exit values from the loop into any instructions outside of
00474 /// the loop that use the final values of the current expressions.
00475 ///
00476 /// This is mostly redundant with the regular IndVarSimplify activities that
00477 /// happen later, except that it's more powerful in some cases, because it's
00478 /// able to brute-force evaluate arbitrary instructions as long as they have
00479 /// constant operands at the beginning of the loop.
00480 void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
00481   // Verify the input to the pass in already in LCSSA form.
00482   assert(L->isLCSSAForm(*DT));
00483 
00484   SmallVector<BasicBlock*, 8> ExitBlocks;
00485   L->getUniqueExitBlocks(ExitBlocks);
00486 
00487   // Find all values that are computed inside the loop, but used outside of it.
00488   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
00489   // the exit blocks of the loop to find them.
00490   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
00491     BasicBlock *ExitBB = ExitBlocks[i];
00492 
00493     // If there are no PHI nodes in this exit block, then no values defined
00494     // inside the loop are used on this path, skip it.
00495     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
00496     if (!PN) continue;
00497 
00498     unsigned NumPreds = PN->getNumIncomingValues();
00499 
00500     // We would like to be able to RAUW single-incoming value PHI nodes. We
00501     // have to be certain this is safe even when this is an LCSSA PHI node.
00502     // While the computed exit value is no longer varying in *this* loop, the
00503     // exit block may be an exit block for an outer containing loop as well,
00504     // the exit value may be varying in the outer loop, and thus it may still
00505     // require an LCSSA PHI node. The safe case is when this is
00506     // single-predecessor PHI node (LCSSA) and the exit block containing it is
00507     // part of the enclosing loop, or this is the outer most loop of the nest.
00508     // In either case the exit value could (at most) be varying in the same
00509     // loop body as the phi node itself. Thus if it is in turn used outside of
00510     // an enclosing loop it will only be via a separate LCSSA node.
00511     bool LCSSASafePhiForRAUW =
00512         NumPreds == 1 &&
00513         (!L->getParentLoop() || L->getParentLoop() == LI->getLoopFor(ExitBB));
00514 
00515     // Iterate over all of the PHI nodes.
00516     BasicBlock::iterator BBI = ExitBB->begin();
00517     while ((PN = dyn_cast<PHINode>(BBI++))) {
00518       if (PN->use_empty())
00519         continue; // dead use, don't replace it
00520 
00521       // SCEV only supports integer expressions for now.
00522       if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
00523         continue;
00524 
00525       // It's necessary to tell ScalarEvolution about this explicitly so that
00526       // it can walk the def-use list and forget all SCEVs, as it may not be
00527       // watching the PHI itself. Once the new exit value is in place, there
00528       // may not be a def-use connection between the loop and every instruction
00529       // which got a SCEVAddRecExpr for that loop.
00530       SE->forgetValue(PN);
00531 
00532       // Iterate over all of the values in all the PHI nodes.
00533       for (unsigned i = 0; i != NumPreds; ++i) {
00534         // If the value being merged in is not integer or is not defined
00535         // in the loop, skip it.
00536         Value *InVal = PN->getIncomingValue(i);
00537         if (!isa<Instruction>(InVal))
00538           continue;
00539 
00540         // If this pred is for a subloop, not L itself, skip it.
00541         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
00542           continue; // The Block is in a subloop, skip it.
00543 
00544         // Check that InVal is defined in the loop.
00545         Instruction *Inst = cast<Instruction>(InVal);
00546         if (!L->contains(Inst))
00547           continue;
00548 
00549         // Okay, this instruction has a user outside of the current loop
00550         // and varies predictably *inside* the loop.  Evaluate the value it
00551         // contains when the loop exits, if possible.
00552         const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
00553         if (!SE->isLoopInvariant(ExitValue, L) ||
00554             !isSafeToExpand(ExitValue, *SE))
00555           continue;
00556 
00557         // Computing the value outside of the loop brings no benefit if :
00558         //  - it is definitely used inside the loop in a way which can not be
00559         //    optimized away.
00560         //  - no use outside of the loop can take advantage of hoisting the
00561         //    computation out of the loop
00562         if (ExitValue->getSCEVType()>=scMulExpr) {
00563           unsigned NumHardInternalUses = 0;
00564           unsigned NumSoftExternalUses = 0;
00565           unsigned NumUses = 0;
00566           for (auto IB = Inst->user_begin(), IE = Inst->user_end();
00567                IB != IE && NumUses <= 6; ++IB) {
00568             Instruction *UseInstr = cast<Instruction>(*IB);
00569             unsigned Opc = UseInstr->getOpcode();
00570             NumUses++;
00571             if (L->contains(UseInstr)) {
00572               if (Opc == Instruction::Call || Opc == Instruction::Ret)
00573                 NumHardInternalUses++;
00574             } else {
00575               if (Opc == Instruction::PHI) {
00576                 // Do not count the Phi as a use. LCSSA may have inserted
00577                 // plenty of trivial ones.
00578                 NumUses--;
00579                 for (auto PB = UseInstr->user_begin(),
00580                           PE = UseInstr->user_end();
00581                      PB != PE && NumUses <= 6; ++PB, ++NumUses) {
00582                   unsigned PhiOpc = cast<Instruction>(*PB)->getOpcode();
00583                   if (PhiOpc != Instruction::Call && PhiOpc != Instruction::Ret)
00584                     NumSoftExternalUses++;
00585                 }
00586                 continue;
00587               }
00588               if (Opc != Instruction::Call && Opc != Instruction::Ret)
00589                 NumSoftExternalUses++;
00590             }
00591           }
00592           if (NumUses <= 6 && NumHardInternalUses && !NumSoftExternalUses)
00593             continue;
00594         }
00595 
00596         Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
00597 
00598         DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
00599                      << "  LoopVal = " << *Inst << "\n");
00600 
00601         if (!isValidRewrite(Inst, ExitVal)) {
00602           DeadInsts.push_back(ExitVal);
00603           continue;
00604         }
00605         Changed = true;
00606         ++NumReplaced;
00607 
00608         PN->setIncomingValue(i, ExitVal);
00609 
00610         // If this instruction is dead now, delete it. Don't do it now to avoid
00611         // invalidating iterators.
00612         if (isInstructionTriviallyDead(Inst, TLI))
00613           DeadInsts.push_back(Inst);
00614 
00615         // If we determined that this PHI is safe to replace even if an LCSSA
00616         // PHI, do so.
00617         if (LCSSASafePhiForRAUW) {
00618           PN->replaceAllUsesWith(ExitVal);
00619           PN->eraseFromParent();
00620         }
00621       }
00622 
00623       // If we were unable to completely replace the PHI node, clone the PHI
00624       // and delete the original one. This lets IVUsers and any other maps
00625       // purge the original user from their records.
00626       if (!LCSSASafePhiForRAUW) {
00627         PHINode *NewPN = cast<PHINode>(PN->clone());
00628         NewPN->takeName(PN);
00629         NewPN->insertBefore(PN);
00630         PN->replaceAllUsesWith(NewPN);
00631         PN->eraseFromParent();
00632       }
00633     }
00634   }
00635 
00636   // The insertion point instruction may have been deleted; clear it out
00637   // so that the rewriter doesn't trip over it later.
00638   Rewriter.clearInsertPoint();
00639 }
00640 
00641 //===----------------------------------------------------------------------===//
00642 //  IV Widening - Extend the width of an IV to cover its widest uses.
00643 //===----------------------------------------------------------------------===//
00644 
00645 namespace {
00646   // Collect information about induction variables that are used by sign/zero
00647   // extend operations. This information is recorded by CollectExtend and
00648   // provides the input to WidenIV.
00649   struct WideIVInfo {
00650     PHINode *NarrowIV;
00651     Type *WidestNativeType; // Widest integer type created [sz]ext
00652     bool IsSigned;          // Was an sext user seen before a zext?
00653 
00654     WideIVInfo() : NarrowIV(0), WidestNativeType(0), IsSigned(false) {}
00655   };
00656 }
00657 
00658 /// visitCast - Update information about the induction variable that is
00659 /// extended by this sign or zero extend operation. This is used to determine
00660 /// the final width of the IV before actually widening it.
00661 static void visitIVCast(CastInst *Cast, WideIVInfo &WI, ScalarEvolution *SE,
00662                         const DataLayout *DL) {
00663   bool IsSigned = Cast->getOpcode() == Instruction::SExt;
00664   if (!IsSigned && Cast->getOpcode() != Instruction::ZExt)
00665     return;
00666 
00667   Type *Ty = Cast->getType();
00668   uint64_t Width = SE->getTypeSizeInBits(Ty);
00669   if (DL && !DL->isLegalInteger(Width))
00670     return;
00671 
00672   if (!WI.WidestNativeType) {
00673     WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
00674     WI.IsSigned = IsSigned;
00675     return;
00676   }
00677 
00678   // We extend the IV to satisfy the sign of its first user, arbitrarily.
00679   if (WI.IsSigned != IsSigned)
00680     return;
00681 
00682   if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
00683     WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
00684 }
00685 
00686 namespace {
00687 
00688 /// NarrowIVDefUse - Record a link in the Narrow IV def-use chain along with the
00689 /// WideIV that computes the same value as the Narrow IV def.  This avoids
00690 /// caching Use* pointers.
00691 struct NarrowIVDefUse {
00692   Instruction *NarrowDef;
00693   Instruction *NarrowUse;
00694   Instruction *WideDef;
00695 
00696   NarrowIVDefUse(): NarrowDef(0), NarrowUse(0), WideDef(0) {}
00697 
00698   NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD):
00699     NarrowDef(ND), NarrowUse(NU), WideDef(WD) {}
00700 };
00701 
00702 /// WidenIV - The goal of this transform is to remove sign and zero extends
00703 /// without creating any new induction variables. To do this, it creates a new
00704 /// phi of the wider type and redirects all users, either removing extends or
00705 /// inserting truncs whenever we stop propagating the type.
00706 ///
00707 class WidenIV {
00708   // Parameters
00709   PHINode *OrigPhi;
00710   Type *WideType;
00711   bool IsSigned;
00712 
00713   // Context
00714   LoopInfo        *LI;
00715   Loop            *L;
00716   ScalarEvolution *SE;
00717   DominatorTree   *DT;
00718 
00719   // Result
00720   PHINode *WidePhi;
00721   Instruction *WideInc;
00722   const SCEV *WideIncExpr;
00723   SmallVectorImpl<WeakVH> &DeadInsts;
00724 
00725   SmallPtrSet<Instruction*,16> Widened;
00726   SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
00727 
00728 public:
00729   WidenIV(const WideIVInfo &WI, LoopInfo *LInfo,
00730           ScalarEvolution *SEv, DominatorTree *DTree,
00731           SmallVectorImpl<WeakVH> &DI) :
00732     OrigPhi(WI.NarrowIV),
00733     WideType(WI.WidestNativeType),
00734     IsSigned(WI.IsSigned),
00735     LI(LInfo),
00736     L(LI->getLoopFor(OrigPhi->getParent())),
00737     SE(SEv),
00738     DT(DTree),
00739     WidePhi(0),
00740     WideInc(0),
00741     WideIncExpr(0),
00742     DeadInsts(DI) {
00743     assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
00744   }
00745 
00746   PHINode *CreateWideIV(SCEVExpander &Rewriter);
00747 
00748 protected:
00749   Value *getExtend(Value *NarrowOper, Type *WideType, bool IsSigned,
00750                    Instruction *Use);
00751 
00752   Instruction *CloneIVUser(NarrowIVDefUse DU);
00753 
00754   const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
00755 
00756   const SCEVAddRecExpr* GetExtendedOperandRecurrence(NarrowIVDefUse DU);
00757 
00758   Instruction *WidenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter);
00759 
00760   void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
00761 };
00762 } // anonymous namespace
00763 
00764 /// isLoopInvariant - Perform a quick domtree based check for loop invariance
00765 /// assuming that V is used within the loop. LoopInfo::isLoopInvariant() seems
00766 /// gratuitous for this purpose.
00767 static bool isLoopInvariant(Value *V, const Loop *L, const DominatorTree *DT) {
00768   Instruction *Inst = dyn_cast<Instruction>(V);
00769   if (!Inst)
00770     return true;
00771 
00772   return DT->properlyDominates(Inst->getParent(), L->getHeader());
00773 }
00774 
00775 Value *WidenIV::getExtend(Value *NarrowOper, Type *WideType, bool IsSigned,
00776                           Instruction *Use) {
00777   // Set the debug location and conservative insertion point.
00778   IRBuilder<> Builder(Use);
00779   // Hoist the insertion point into loop preheaders as far as possible.
00780   for (const Loop *L = LI->getLoopFor(Use->getParent());
00781        L && L->getLoopPreheader() && isLoopInvariant(NarrowOper, L, DT);
00782        L = L->getParentLoop())
00783     Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
00784 
00785   return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
00786                     Builder.CreateZExt(NarrowOper, WideType);
00787 }
00788 
00789 /// CloneIVUser - Instantiate a wide operation to replace a narrow
00790 /// operation. This only needs to handle operations that can evaluation to
00791 /// SCEVAddRec. It can safely return 0 for any operation we decide not to clone.
00792 Instruction *WidenIV::CloneIVUser(NarrowIVDefUse DU) {
00793   unsigned Opcode = DU.NarrowUse->getOpcode();
00794   switch (Opcode) {
00795   default:
00796     return 0;
00797   case Instruction::Add:
00798   case Instruction::Mul:
00799   case Instruction::UDiv:
00800   case Instruction::Sub:
00801   case Instruction::And:
00802   case Instruction::Or:
00803   case Instruction::Xor:
00804   case Instruction::Shl:
00805   case Instruction::LShr:
00806   case Instruction::AShr:
00807     DEBUG(dbgs() << "Cloning IVUser: " << *DU.NarrowUse << "\n");
00808 
00809     // Replace NarrowDef operands with WideDef. Otherwise, we don't know
00810     // anything about the narrow operand yet so must insert a [sz]ext. It is
00811     // probably loop invariant and will be folded or hoisted. If it actually
00812     // comes from a widened IV, it should be removed during a future call to
00813     // WidenIVUse.
00814     Value *LHS = (DU.NarrowUse->getOperand(0) == DU.NarrowDef) ? DU.WideDef :
00815       getExtend(DU.NarrowUse->getOperand(0), WideType, IsSigned, DU.NarrowUse);
00816     Value *RHS = (DU.NarrowUse->getOperand(1) == DU.NarrowDef) ? DU.WideDef :
00817       getExtend(DU.NarrowUse->getOperand(1), WideType, IsSigned, DU.NarrowUse);
00818 
00819     BinaryOperator *NarrowBO = cast<BinaryOperator>(DU.NarrowUse);
00820     BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
00821                                                     LHS, RHS,
00822                                                     NarrowBO->getName());
00823     IRBuilder<> Builder(DU.NarrowUse);
00824     Builder.Insert(WideBO);
00825     if (const OverflowingBinaryOperator *OBO =
00826         dyn_cast<OverflowingBinaryOperator>(NarrowBO)) {
00827       if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
00828       if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
00829     }
00830     return WideBO;
00831   }
00832 }
00833 
00834 /// No-wrap operations can transfer sign extension of their result to their
00835 /// operands. Generate the SCEV value for the widened operation without
00836 /// actually modifying the IR yet. If the expression after extending the
00837 /// operands is an AddRec for this loop, return it.
00838 const SCEVAddRecExpr* WidenIV::GetExtendedOperandRecurrence(NarrowIVDefUse DU) {
00839   // Handle the common case of add<nsw/nuw>
00840   if (DU.NarrowUse->getOpcode() != Instruction::Add)
00841     return 0;
00842 
00843   // One operand (NarrowDef) has already been extended to WideDef. Now determine
00844   // if extending the other will lead to a recurrence.
00845   unsigned ExtendOperIdx = DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
00846   assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU");
00847 
00848   const SCEV *ExtendOperExpr = 0;
00849   const OverflowingBinaryOperator *OBO =
00850     cast<OverflowingBinaryOperator>(DU.NarrowUse);
00851   if (IsSigned && OBO->hasNoSignedWrap())
00852     ExtendOperExpr = SE->getSignExtendExpr(
00853       SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
00854   else if(!IsSigned && OBO->hasNoUnsignedWrap())
00855     ExtendOperExpr = SE->getZeroExtendExpr(
00856       SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
00857   else
00858     return 0;
00859 
00860   // When creating this AddExpr, don't apply the current operations NSW or NUW
00861   // flags. This instruction may be guarded by control flow that the no-wrap
00862   // behavior depends on. Non-control-equivalent instructions can be mapped to
00863   // the same SCEV expression, and it would be incorrect to transfer NSW/NUW
00864   // semantics to those operations.
00865   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(
00866     SE->getAddExpr(SE->getSCEV(DU.WideDef), ExtendOperExpr));
00867 
00868   if (!AddRec || AddRec->getLoop() != L)
00869     return 0;
00870   return AddRec;
00871 }
00872 
00873 /// GetWideRecurrence - Is this instruction potentially interesting from
00874 /// IVUsers' perspective after widening it's type? In other words, can the
00875 /// extend be safely hoisted out of the loop with SCEV reducing the value to a
00876 /// recurrence on the same loop. If so, return the sign or zero extended
00877 /// recurrence. Otherwise return NULL.
00878 const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
00879   if (!SE->isSCEVable(NarrowUse->getType()))
00880     return 0;
00881 
00882   const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
00883   if (SE->getTypeSizeInBits(NarrowExpr->getType())
00884       >= SE->getTypeSizeInBits(WideType)) {
00885     // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
00886     // index. So don't follow this use.
00887     return 0;
00888   }
00889 
00890   const SCEV *WideExpr = IsSigned ?
00891     SE->getSignExtendExpr(NarrowExpr, WideType) :
00892     SE->getZeroExtendExpr(NarrowExpr, WideType);
00893   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
00894   if (!AddRec || AddRec->getLoop() != L)
00895     return 0;
00896   return AddRec;
00897 }
00898 
00899 /// This IV user cannot be widen. Replace this use of the original narrow IV
00900 /// with a truncation of the new wide IV to isolate and eliminate the narrow IV.
00901 static void truncateIVUse(NarrowIVDefUse DU, DominatorTree *DT) {
00902   DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef
00903         << " for user " << *DU.NarrowUse << "\n");
00904   IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT));
00905   Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
00906   DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
00907 }
00908 
00909 /// WidenIVUse - Determine whether an individual user of the narrow IV can be
00910 /// widened. If so, return the wide clone of the user.
00911 Instruction *WidenIV::WidenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter) {
00912 
00913   // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
00914   if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
00915     if (LI->getLoopFor(UsePhi->getParent()) != L) {
00916       // For LCSSA phis, sink the truncate outside the loop.
00917       // After SimplifyCFG most loop exit targets have a single predecessor.
00918       // Otherwise fall back to a truncate within the loop.
00919       if (UsePhi->getNumOperands() != 1)
00920         truncateIVUse(DU, DT);
00921       else {
00922         PHINode *WidePhi =
00923           PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
00924                           UsePhi);
00925         WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
00926         IRBuilder<> Builder(WidePhi->getParent()->getFirstInsertionPt());
00927         Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
00928         UsePhi->replaceAllUsesWith(Trunc);
00929         DeadInsts.push_back(UsePhi);
00930         DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi
00931               << " to " << *WidePhi << "\n");
00932       }
00933       return 0;
00934     }
00935   }
00936   // Our raison d'etre! Eliminate sign and zero extension.
00937   if (IsSigned ? isa<SExtInst>(DU.NarrowUse) : isa<ZExtInst>(DU.NarrowUse)) {
00938     Value *NewDef = DU.WideDef;
00939     if (DU.NarrowUse->getType() != WideType) {
00940       unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
00941       unsigned IVWidth = SE->getTypeSizeInBits(WideType);
00942       if (CastWidth < IVWidth) {
00943         // The cast isn't as wide as the IV, so insert a Trunc.
00944         IRBuilder<> Builder(DU.NarrowUse);
00945         NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
00946       }
00947       else {
00948         // A wider extend was hidden behind a narrower one. This may induce
00949         // another round of IV widening in which the intermediate IV becomes
00950         // dead. It should be very rare.
00951         DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
00952               << " not wide enough to subsume " << *DU.NarrowUse << "\n");
00953         DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
00954         NewDef = DU.NarrowUse;
00955       }
00956     }
00957     if (NewDef != DU.NarrowUse) {
00958       DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
00959             << " replaced by " << *DU.WideDef << "\n");
00960       ++NumElimExt;
00961       DU.NarrowUse->replaceAllUsesWith(NewDef);
00962       DeadInsts.push_back(DU.NarrowUse);
00963     }
00964     // Now that the extend is gone, we want to expose it's uses for potential
00965     // further simplification. We don't need to directly inform SimplifyIVUsers
00966     // of the new users, because their parent IV will be processed later as a
00967     // new loop phi. If we preserved IVUsers analysis, we would also want to
00968     // push the uses of WideDef here.
00969 
00970     // No further widening is needed. The deceased [sz]ext had done it for us.
00971     return 0;
00972   }
00973 
00974   // Does this user itself evaluate to a recurrence after widening?
00975   const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(DU.NarrowUse);
00976   if (!WideAddRec) {
00977       WideAddRec = GetExtendedOperandRecurrence(DU);
00978   }
00979   if (!WideAddRec) {
00980     // This user does not evaluate to a recurence after widening, so don't
00981     // follow it. Instead insert a Trunc to kill off the original use,
00982     // eventually isolating the original narrow IV so it can be removed.
00983     truncateIVUse(DU, DT);
00984     return 0;
00985   }
00986   // Assume block terminators cannot evaluate to a recurrence. We can't to
00987   // insert a Trunc after a terminator if there happens to be a critical edge.
00988   assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
00989          "SCEV is not expected to evaluate a block terminator");
00990 
00991   // Reuse the IV increment that SCEVExpander created as long as it dominates
00992   // NarrowUse.
00993   Instruction *WideUse = 0;
00994   if (WideAddRec == WideIncExpr
00995       && Rewriter.hoistIVInc(WideInc, DU.NarrowUse))
00996     WideUse = WideInc;
00997   else {
00998     WideUse = CloneIVUser(DU);
00999     if (!WideUse)
01000       return 0;
01001   }
01002   // Evaluation of WideAddRec ensured that the narrow expression could be
01003   // extended outside the loop without overflow. This suggests that the wide use
01004   // evaluates to the same expression as the extended narrow use, but doesn't
01005   // absolutely guarantee it. Hence the following failsafe check. In rare cases
01006   // where it fails, we simply throw away the newly created wide use.
01007   if (WideAddRec != SE->getSCEV(WideUse)) {
01008     DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
01009           << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
01010     DeadInsts.push_back(WideUse);
01011     return 0;
01012   }
01013 
01014   // Returning WideUse pushes it on the worklist.
01015   return WideUse;
01016 }
01017 
01018 /// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers.
01019 ///
01020 void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
01021   for (User *U : NarrowDef->users()) {
01022     Instruction *NarrowUser = cast<Instruction>(U);
01023 
01024     // Handle data flow merges and bizarre phi cycles.
01025     if (!Widened.insert(NarrowUser))
01026       continue;
01027 
01028     NarrowIVUsers.push_back(NarrowIVDefUse(NarrowDef, NarrowUser, WideDef));
01029   }
01030 }
01031 
01032 /// CreateWideIV - Process a single induction variable. First use the
01033 /// SCEVExpander to create a wide induction variable that evaluates to the same
01034 /// recurrence as the original narrow IV. Then use a worklist to forward
01035 /// traverse the narrow IV's def-use chain. After WidenIVUse has processed all
01036 /// interesting IV users, the narrow IV will be isolated for removal by
01037 /// DeleteDeadPHIs.
01038 ///
01039 /// It would be simpler to delete uses as they are processed, but we must avoid
01040 /// invalidating SCEV expressions.
01041 ///
01042 PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
01043   // Is this phi an induction variable?
01044   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
01045   if (!AddRec)
01046     return NULL;
01047 
01048   // Widen the induction variable expression.
01049   const SCEV *WideIVExpr = IsSigned ?
01050     SE->getSignExtendExpr(AddRec, WideType) :
01051     SE->getZeroExtendExpr(AddRec, WideType);
01052 
01053   assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
01054          "Expect the new IV expression to preserve its type");
01055 
01056   // Can the IV be extended outside the loop without overflow?
01057   AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
01058   if (!AddRec || AddRec->getLoop() != L)
01059     return NULL;
01060 
01061   // An AddRec must have loop-invariant operands. Since this AddRec is
01062   // materialized by a loop header phi, the expression cannot have any post-loop
01063   // operands, so they must dominate the loop header.
01064   assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
01065          SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
01066          && "Loop header phi recurrence inputs do not dominate the loop");
01067 
01068   // The rewriter provides a value for the desired IV expression. This may
01069   // either find an existing phi or materialize a new one. Either way, we
01070   // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
01071   // of the phi-SCC dominates the loop entry.
01072   Instruction *InsertPt = L->getHeader()->begin();
01073   WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
01074 
01075   // Remembering the WideIV increment generated by SCEVExpander allows
01076   // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
01077   // employ a general reuse mechanism because the call above is the only call to
01078   // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
01079   if (BasicBlock *LatchBlock = L->getLoopLatch()) {
01080     WideInc =
01081       cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
01082     WideIncExpr = SE->getSCEV(WideInc);
01083   }
01084 
01085   DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
01086   ++NumWidened;
01087 
01088   // Traverse the def-use chain using a worklist starting at the original IV.
01089   assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
01090 
01091   Widened.insert(OrigPhi);
01092   pushNarrowIVUsers(OrigPhi, WidePhi);
01093 
01094   while (!NarrowIVUsers.empty()) {
01095     NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
01096 
01097     // Process a def-use edge. This may replace the use, so don't hold a
01098     // use_iterator across it.
01099     Instruction *WideUse = WidenIVUse(DU, Rewriter);
01100 
01101     // Follow all def-use edges from the previous narrow use.
01102     if (WideUse)
01103       pushNarrowIVUsers(DU.NarrowUse, WideUse);
01104 
01105     // WidenIVUse may have removed the def-use edge.
01106     if (DU.NarrowDef->use_empty())
01107       DeadInsts.push_back(DU.NarrowDef);
01108   }
01109   return WidePhi;
01110 }
01111 
01112 //===----------------------------------------------------------------------===//
01113 //  Live IV Reduction - Minimize IVs live across the loop.
01114 //===----------------------------------------------------------------------===//
01115 
01116 
01117 //===----------------------------------------------------------------------===//
01118 //  Simplification of IV users based on SCEV evaluation.
01119 //===----------------------------------------------------------------------===//
01120 
01121 namespace {
01122   class IndVarSimplifyVisitor : public IVVisitor {
01123     ScalarEvolution *SE;
01124     const DataLayout *DL;
01125     PHINode *IVPhi;
01126 
01127   public:
01128     WideIVInfo WI;
01129 
01130     IndVarSimplifyVisitor(PHINode *IV, ScalarEvolution *SCEV,
01131                           const DataLayout *DL, const DominatorTree *DTree):
01132       SE(SCEV), DL(DL), IVPhi(IV) {
01133       DT = DTree;
01134       WI.NarrowIV = IVPhi;
01135       if (ReduceLiveIVs)
01136         setSplitOverflowIntrinsics();
01137     }
01138 
01139     // Implement the interface used by simplifyUsersOfIV.
01140     void visitCast(CastInst *Cast) override { visitIVCast(Cast, WI, SE, DL); }
01141   };
01142 }
01143 
01144 /// SimplifyAndExtend - Iteratively perform simplification on a worklist of IV
01145 /// users. Each successive simplification may push more users which may
01146 /// themselves be candidates for simplification.
01147 ///
01148 /// Sign/Zero extend elimination is interleaved with IV simplification.
01149 ///
01150 void IndVarSimplify::SimplifyAndExtend(Loop *L,
01151                                        SCEVExpander &Rewriter,
01152                                        LPPassManager &LPM) {
01153   SmallVector<WideIVInfo, 8> WideIVs;
01154 
01155   SmallVector<PHINode*, 8> LoopPhis;
01156   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
01157     LoopPhis.push_back(cast<PHINode>(I));
01158   }
01159   // Each round of simplification iterates through the SimplifyIVUsers worklist
01160   // for all current phis, then determines whether any IVs can be
01161   // widened. Widening adds new phis to LoopPhis, inducing another round of
01162   // simplification on the wide IVs.
01163   while (!LoopPhis.empty()) {
01164     // Evaluate as many IV expressions as possible before widening any IVs. This
01165     // forces SCEV to set no-wrap flags before evaluating sign/zero
01166     // extension. The first time SCEV attempts to normalize sign/zero extension,
01167     // the result becomes final. So for the most predictable results, we delay
01168     // evaluation of sign/zero extend evaluation until needed, and avoid running
01169     // other SCEV based analysis prior to SimplifyAndExtend.
01170     do {
01171       PHINode *CurrIV = LoopPhis.pop_back_val();
01172 
01173       // Information about sign/zero extensions of CurrIV.
01174       IndVarSimplifyVisitor Visitor(CurrIV, SE, DL, DT);
01175 
01176       Changed |= simplifyUsersOfIV(CurrIV, SE, &LPM, DeadInsts, &Visitor);
01177 
01178       if (Visitor.WI.WidestNativeType) {
01179         WideIVs.push_back(Visitor.WI);
01180       }
01181     } while(!LoopPhis.empty());
01182 
01183     for (; !WideIVs.empty(); WideIVs.pop_back()) {
01184       WidenIV Widener(WideIVs.back(), LI, SE, DT, DeadInsts);
01185       if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) {
01186         Changed = true;
01187         LoopPhis.push_back(WidePhi);
01188       }
01189     }
01190   }
01191 }
01192 
01193 //===----------------------------------------------------------------------===//
01194 //  LinearFunctionTestReplace and its kin. Rewrite the loop exit condition.
01195 //===----------------------------------------------------------------------===//
01196 
01197 /// Check for expressions that ScalarEvolution generates to compute
01198 /// BackedgeTakenInfo. If these expressions have not been reduced, then
01199 /// expanding them may incur additional cost (albeit in the loop preheader).
01200 static bool isHighCostExpansion(const SCEV *S, BranchInst *BI,
01201                                 SmallPtrSet<const SCEV*, 8> &Processed,
01202                                 ScalarEvolution *SE) {
01203   if (!Processed.insert(S))
01204     return false;
01205 
01206   // If the backedge-taken count is a UDiv, it's very likely a UDiv that
01207   // ScalarEvolution's HowFarToZero or HowManyLessThans produced to compute a
01208   // precise expression, rather than a UDiv from the user's code. If we can't
01209   // find a UDiv in the code with some simple searching, assume the former and
01210   // forego rewriting the loop.
01211   if (isa<SCEVUDivExpr>(S)) {
01212     ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
01213     if (!OrigCond) return true;
01214     const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
01215     R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
01216     if (R != S) {
01217       const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
01218       L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
01219       if (L != S)
01220         return true;
01221     }
01222   }
01223 
01224   // Recurse past add expressions, which commonly occur in the
01225   // BackedgeTakenCount. They may already exist in program code, and if not,
01226   // they are not too expensive rematerialize.
01227   if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
01228     for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
01229          I != E; ++I) {
01230       if (isHighCostExpansion(*I, BI, Processed, SE))
01231         return true;
01232     }
01233     return false;
01234   }
01235 
01236   // HowManyLessThans uses a Max expression whenever the loop is not guarded by
01237   // the exit condition.
01238   if (isa<SCEVSMaxExpr>(S) || isa<SCEVUMaxExpr>(S))
01239     return true;
01240 
01241   // If we haven't recognized an expensive SCEV pattern, assume it's an
01242   // expression produced by program code.
01243   return false;
01244 }
01245 
01246 /// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
01247 /// count expression can be safely and cheaply expanded into an instruction
01248 /// sequence that can be used by LinearFunctionTestReplace.
01249 ///
01250 /// TODO: This fails for pointer-type loop counters with greater than one byte
01251 /// strides, consequently preventing LFTR from running. For the purpose of LFTR
01252 /// we could skip this check in the case that the LFTR loop counter (chosen by
01253 /// FindLoopCounter) is also pointer type. Instead, we could directly convert
01254 /// the loop test to an inequality test by checking the target data's alignment
01255 /// of element types (given that the initial pointer value originates from or is
01256 /// used by ABI constrained operation, as opposed to inttoptr/ptrtoint).
01257 /// However, we don't yet have a strong motivation for converting loop tests
01258 /// into inequality tests.
01259 static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE) {
01260   const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
01261   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
01262       BackedgeTakenCount->isZero())
01263     return false;
01264 
01265   if (!L->getExitingBlock())
01266     return false;
01267 
01268   // Can't rewrite non-branch yet.
01269   BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
01270   if (!BI)
01271     return false;
01272 
01273   SmallPtrSet<const SCEV*, 8> Processed;
01274   if (isHighCostExpansion(BackedgeTakenCount, BI, Processed, SE))
01275     return false;
01276 
01277   return true;
01278 }
01279 
01280 /// getLoopPhiForCounter - Return the loop header phi IFF IncV adds a loop
01281 /// invariant value to the phi.
01282 static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) {
01283   Instruction *IncI = dyn_cast<Instruction>(IncV);
01284   if (!IncI)
01285     return 0;
01286 
01287   switch (IncI->getOpcode()) {
01288   case Instruction::Add:
01289   case Instruction::Sub:
01290     break;
01291   case Instruction::GetElementPtr:
01292     // An IV counter must preserve its type.
01293     if (IncI->getNumOperands() == 2)
01294       break;
01295   default:
01296     return 0;
01297   }
01298 
01299   PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
01300   if (Phi && Phi->getParent() == L->getHeader()) {
01301     if (isLoopInvariant(IncI->getOperand(1), L, DT))
01302       return Phi;
01303     return 0;
01304   }
01305   if (IncI->getOpcode() == Instruction::GetElementPtr)
01306     return 0;
01307 
01308   // Allow add/sub to be commuted.
01309   Phi = dyn_cast<PHINode>(IncI->getOperand(1));
01310   if (Phi && Phi->getParent() == L->getHeader()) {
01311     if (isLoopInvariant(IncI->getOperand(0), L, DT))
01312       return Phi;
01313   }
01314   return 0;
01315 }
01316 
01317 /// Return the compare guarding the loop latch, or NULL for unrecognized tests.
01318 static ICmpInst *getLoopTest(Loop *L) {
01319   assert(L->getExitingBlock() && "expected loop exit");
01320 
01321   BasicBlock *LatchBlock = L->getLoopLatch();
01322   // Don't bother with LFTR if the loop is not properly simplified.
01323   if (!LatchBlock)
01324     return 0;
01325 
01326   BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
01327   assert(BI && "expected exit branch");
01328 
01329   return dyn_cast<ICmpInst>(BI->getCondition());
01330 }
01331 
01332 /// needsLFTR - LinearFunctionTestReplace policy. Return true unless we can show
01333 /// that the current exit test is already sufficiently canonical.
01334 static bool needsLFTR(Loop *L, DominatorTree *DT) {
01335   // Do LFTR to simplify the exit condition to an ICMP.
01336   ICmpInst *Cond = getLoopTest(L);
01337   if (!Cond)
01338     return true;
01339 
01340   // Do LFTR to simplify the exit ICMP to EQ/NE
01341   ICmpInst::Predicate Pred = Cond->getPredicate();
01342   if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
01343     return true;
01344 
01345   // Look for a loop invariant RHS
01346   Value *LHS = Cond->getOperand(0);
01347   Value *RHS = Cond->getOperand(1);
01348   if (!isLoopInvariant(RHS, L, DT)) {
01349     if (!isLoopInvariant(LHS, L, DT))
01350       return true;
01351     std::swap(LHS, RHS);
01352   }
01353   // Look for a simple IV counter LHS
01354   PHINode *Phi = dyn_cast<PHINode>(LHS);
01355   if (!Phi)
01356     Phi = getLoopPhiForCounter(LHS, L, DT);
01357 
01358   if (!Phi)
01359     return true;
01360 
01361   // Do LFTR if PHI node is defined in the loop, but is *not* a counter.
01362   int Idx = Phi->getBasicBlockIndex(L->getLoopLatch());
01363   if (Idx < 0)
01364     return true;
01365 
01366   // Do LFTR if the exit condition's IV is *not* a simple counter.
01367   Value *IncV = Phi->getIncomingValue(Idx);
01368   return Phi != getLoopPhiForCounter(IncV, L, DT);
01369 }
01370 
01371 /// Recursive helper for hasConcreteDef(). Unfortunately, this currently boils
01372 /// down to checking that all operands are constant and listing instructions
01373 /// that may hide undef.
01374 static bool hasConcreteDefImpl(Value *V, SmallPtrSet<Value*, 8> &Visited,
01375                                unsigned Depth) {
01376   if (isa<Constant>(V))
01377     return !isa<UndefValue>(V);
01378 
01379   if (Depth >= 6)
01380     return false;
01381 
01382   // Conservatively handle non-constant non-instructions. For example, Arguments
01383   // may be undef.
01384   Instruction *I = dyn_cast<Instruction>(V);
01385   if (!I)
01386     return false;
01387 
01388   // Load and return values may be undef.
01389   if(I->mayReadFromMemory() || isa<CallInst>(I) || isa<InvokeInst>(I))
01390     return false;
01391 
01392   // Optimistically handle other instructions.
01393   for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) {
01394     if (!Visited.insert(*OI))
01395       continue;
01396     if (!hasConcreteDefImpl(*OI, Visited, Depth+1))
01397       return false;
01398   }
01399   return true;
01400 }
01401 
01402 /// Return true if the given value is concrete. We must prove that undef can
01403 /// never reach it.
01404 ///
01405 /// TODO: If we decide that this is a good approach to checking for undef, we
01406 /// may factor it into a common location.
01407 static bool hasConcreteDef(Value *V) {
01408   SmallPtrSet<Value*, 8> Visited;
01409   Visited.insert(V);
01410   return hasConcreteDefImpl(V, Visited, 0);
01411 }
01412 
01413 /// AlmostDeadIV - Return true if this IV has any uses other than the (soon to
01414 /// be rewritten) loop exit test.
01415 static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) {
01416   int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
01417   Value *IncV = Phi->getIncomingValue(LatchIdx);
01418 
01419   for (User *U : Phi->users())
01420     if (U != Cond && U != IncV) return false;
01421 
01422   for (User *U : IncV->users())
01423     if (U != Cond && U != Phi) return false;
01424   return true;
01425 }
01426 
01427 /// FindLoopCounter - Find an affine IV in canonical form.
01428 ///
01429 /// BECount may be an i8* pointer type. The pointer difference is already
01430 /// valid count without scaling the address stride, so it remains a pointer
01431 /// expression as far as SCEV is concerned.
01432 ///
01433 /// Currently only valid for LFTR. See the comments on hasConcreteDef below.
01434 ///
01435 /// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount
01436 ///
01437 /// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride.
01438 /// This is difficult in general for SCEV because of potential overflow. But we
01439 /// could at least handle constant BECounts.
01440 static PHINode *
01441 FindLoopCounter(Loop *L, const SCEV *BECount,
01442                 ScalarEvolution *SE, DominatorTree *DT, const DataLayout *DL) {
01443   uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
01444 
01445   Value *Cond =
01446     cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition();
01447 
01448   // Loop over all of the PHI nodes, looking for a simple counter.
01449   PHINode *BestPhi = 0;
01450   const SCEV *BestInit = 0;
01451   BasicBlock *LatchBlock = L->getLoopLatch();
01452   assert(LatchBlock && "needsLFTR should guarantee a loop latch");
01453 
01454   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
01455     PHINode *Phi = cast<PHINode>(I);
01456     if (!SE->isSCEVable(Phi->getType()))
01457       continue;
01458 
01459     // Avoid comparing an integer IV against a pointer Limit.
01460     if (BECount->getType()->isPointerTy() && !Phi->getType()->isPointerTy())
01461       continue;
01462 
01463     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
01464     if (!AR || AR->getLoop() != L || !AR->isAffine())
01465       continue;
01466 
01467     // AR may be a pointer type, while BECount is an integer type.
01468     // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
01469     // AR may not be a narrower type, or we may never exit.
01470     uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
01471     if (PhiWidth < BCWidth || (DL && !DL->isLegalInteger(PhiWidth)))
01472       continue;
01473 
01474     const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
01475     if (!Step || !Step->isOne())
01476       continue;
01477 
01478     int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
01479     Value *IncV = Phi->getIncomingValue(LatchIdx);
01480     if (getLoopPhiForCounter(IncV, L, DT) != Phi)
01481       continue;
01482 
01483     // Avoid reusing a potentially undef value to compute other values that may
01484     // have originally had a concrete definition.
01485     if (!hasConcreteDef(Phi)) {
01486       // We explicitly allow unknown phis as long as they are already used by
01487       // the loop test. In this case we assume that performing LFTR could not
01488       // increase the number of undef users.
01489       if (ICmpInst *Cond = getLoopTest(L)) {
01490         if (Phi != getLoopPhiForCounter(Cond->getOperand(0), L, DT)
01491             && Phi != getLoopPhiForCounter(Cond->getOperand(1), L, DT)) {
01492           continue;
01493         }
01494       }
01495     }
01496     const SCEV *Init = AR->getStart();
01497 
01498     if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
01499       // Don't force a live loop counter if another IV can be used.
01500       if (AlmostDeadIV(Phi, LatchBlock, Cond))
01501         continue;
01502 
01503       // Prefer to count-from-zero. This is a more "canonical" counter form. It
01504       // also prefers integer to pointer IVs.
01505       if (BestInit->isZero() != Init->isZero()) {
01506         if (BestInit->isZero())
01507           continue;
01508       }
01509       // If two IVs both count from zero or both count from nonzero then the
01510       // narrower is likely a dead phi that has been widened. Use the wider phi
01511       // to allow the other to be eliminated.
01512       else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
01513         continue;
01514     }
01515     BestPhi = Phi;
01516     BestInit = Init;
01517   }
01518   return BestPhi;
01519 }
01520 
01521 /// genLoopLimit - Help LinearFunctionTestReplace by generating a value that
01522 /// holds the RHS of the new loop test.
01523 static Value *genLoopLimit(PHINode *IndVar, const SCEV *IVCount, Loop *L,
01524                            SCEVExpander &Rewriter, ScalarEvolution *SE) {
01525   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
01526   assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter");
01527   const SCEV *IVInit = AR->getStart();
01528 
01529   // IVInit may be a pointer while IVCount is an integer when FindLoopCounter
01530   // finds a valid pointer IV. Sign extend BECount in order to materialize a
01531   // GEP. Avoid running SCEVExpander on a new pointer value, instead reusing
01532   // the existing GEPs whenever possible.
01533   if (IndVar->getType()->isPointerTy()
01534       && !IVCount->getType()->isPointerTy()) {
01535 
01536     // IVOffset will be the new GEP offset that is interpreted by GEP as a
01537     // signed value. IVCount on the other hand represents the loop trip count,
01538     // which is an unsigned value. FindLoopCounter only allows induction
01539     // variables that have a positive unit stride of one. This means we don't
01540     // have to handle the case of negative offsets (yet) and just need to zero
01541     // extend IVCount.
01542     Type *OfsTy = SE->getEffectiveSCEVType(IVInit->getType());
01543     const SCEV *IVOffset = SE->getTruncateOrZeroExtend(IVCount, OfsTy);
01544 
01545     // Expand the code for the iteration count.
01546     assert(SE->isLoopInvariant(IVOffset, L) &&
01547            "Computed iteration count is not loop invariant!");
01548     BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
01549     Value *GEPOffset = Rewriter.expandCodeFor(IVOffset, OfsTy, BI);
01550 
01551     Value *GEPBase = IndVar->getIncomingValueForBlock(L->getLoopPreheader());
01552     assert(AR->getStart() == SE->getSCEV(GEPBase) && "bad loop counter");
01553     // We could handle pointer IVs other than i8*, but we need to compensate for
01554     // gep index scaling. See canExpandBackedgeTakenCount comments.
01555     assert(SE->getSizeOfExpr(IntegerType::getInt64Ty(IndVar->getContext()),
01556              cast<PointerType>(GEPBase->getType())->getElementType())->isOne()
01557            && "unit stride pointer IV must be i8*");
01558 
01559     IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
01560     return Builder.CreateGEP(GEPBase, GEPOffset, "lftr.limit");
01561   }
01562   else {
01563     // In any other case, convert both IVInit and IVCount to integers before
01564     // comparing. This may result in SCEV expension of pointers, but in practice
01565     // SCEV will fold the pointer arithmetic away as such:
01566     // BECount = (IVEnd - IVInit - 1) => IVLimit = IVInit (postinc).
01567     //
01568     // Valid Cases: (1) both integers is most common; (2) both may be pointers
01569     // for simple memset-style loops.
01570     //
01571     // IVInit integer and IVCount pointer would only occur if a canonical IV
01572     // were generated on top of case #2, which is not expected.
01573 
01574     const SCEV *IVLimit = 0;
01575     // For unit stride, IVCount = Start + BECount with 2's complement overflow.
01576     // For non-zero Start, compute IVCount here.
01577     if (AR->getStart()->isZero())
01578       IVLimit = IVCount;
01579     else {
01580       assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
01581       const SCEV *IVInit = AR->getStart();
01582 
01583       // For integer IVs, truncate the IV before computing IVInit + BECount.
01584       if (SE->getTypeSizeInBits(IVInit->getType())
01585           > SE->getTypeSizeInBits(IVCount->getType()))
01586         IVInit = SE->getTruncateExpr(IVInit, IVCount->getType());
01587 
01588       IVLimit = SE->getAddExpr(IVInit, IVCount);
01589     }
01590     // Expand the code for the iteration count.
01591     BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
01592     IRBuilder<> Builder(BI);
01593     assert(SE->isLoopInvariant(IVLimit, L) &&
01594            "Computed iteration count is not loop invariant!");
01595     // Ensure that we generate the same type as IndVar, or a smaller integer
01596     // type. In the presence of null pointer values, we have an integer type
01597     // SCEV expression (IVInit) for a pointer type IV value (IndVar).
01598     Type *LimitTy = IVCount->getType()->isPointerTy() ?
01599       IndVar->getType() : IVCount->getType();
01600     return Rewriter.expandCodeFor(IVLimit, LimitTy, BI);
01601   }
01602 }
01603 
01604 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
01605 /// loop to be a canonical != comparison against the incremented loop induction
01606 /// variable.  This pass is able to rewrite the exit tests of any loop where the
01607 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
01608 /// is actually a much broader range than just linear tests.
01609 Value *IndVarSimplify::
01610 LinearFunctionTestReplace(Loop *L,
01611                           const SCEV *BackedgeTakenCount,
01612                           PHINode *IndVar,
01613                           SCEVExpander &Rewriter) {
01614   assert(canExpandBackedgeTakenCount(L, SE) && "precondition");
01615 
01616   // Initialize CmpIndVar and IVCount to their preincremented values.
01617   Value *CmpIndVar = IndVar;
01618   const SCEV *IVCount = BackedgeTakenCount;
01619 
01620   // If the exiting block is the same as the backedge block, we prefer to
01621   // compare against the post-incremented value, otherwise we must compare
01622   // against the preincremented value.
01623   if (L->getExitingBlock() == L->getLoopLatch()) {
01624     // Add one to the "backedge-taken" count to get the trip count.
01625     // This addition may overflow, which is valid as long as the comparison is
01626     // truncated to BackedgeTakenCount->getType().
01627     IVCount = SE->getAddExpr(BackedgeTakenCount,
01628                              SE->getConstant(BackedgeTakenCount->getType(), 1));
01629     // The BackedgeTaken expression contains the number of times that the
01630     // backedge branches to the loop header.  This is one less than the
01631     // number of times the loop executes, so use the incremented indvar.
01632     CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
01633   }
01634 
01635   Value *ExitCnt = genLoopLimit(IndVar, IVCount, L, Rewriter, SE);
01636   assert(ExitCnt->getType()->isPointerTy() == IndVar->getType()->isPointerTy()
01637          && "genLoopLimit missed a cast");
01638 
01639   // Insert a new icmp_ne or icmp_eq instruction before the branch.
01640   BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
01641   ICmpInst::Predicate P;
01642   if (L->contains(BI->getSuccessor(0)))
01643     P = ICmpInst::ICMP_NE;
01644   else
01645     P = ICmpInst::ICMP_EQ;
01646 
01647   DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
01648                << "      LHS:" << *CmpIndVar << '\n'
01649                << "       op:\t"
01650                << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
01651                << "      RHS:\t" << *ExitCnt << "\n"
01652                << "  IVCount:\t" << *IVCount << "\n");
01653 
01654   IRBuilder<> Builder(BI);
01655 
01656   // LFTR can ignore IV overflow and truncate to the width of
01657   // BECount. This avoids materializing the add(zext(add)) expression.
01658   unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->getType());
01659   unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->getType());
01660   if (CmpIndVarSize > ExitCntSize) {
01661     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
01662     const SCEV *ARStart = AR->getStart();
01663     const SCEV *ARStep = AR->getStepRecurrence(*SE);
01664     // For constant IVCount, avoid truncation.
01665     if (isa<SCEVConstant>(ARStart) && isa<SCEVConstant>(IVCount)) {
01666       const APInt &Start = cast<SCEVConstant>(ARStart)->getValue()->getValue();
01667       APInt Count = cast<SCEVConstant>(IVCount)->getValue()->getValue();
01668       // Note that the post-inc value of BackedgeTakenCount may have overflowed
01669       // above such that IVCount is now zero.
01670       if (IVCount != BackedgeTakenCount && Count == 0) {
01671         Count = APInt::getMaxValue(Count.getBitWidth()).zext(CmpIndVarSize);
01672         ++Count;
01673       }
01674       else
01675         Count = Count.zext(CmpIndVarSize);
01676       APInt NewLimit;
01677       if (cast<SCEVConstant>(ARStep)->getValue()->isNegative())
01678         NewLimit = Start - Count;
01679       else
01680         NewLimit = Start + Count;
01681       ExitCnt = ConstantInt::get(CmpIndVar->getType(), NewLimit);
01682 
01683       DEBUG(dbgs() << "  Widen RHS:\t" << *ExitCnt << "\n");
01684     } else {
01685       CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(),
01686                                       "lftr.wideiv");
01687     }
01688   }
01689   Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
01690   Value *OrigCond = BI->getCondition();
01691   // It's tempting to use replaceAllUsesWith here to fully replace the old
01692   // comparison, but that's not immediately safe, since users of the old
01693   // comparison may not be dominated by the new comparison. Instead, just
01694   // update the branch to use the new comparison; in the common case this
01695   // will make old comparison dead.
01696   BI->setCondition(Cond);
01697   DeadInsts.push_back(OrigCond);
01698 
01699   ++NumLFTR;
01700   Changed = true;
01701   return Cond;
01702 }
01703 
01704 //===----------------------------------------------------------------------===//
01705 //  SinkUnusedInvariants. A late subpass to cleanup loop preheaders.
01706 //===----------------------------------------------------------------------===//
01707 
01708 /// If there's a single exit block, sink any loop-invariant values that
01709 /// were defined in the preheader but not used inside the loop into the
01710 /// exit block to reduce register pressure in the loop.
01711 void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
01712   BasicBlock *ExitBlock = L->getExitBlock();
01713   if (!ExitBlock) return;
01714 
01715   BasicBlock *Preheader = L->getLoopPreheader();
01716   if (!Preheader) return;
01717 
01718   Instruction *InsertPt = ExitBlock->getFirstInsertionPt();
01719   BasicBlock::iterator I = Preheader->getTerminator();
01720   while (I != Preheader->begin()) {
01721     --I;
01722     // New instructions were inserted at the end of the preheader.
01723     if (isa<PHINode>(I))
01724       break;
01725 
01726     // Don't move instructions which might have side effects, since the side
01727     // effects need to complete before instructions inside the loop.  Also don't
01728     // move instructions which might read memory, since the loop may modify
01729     // memory. Note that it's okay if the instruction might have undefined
01730     // behavior: LoopSimplify guarantees that the preheader dominates the exit
01731     // block.
01732     if (I->mayHaveSideEffects() || I->mayReadFromMemory())
01733       continue;
01734 
01735     // Skip debug info intrinsics.
01736     if (isa<DbgInfoIntrinsic>(I))
01737       continue;
01738 
01739     // Skip landingpad instructions.
01740     if (isa<LandingPadInst>(I))
01741       continue;
01742 
01743     // Don't sink alloca: we never want to sink static alloca's out of the
01744     // entry block, and correctly sinking dynamic alloca's requires
01745     // checks for stacksave/stackrestore intrinsics.
01746     // FIXME: Refactor this check somehow?
01747     if (isa<AllocaInst>(I))
01748       continue;
01749 
01750     // Determine if there is a use in or before the loop (direct or
01751     // otherwise).
01752     bool UsedInLoop = false;
01753     for (Use &U : I->uses()) {
01754       Instruction *User = cast<Instruction>(U.getUser());
01755       BasicBlock *UseBB = User->getParent();
01756       if (PHINode *P = dyn_cast<PHINode>(User)) {
01757         unsigned i =
01758           PHINode::getIncomingValueNumForOperand(U.getOperandNo());
01759         UseBB = P->getIncomingBlock(i);
01760       }
01761       if (UseBB == Preheader || L->contains(UseBB)) {
01762         UsedInLoop = true;
01763         break;
01764       }
01765     }
01766 
01767     // If there is, the def must remain in the preheader.
01768     if (UsedInLoop)
01769       continue;
01770 
01771     // Otherwise, sink it to the exit block.
01772     Instruction *ToMove = I;
01773     bool Done = false;
01774 
01775     if (I != Preheader->begin()) {
01776       // Skip debug info intrinsics.
01777       do {
01778         --I;
01779       } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
01780 
01781       if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
01782         Done = true;
01783     } else {
01784       Done = true;
01785     }
01786 
01787     ToMove->moveBefore(InsertPt);
01788     if (Done) break;
01789     InsertPt = ToMove;
01790   }
01791 }
01792 
01793 //===----------------------------------------------------------------------===//
01794 //  IndVarSimplify driver. Manage several subpasses of IV simplification.
01795 //===----------------------------------------------------------------------===//
01796 
01797 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
01798   if (skipOptnoneFunction(L))
01799     return false;
01800 
01801   // If LoopSimplify form is not available, stay out of trouble. Some notes:
01802   //  - LSR currently only supports LoopSimplify-form loops. Indvars'
01803   //    canonicalization can be a pessimization without LSR to "clean up"
01804   //    afterwards.
01805   //  - We depend on having a preheader; in particular,
01806   //    Loop::getCanonicalInductionVariable only supports loops with preheaders,
01807   //    and we're in trouble if we can't find the induction variable even when
01808   //    we've manually inserted one.
01809   if (!L->isLoopSimplifyForm())
01810     return false;
01811 
01812   LI = &getAnalysis<LoopInfo>();
01813   SE = &getAnalysis<ScalarEvolution>();
01814   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
01815   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
01816   DL = DLP ? &DLP->getDataLayout() : 0;
01817   TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
01818 
01819   DeadInsts.clear();
01820   Changed = false;
01821 
01822   // If there are any floating-point recurrences, attempt to
01823   // transform them to use integer recurrences.
01824   RewriteNonIntegerIVs(L);
01825 
01826   const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
01827 
01828   // Create a rewriter object which we'll use to transform the code with.
01829   SCEVExpander Rewriter(*SE, "indvars");
01830 #ifndef NDEBUG
01831   Rewriter.setDebugType(DEBUG_TYPE);
01832 #endif
01833 
01834   // Eliminate redundant IV users.
01835   //
01836   // Simplification works best when run before other consumers of SCEV. We
01837   // attempt to avoid evaluating SCEVs for sign/zero extend operations until
01838   // other expressions involving loop IVs have been evaluated. This helps SCEV
01839   // set no-wrap flags before normalizing sign/zero extension.
01840   Rewriter.disableCanonicalMode();
01841   SimplifyAndExtend(L, Rewriter, LPM);
01842 
01843   // Check to see if this loop has a computable loop-invariant execution count.
01844   // If so, this means that we can compute the final value of any expressions
01845   // that are recurrent in the loop, and substitute the exit values from the
01846   // loop into any instructions outside of the loop that use the final values of
01847   // the current expressions.
01848   //
01849   if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
01850     RewriteLoopExitValues(L, Rewriter);
01851 
01852   // Eliminate redundant IV cycles.
01853   NumElimIV += Rewriter.replaceCongruentIVs(L, DT, DeadInsts);
01854 
01855   // If we have a trip count expression, rewrite the loop's exit condition
01856   // using it.  We can currently only handle loops with a single exit.
01857   if (canExpandBackedgeTakenCount(L, SE) && needsLFTR(L, DT)) {
01858     PHINode *IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT, DL);
01859     if (IndVar) {
01860       // Check preconditions for proper SCEVExpander operation. SCEV does not
01861       // express SCEVExpander's dependencies, such as LoopSimplify. Instead any
01862       // pass that uses the SCEVExpander must do it. This does not work well for
01863       // loop passes because SCEVExpander makes assumptions about all loops,
01864       // while LoopPassManager only forces the current loop to be simplified.
01865       //
01866       // FIXME: SCEV expansion has no way to bail out, so the caller must
01867       // explicitly check any assumptions made by SCEV. Brittle.
01868       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount);
01869       if (!AR || AR->getLoop()->getLoopPreheader())
01870         (void)LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
01871                                         Rewriter);
01872     }
01873   }
01874   // Clear the rewriter cache, because values that are in the rewriter's cache
01875   // can be deleted in the loop below, causing the AssertingVH in the cache to
01876   // trigger.
01877   Rewriter.clear();
01878 
01879   // Now that we're done iterating through lists, clean up any instructions
01880   // which are now dead.
01881   while (!DeadInsts.empty())
01882     if (Instruction *Inst =
01883           dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
01884       RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
01885 
01886   // The Rewriter may not be used from this point on.
01887 
01888   // Loop-invariant instructions in the preheader that aren't used in the
01889   // loop may be sunk below the loop to reduce register pressure.
01890   SinkUnusedInvariants(L);
01891 
01892   // Clean up dead instructions.
01893   Changed |= DeleteDeadPHIs(L->getHeader(), TLI);
01894   // Check a post-condition.
01895   assert(L->isLCSSAForm(*DT) &&
01896          "Indvars did not leave the loop in lcssa form!");
01897 
01898   // Verify that LFTR, and any other change have not interfered with SCEV's
01899   // ability to compute trip count.
01900 #ifndef NDEBUG
01901   if (VerifyIndvars && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
01902     SE->forgetLoop(L);
01903     const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
01904     if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
01905         SE->getTypeSizeInBits(NewBECount->getType()))
01906       NewBECount = SE->getTruncateOrNoop(NewBECount,
01907                                          BackedgeTakenCount->getType());
01908     else
01909       BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
01910                                                  NewBECount->getType());
01911     assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV");
01912   }
01913 #endif
01914 
01915   return Changed;
01916 }