LLVM API Documentation

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