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