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