IndVarSimplify.cpp 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112
  1. //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This transformation analyzes and transforms the induction variables (and
  11. // computations derived from them) into simpler forms suitable for subsequent
  12. // analysis and transformation.
  13. //
  14. // If the trip count of a loop is computable, this pass also makes the following
  15. // changes:
  16. // 1. The exit condition for the loop is canonicalized to compare the
  17. // induction value against the exit value. This turns loops like:
  18. // 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
  19. // 2. Any use outside of the loop of an expression derived from the indvar
  20. // is changed to compute the derived value outside of the loop, eliminating
  21. // the dependence on the exit value of the induction variable. If the only
  22. // purpose of the loop is to compute the exit value of some derived
  23. // expression, this transformation will make the loop dead.
  24. //
  25. //===----------------------------------------------------------------------===//
  26. #include "llvm/Transforms/Scalar.h"
  27. #include "llvm/ADT/DenseMap.h"
  28. #include "llvm/ADT/SmallVector.h"
  29. #include "llvm/ADT/Statistic.h"
  30. #include "llvm/Analysis/LoopInfo.h"
  31. #include "llvm/Analysis/LoopPass.h"
  32. #include "llvm/Analysis/ScalarEvolutionExpander.h"
  33. #include "llvm/Analysis/TargetLibraryInfo.h"
  34. #include "llvm/Analysis/TargetTransformInfo.h"
  35. #include "llvm/IR/BasicBlock.h"
  36. #include "llvm/IR/CFG.h"
  37. #include "llvm/IR/Constants.h"
  38. #include "llvm/IR/DataLayout.h"
  39. #include "llvm/IR/Dominators.h"
  40. #include "llvm/IR/Instructions.h"
  41. #include "llvm/IR/IntrinsicInst.h"
  42. #include "llvm/IR/LLVMContext.h"
  43. #include "llvm/IR/PatternMatch.h"
  44. #include "llvm/IR/Type.h"
  45. #include "llvm/Support/CommandLine.h"
  46. #include "llvm/Support/Debug.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  49. #include "llvm/Transforms/Utils/Local.h"
  50. #include "llvm/Transforms/Utils/SimplifyIndVar.h"
  51. using namespace llvm;
  52. #define DEBUG_TYPE "indvars"
  53. STATISTIC(NumWidened , "Number of indvars widened");
  54. STATISTIC(NumReplaced , "Number of exit values replaced");
  55. STATISTIC(NumLFTR , "Number of loop exit tests replaced");
  56. STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated");
  57. STATISTIC(NumElimIV , "Number of congruent IVs eliminated");
  58. #if 0 // HLSL Change Starts - option pending
  59. // Trip count verification can be enabled by default under NDEBUG if we
  60. // implement a strong expression equivalence checker in SCEV. Until then, we
  61. // use the verify-indvars flag, which may assert in some cases.
  62. static cl::opt<bool> VerifyIndvars(
  63. "verify-indvars", cl::Hidden,
  64. cl::desc("Verify the ScalarEvolution result after running indvars"));
  65. static cl::opt<bool> ReduceLiveIVs("liv-reduce", cl::Hidden,
  66. cl::desc("Reduce live induction variables."));
  67. enum ReplaceExitVal { NeverRepl, OnlyCheapRepl, AlwaysRepl };
  68. static cl::opt<ReplaceExitVal> ReplaceExitValue(
  69. "replexitval", cl::Hidden, cl::init(OnlyCheapRepl),
  70. cl::desc("Choose the strategy to replace exit value in IndVarSimplify"),
  71. cl::values(clEnumValN(NeverRepl, "never", "never replace exit value"),
  72. clEnumValN(OnlyCheapRepl, "cheap",
  73. "only replace exit value when the cost is cheap"),
  74. clEnumValN(AlwaysRepl, "always",
  75. "always replace exit value whenever possible"),
  76. clEnumValEnd));
  77. #else
  78. static const bool ReduceLiveIVs = false;
  79. enum ReplaceExitVal { NeverRepl, OnlyCheapRepl, AlwaysRepl };
  80. static const ReplaceExitVal ReplaceExitValue = OnlyCheapRepl;
  81. #endif // HLSL Change Ends - option pending
  82. namespace {
  83. struct RewritePhi;
  84. }
  85. namespace {
  86. class IndVarSimplify : public LoopPass {
  87. LoopInfo *LI;
  88. ScalarEvolution *SE;
  89. DominatorTree *DT;
  90. TargetLibraryInfo *TLI;
  91. const TargetTransformInfo *TTI;
  92. SmallVector<WeakVH, 16> DeadInsts;
  93. bool Changed;
  94. public:
  95. static char ID; // Pass identification, replacement for typeid
  96. IndVarSimplify()
  97. : LoopPass(ID), LI(nullptr), SE(nullptr), DT(nullptr), Changed(false) {
  98. initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
  99. }
  100. bool runOnLoop(Loop *L, LPPassManager &LPM) override;
  101. void getAnalysisUsage(AnalysisUsage &AU) const override {
  102. AU.addRequired<DominatorTreeWrapperPass>();
  103. AU.addRequired<LoopInfoWrapperPass>();
  104. AU.addRequired<ScalarEvolution>();
  105. AU.addRequiredID(LoopSimplifyID);
  106. AU.addRequiredID(LCSSAID);
  107. AU.addPreserved<ScalarEvolution>();
  108. AU.addPreservedID(LoopSimplifyID);
  109. AU.addPreservedID(LCSSAID);
  110. AU.setPreservesCFG();
  111. }
  112. private:
  113. void releaseMemory() override {
  114. DeadInsts.clear();
  115. }
  116. bool isValidRewrite(Value *FromVal, Value *ToVal);
  117. void HandleFloatingPointIV(Loop *L, PHINode *PH);
  118. void RewriteNonIntegerIVs(Loop *L);
  119. void SimplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LPPassManager &LPM);
  120. bool CanLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet);
  121. void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
  122. Value *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
  123. PHINode *IndVar, SCEVExpander &Rewriter);
  124. void SinkUnusedInvariants(Loop *L);
  125. Value *ExpandSCEVIfNeeded(SCEVExpander &Rewriter, const SCEV *S, Loop *L,
  126. Instruction *InsertPt, Type *Ty,
  127. bool &IsHighCostExpansion);
  128. };
  129. }
  130. char IndVarSimplify::ID = 0;
  131. INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
  132. "Induction Variable Simplification", false, false)
  133. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  134. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  135. INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
  136. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  137. INITIALIZE_PASS_DEPENDENCY(LCSSA)
  138. INITIALIZE_PASS_END(IndVarSimplify, "indvars",
  139. "Induction Variable Simplification", false, false)
  140. Pass *llvm::createIndVarSimplifyPass() {
  141. return new IndVarSimplify();
  142. }
  143. /// isValidRewrite - Return true if the SCEV expansion generated by the
  144. /// rewriter can replace the original value. SCEV guarantees that it
  145. /// produces the same value, but the way it is produced may be illegal IR.
  146. /// Ideally, this function will only be called for verification.
  147. bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
  148. // If an SCEV expression subsumed multiple pointers, its expansion could
  149. // reassociate the GEP changing the base pointer. This is illegal because the
  150. // final address produced by a GEP chain must be inbounds relative to its
  151. // underlying object. Otherwise basic alias analysis, among other things,
  152. // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
  153. // producing an expression involving multiple pointers. Until then, we must
  154. // bail out here.
  155. //
  156. // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
  157. // because it understands lcssa phis while SCEV does not.
  158. Value *FromPtr = FromVal;
  159. Value *ToPtr = ToVal;
  160. if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
  161. FromPtr = GEP->getPointerOperand();
  162. }
  163. if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
  164. ToPtr = GEP->getPointerOperand();
  165. }
  166. if (FromPtr != FromVal || ToPtr != ToVal) {
  167. // Quickly check the common case
  168. if (FromPtr == ToPtr)
  169. return true;
  170. // SCEV may have rewritten an expression that produces the GEP's pointer
  171. // operand. That's ok as long as the pointer operand has the same base
  172. // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
  173. // base of a recurrence. This handles the case in which SCEV expansion
  174. // converts a pointer type recurrence into a nonrecurrent pointer base
  175. // indexed by an integer recurrence.
  176. // If the GEP base pointer is a vector of pointers, abort.
  177. if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy())
  178. return false;
  179. const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
  180. const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
  181. if (FromBase == ToBase)
  182. return true;
  183. DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
  184. << *FromBase << " != " << *ToBase << "\n");
  185. return false;
  186. }
  187. return true;
  188. }
  189. /// Determine the insertion point for this user. By default, insert immediately
  190. /// before the user. SCEVExpander or LICM will hoist loop invariants out of the
  191. /// loop. For PHI nodes, there may be multiple uses, so compute the nearest
  192. /// common dominator for the incoming blocks.
  193. static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
  194. DominatorTree *DT) {
  195. PHINode *PHI = dyn_cast<PHINode>(User);
  196. if (!PHI)
  197. return User;
  198. Instruction *InsertPt = nullptr;
  199. for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
  200. if (PHI->getIncomingValue(i) != Def)
  201. continue;
  202. BasicBlock *InsertBB = PHI->getIncomingBlock(i);
  203. if (!InsertPt) {
  204. InsertPt = InsertBB->getTerminator();
  205. continue;
  206. }
  207. InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
  208. InsertPt = InsertBB->getTerminator();
  209. }
  210. assert(InsertPt && "Missing phi operand");
  211. assert((!isa<Instruction>(Def) ||
  212. DT->dominates(cast<Instruction>(Def), InsertPt)) &&
  213. "def does not dominate all uses");
  214. return InsertPt;
  215. }
  216. //===----------------------------------------------------------------------===//
  217. // RewriteNonIntegerIVs and helpers. Prefer integer IVs.
  218. //===----------------------------------------------------------------------===//
  219. /// ConvertToSInt - Convert APF to an integer, if possible.
  220. static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
  221. bool isExact = false;
  222. // See if we can convert this to an int64_t
  223. uint64_t UIntVal;
  224. if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
  225. &isExact) != APFloat::opOK || !isExact)
  226. return false;
  227. IntVal = UIntVal;
  228. return true;
  229. }
  230. /// HandleFloatingPointIV - If the loop has floating induction variable
  231. /// then insert corresponding integer induction variable if possible.
  232. /// For example,
  233. /// for(double i = 0; i < 10000; ++i)
  234. /// bar(i)
  235. /// is converted into
  236. /// for(int i = 0; i < 10000; ++i)
  237. /// bar((double)i);
  238. ///
  239. void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
  240. unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
  241. unsigned BackEdge = IncomingEdge^1;
  242. // Check incoming value.
  243. ConstantFP *InitValueVal =
  244. dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
  245. int64_t InitValue;
  246. if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
  247. return;
  248. // Check IV increment. Reject this PN if increment operation is not
  249. // an add or increment value can not be represented by an integer.
  250. BinaryOperator *Incr =
  251. dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
  252. if (Incr == nullptr || Incr->getOpcode() != Instruction::FAdd) return;
  253. // If this is not an add of the PHI with a constantfp, or if the constant fp
  254. // is not an integer, bail out.
  255. ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
  256. int64_t IncValue;
  257. if (IncValueVal == nullptr || Incr->getOperand(0) != PN ||
  258. !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
  259. return;
  260. // Check Incr uses. One user is PN and the other user is an exit condition
  261. // used by the conditional terminator.
  262. Value::user_iterator IncrUse = Incr->user_begin();
  263. Instruction *U1 = cast<Instruction>(*IncrUse++);
  264. if (IncrUse == Incr->user_end()) return;
  265. Instruction *U2 = cast<Instruction>(*IncrUse++);
  266. if (IncrUse != Incr->user_end()) return;
  267. // Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
  268. // only used by a branch, we can't transform it.
  269. FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
  270. if (!Compare)
  271. Compare = dyn_cast<FCmpInst>(U2);
  272. if (!Compare || !Compare->hasOneUse() ||
  273. !isa<BranchInst>(Compare->user_back()))
  274. return;
  275. BranchInst *TheBr = cast<BranchInst>(Compare->user_back());
  276. // We need to verify that the branch actually controls the iteration count
  277. // of the loop. If not, the new IV can overflow and no one will notice.
  278. // The branch block must be in the loop and one of the successors must be out
  279. // of the loop.
  280. assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
  281. if (!L->contains(TheBr->getParent()) ||
  282. (L->contains(TheBr->getSuccessor(0)) &&
  283. L->contains(TheBr->getSuccessor(1))))
  284. return;
  285. // If it isn't a comparison with an integer-as-fp (the exit value), we can't
  286. // transform it.
  287. ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
  288. int64_t ExitValue;
  289. if (ExitValueVal == nullptr ||
  290. !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
  291. return;
  292. // Find new predicate for integer comparison.
  293. CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
  294. switch (Compare->getPredicate()) {
  295. default: return; // Unknown comparison.
  296. case CmpInst::FCMP_OEQ:
  297. case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
  298. case CmpInst::FCMP_ONE:
  299. case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
  300. case CmpInst::FCMP_OGT:
  301. case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
  302. case CmpInst::FCMP_OGE:
  303. case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
  304. case CmpInst::FCMP_OLT:
  305. case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
  306. case CmpInst::FCMP_OLE:
  307. case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
  308. }
  309. // We convert the floating point induction variable to a signed i32 value if
  310. // we can. This is only safe if the comparison will not overflow in a way
  311. // that won't be trapped by the integer equivalent operations. Check for this
  312. // now.
  313. // TODO: We could use i64 if it is native and the range requires it.
  314. // The start/stride/exit values must all fit in signed i32.
  315. if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
  316. return;
  317. // If not actually striding (add x, 0.0), avoid touching the code.
  318. if (IncValue == 0)
  319. return;
  320. // Positive and negative strides have different safety conditions.
  321. if (IncValue > 0) {
  322. // If we have a positive stride, we require the init to be less than the
  323. // exit value.
  324. if (InitValue >= ExitValue)
  325. return;
  326. uint32_t Range = uint32_t(ExitValue-InitValue);
  327. // Check for infinite loop, either:
  328. // while (i <= Exit) or until (i > Exit)
  329. if (NewPred == CmpInst::ICMP_SLE || NewPred == CmpInst::ICMP_SGT) {
  330. if (++Range == 0) return; // Range overflows.
  331. }
  332. unsigned Leftover = Range % uint32_t(IncValue);
  333. // If this is an equality comparison, we require that the strided value
  334. // exactly land on the exit value, otherwise the IV condition will wrap
  335. // around and do things the fp IV wouldn't.
  336. if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
  337. Leftover != 0)
  338. return;
  339. // If the stride would wrap around the i32 before exiting, we can't
  340. // transform the IV.
  341. if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
  342. return;
  343. } else {
  344. // If we have a negative stride, we require the init to be greater than the
  345. // exit value.
  346. if (InitValue <= ExitValue)
  347. return;
  348. uint32_t Range = uint32_t(InitValue-ExitValue);
  349. // Check for infinite loop, either:
  350. // while (i >= Exit) or until (i < Exit)
  351. if (NewPred == CmpInst::ICMP_SGE || NewPred == CmpInst::ICMP_SLT) {
  352. if (++Range == 0) return; // Range overflows.
  353. }
  354. unsigned Leftover = Range % uint32_t(-IncValue);
  355. // If this is an equality comparison, we require that the strided value
  356. // exactly land on the exit value, otherwise the IV condition will wrap
  357. // around and do things the fp IV wouldn't.
  358. if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
  359. Leftover != 0)
  360. return;
  361. // If the stride would wrap around the i32 before exiting, we can't
  362. // transform the IV.
  363. if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
  364. return;
  365. }
  366. IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
  367. // Insert new integer induction variable.
  368. PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
  369. NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
  370. PN->getIncomingBlock(IncomingEdge));
  371. Value *NewAdd =
  372. BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
  373. Incr->getName()+".int", Incr);
  374. NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
  375. ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
  376. ConstantInt::get(Int32Ty, ExitValue),
  377. Compare->getName());
  378. // In the following deletions, PN may become dead and may be deleted.
  379. // Use a WeakVH to observe whether this happens.
  380. WeakVH WeakPH = PN;
  381. // Delete the old floating point exit comparison. The branch starts using the
  382. // new comparison.
  383. NewCompare->takeName(Compare);
  384. Compare->replaceAllUsesWith(NewCompare);
  385. RecursivelyDeleteTriviallyDeadInstructions(Compare, TLI);
  386. // Delete the old floating point increment.
  387. Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
  388. RecursivelyDeleteTriviallyDeadInstructions(Incr, TLI);
  389. // If the FP induction variable still has uses, this is because something else
  390. // in the loop uses its value. In order to canonicalize the induction
  391. // variable, we chose to eliminate the IV and rewrite it in terms of an
  392. // int->fp cast.
  393. //
  394. // We give preference to sitofp over uitofp because it is faster on most
  395. // platforms.
  396. if (WeakPH) {
  397. Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
  398. PN->getParent()->getFirstInsertionPt());
  399. PN->replaceAllUsesWith(Conv);
  400. RecursivelyDeleteTriviallyDeadInstructions(PN, TLI);
  401. }
  402. Changed = true;
  403. }
  404. void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
  405. // First step. Check to see if there are any floating-point recurrences.
  406. // If there are, change them into integer recurrences, permitting analysis by
  407. // the SCEV routines.
  408. //
  409. BasicBlock *Header = L->getHeader();
  410. SmallVector<WeakVH, 8> PHIs;
  411. for (BasicBlock::iterator I = Header->begin();
  412. PHINode *PN = dyn_cast<PHINode>(I); ++I)
  413. PHIs.push_back(PN);
  414. for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
  415. if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
  416. HandleFloatingPointIV(L, PN);
  417. // If the loop previously had floating-point IV, ScalarEvolution
  418. // may not have been able to compute a trip count. Now that we've done some
  419. // re-writing, the trip count may be computable.
  420. if (Changed)
  421. SE->forgetLoop(L);
  422. }
  423. namespace {
  424. // Collect information about PHI nodes which can be transformed in
  425. // RewriteLoopExitValues.
  426. struct RewritePhi {
  427. PHINode *PN;
  428. unsigned Ith; // Ith incoming value.
  429. Value *Val; // Exit value after expansion.
  430. bool HighCost; // High Cost when expansion.
  431. bool SafePhi; // LCSSASafePhiForRAUW.
  432. RewritePhi(PHINode *P, unsigned I, Value *V, bool H, bool S)
  433. : PN(P), Ith(I), Val(V), HighCost(H), SafePhi(S) {}
  434. };
  435. }
  436. Value *IndVarSimplify::ExpandSCEVIfNeeded(SCEVExpander &Rewriter, const SCEV *S,
  437. Loop *L, Instruction *InsertPt,
  438. Type *ResultTy,
  439. bool &IsHighCostExpansion) {
  440. using namespace llvm::PatternMatch;
  441. if (!Rewriter.isHighCostExpansion(S, L)) {
  442. IsHighCostExpansion = false;
  443. return Rewriter.expandCodeFor(S, ResultTy, InsertPt);
  444. }
  445. // Before expanding S into an expensive LLVM expression, see if we can use an
  446. // already existing value as the expansion for S. There is potential to make
  447. // this significantly smarter, but this simple heuristic already gets some
  448. // interesting cases.
  449. SmallVector<BasicBlock *, 4> Latches;
  450. L->getLoopLatches(Latches);
  451. for (BasicBlock *BB : Latches) {
  452. ICmpInst::Predicate Pred;
  453. Instruction *LHS, *RHS;
  454. BasicBlock *TrueBB, *FalseBB;
  455. if (!match(BB->getTerminator(),
  456. m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
  457. TrueBB, FalseBB)))
  458. continue;
  459. if (SE->getSCEV(LHS) == S && DT->dominates(LHS, InsertPt)) {
  460. IsHighCostExpansion = false;
  461. return LHS;
  462. }
  463. if (SE->getSCEV(RHS) == S && DT->dominates(RHS, InsertPt)) {
  464. IsHighCostExpansion = false;
  465. return RHS;
  466. }
  467. }
  468. // We didn't find anything, fall back to using SCEVExpander.
  469. assert(Rewriter.isHighCostExpansion(S, L) && "this should not have changed!");
  470. IsHighCostExpansion = true;
  471. return Rewriter.expandCodeFor(S, ResultTy, InsertPt);
  472. }
  473. //===----------------------------------------------------------------------===//
  474. // RewriteLoopExitValues - Optimize IV users outside the loop.
  475. // As a side effect, reduces the amount of IV processing within the loop.
  476. //===----------------------------------------------------------------------===//
  477. /// RewriteLoopExitValues - Check to see if this loop has a computable
  478. /// loop-invariant execution count. If so, this means that we can compute the
  479. /// final value of any expressions that are recurrent in the loop, and
  480. /// substitute the exit values from the loop into any instructions outside of
  481. /// the loop that use the final values of the current expressions.
  482. ///
  483. /// This is mostly redundant with the regular IndVarSimplify activities that
  484. /// happen later, except that it's more powerful in some cases, because it's
  485. /// able to brute-force evaluate arbitrary instructions as long as they have
  486. /// constant operands at the beginning of the loop.
  487. void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
  488. // Verify the input to the pass in already in LCSSA form.
  489. assert(L->isLCSSAForm(*DT));
  490. SmallVector<BasicBlock*, 8> ExitBlocks;
  491. L->getUniqueExitBlocks(ExitBlocks);
  492. SmallVector<RewritePhi, 8> RewritePhiSet;
  493. // Find all values that are computed inside the loop, but used outside of it.
  494. // Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
  495. // the exit blocks of the loop to find them.
  496. for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
  497. BasicBlock *ExitBB = ExitBlocks[i];
  498. // If there are no PHI nodes in this exit block, then no values defined
  499. // inside the loop are used on this path, skip it.
  500. PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
  501. if (!PN) continue;
  502. unsigned NumPreds = PN->getNumIncomingValues();
  503. // We would like to be able to RAUW single-incoming value PHI nodes. We
  504. // have to be certain this is safe even when this is an LCSSA PHI node.
  505. // While the computed exit value is no longer varying in *this* loop, the
  506. // exit block may be an exit block for an outer containing loop as well,
  507. // the exit value may be varying in the outer loop, and thus it may still
  508. // require an LCSSA PHI node. The safe case is when this is
  509. // single-predecessor PHI node (LCSSA) and the exit block containing it is
  510. // part of the enclosing loop, or this is the outer most loop of the nest.
  511. // In either case the exit value could (at most) be varying in the same
  512. // loop body as the phi node itself. Thus if it is in turn used outside of
  513. // an enclosing loop it will only be via a separate LCSSA node.
  514. bool LCSSASafePhiForRAUW =
  515. NumPreds == 1 &&
  516. (!L->getParentLoop() || L->getParentLoop() == LI->getLoopFor(ExitBB));
  517. // Iterate over all of the PHI nodes.
  518. BasicBlock::iterator BBI = ExitBB->begin();
  519. while ((PN = dyn_cast<PHINode>(BBI++))) {
  520. if (PN->use_empty())
  521. continue; // dead use, don't replace it
  522. // SCEV only supports integer expressions for now.
  523. if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
  524. continue;
  525. // It's necessary to tell ScalarEvolution about this explicitly so that
  526. // it can walk the def-use list and forget all SCEVs, as it may not be
  527. // watching the PHI itself. Once the new exit value is in place, there
  528. // may not be a def-use connection between the loop and every instruction
  529. // which got a SCEVAddRecExpr for that loop.
  530. SE->forgetValue(PN);
  531. // Iterate over all of the values in all the PHI nodes.
  532. for (unsigned i = 0; i != NumPreds; ++i) {
  533. // If the value being merged in is not integer or is not defined
  534. // in the loop, skip it.
  535. Value *InVal = PN->getIncomingValue(i);
  536. if (!isa<Instruction>(InVal))
  537. continue;
  538. // If this pred is for a subloop, not L itself, skip it.
  539. if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
  540. continue; // The Block is in a subloop, skip it.
  541. // Check that InVal is defined in the loop.
  542. Instruction *Inst = cast<Instruction>(InVal);
  543. if (!L->contains(Inst))
  544. continue;
  545. // Okay, this instruction has a user outside of the current loop
  546. // and varies predictably *inside* the loop. Evaluate the value it
  547. // contains when the loop exits, if possible.
  548. const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
  549. if (!SE->isLoopInvariant(ExitValue, L) ||
  550. !isSafeToExpand(ExitValue, *SE))
  551. continue;
  552. // Computing the value outside of the loop brings no benefit if :
  553. // - it is definitely used inside the loop in a way which can not be
  554. // optimized away.
  555. // - no use outside of the loop can take advantage of hoisting the
  556. // computation out of the loop
  557. if (ExitValue->getSCEVType()>=scMulExpr) {
  558. unsigned NumHardInternalUses = 0;
  559. unsigned NumSoftExternalUses = 0;
  560. unsigned NumUses = 0;
  561. for (auto IB = Inst->user_begin(), IE = Inst->user_end();
  562. IB != IE && NumUses <= 6; ++IB) {
  563. Instruction *UseInstr = cast<Instruction>(*IB);
  564. unsigned Opc = UseInstr->getOpcode();
  565. NumUses++;
  566. if (L->contains(UseInstr)) {
  567. if (Opc == Instruction::Call || Opc == Instruction::Ret)
  568. NumHardInternalUses++;
  569. } else {
  570. if (Opc == Instruction::PHI) {
  571. // Do not count the Phi as a use. LCSSA may have inserted
  572. // plenty of trivial ones.
  573. NumUses--;
  574. for (auto PB = UseInstr->user_begin(),
  575. PE = UseInstr->user_end();
  576. PB != PE && NumUses <= 6; ++PB, ++NumUses) {
  577. unsigned PhiOpc = cast<Instruction>(*PB)->getOpcode();
  578. if (PhiOpc != Instruction::Call && PhiOpc != Instruction::Ret)
  579. NumSoftExternalUses++;
  580. }
  581. continue;
  582. }
  583. if (Opc != Instruction::Call && Opc != Instruction::Ret)
  584. NumSoftExternalUses++;
  585. }
  586. }
  587. if (NumUses <= 6 && NumHardInternalUses && !NumSoftExternalUses)
  588. continue;
  589. }
  590. bool HighCost = false;
  591. Value *ExitVal = ExpandSCEVIfNeeded(Rewriter, ExitValue, L, Inst,
  592. PN->getType(), HighCost);
  593. DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
  594. << " LoopVal = " << *Inst << "\n");
  595. if (!isValidRewrite(Inst, ExitVal)) {
  596. DeadInsts.push_back(ExitVal);
  597. continue;
  598. }
  599. // Collect all the candidate PHINodes to be rewritten.
  600. RewritePhiSet.push_back(
  601. RewritePhi(PN, i, ExitVal, HighCost, LCSSASafePhiForRAUW));
  602. }
  603. }
  604. }
  605. bool LoopCanBeDel = CanLoopBeDeleted(L, RewritePhiSet);
  606. // Transformation.
  607. for (const RewritePhi &Phi : RewritePhiSet) {
  608. PHINode *PN = Phi.PN;
  609. Value *ExitVal = Phi.Val;
  610. // Only do the rewrite when the ExitValue can be expanded cheaply.
  611. // If LoopCanBeDel is true, rewrite exit value aggressively.
  612. if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) {
  613. DeadInsts.push_back(ExitVal);
  614. continue;
  615. }
  616. Changed = true;
  617. ++NumReplaced;
  618. Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
  619. PN->setIncomingValue(Phi.Ith, ExitVal);
  620. // If this instruction is dead now, delete it. Don't do it now to avoid
  621. // invalidating iterators.
  622. if (isInstructionTriviallyDead(Inst, TLI))
  623. DeadInsts.push_back(Inst);
  624. // If we determined that this PHI is safe to replace even if an LCSSA
  625. // PHI, do so.
  626. if (Phi.SafePhi) {
  627. PN->replaceAllUsesWith(ExitVal);
  628. PN->eraseFromParent();
  629. }
  630. }
  631. // The insertion point instruction may have been deleted; clear it out
  632. // so that the rewriter doesn't trip over it later.
  633. Rewriter.clearInsertPoint();
  634. }
  635. /// CanLoopBeDeleted - Check whether it is possible to delete the loop after
  636. /// rewriting exit value. If it is possible, ignore ReplaceExitValue and
  637. /// do rewriting aggressively.
  638. bool IndVarSimplify::CanLoopBeDeleted(
  639. Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
  640. BasicBlock *Preheader = L->getLoopPreheader();
  641. // If there is no preheader, the loop will not be deleted.
  642. if (!Preheader)
  643. return false;
  644. // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
  645. // We obviate multiple ExitingBlocks case for simplicity.
  646. // TODO: If we see testcase with multiple ExitingBlocks can be deleted
  647. // after exit value rewriting, we can enhance the logic here.
  648. SmallVector<BasicBlock *, 4> ExitingBlocks;
  649. L->getExitingBlocks(ExitingBlocks);
  650. SmallVector<BasicBlock *, 8> ExitBlocks;
  651. L->getUniqueExitBlocks(ExitBlocks);
  652. if (ExitBlocks.size() > 1 || ExitingBlocks.size() > 1)
  653. return false;
  654. BasicBlock *ExitBlock = ExitBlocks[0];
  655. BasicBlock::iterator BI = ExitBlock->begin();
  656. while (PHINode *P = dyn_cast<PHINode>(BI)) {
  657. Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
  658. // If the Incoming value of P is found in RewritePhiSet, we know it
  659. // could be rewritten to use a loop invariant value in transformation
  660. // phase later. Skip it in the loop invariant check below.
  661. bool found = false;
  662. for (const RewritePhi &Phi : RewritePhiSet) {
  663. unsigned i = Phi.Ith;
  664. if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
  665. found = true;
  666. break;
  667. }
  668. }
  669. Instruction *I;
  670. if (!found && (I = dyn_cast<Instruction>(Incoming)))
  671. if (!L->hasLoopInvariantOperands(I))
  672. return false;
  673. ++BI;
  674. }
  675. for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
  676. LI != LE; ++LI) {
  677. for (BasicBlock::iterator BI = (*LI)->begin(), BE = (*LI)->end(); BI != BE;
  678. ++BI) {
  679. if (BI->mayHaveSideEffects())
  680. return false;
  681. }
  682. }
  683. return true;
  684. }
  685. //===----------------------------------------------------------------------===//
  686. // IV Widening - Extend the width of an IV to cover its widest uses.
  687. //===----------------------------------------------------------------------===//
  688. namespace {
  689. // Collect information about induction variables that are used by sign/zero
  690. // extend operations. This information is recorded by CollectExtend and
  691. // provides the input to WidenIV.
  692. struct WideIVInfo {
  693. PHINode *NarrowIV;
  694. Type *WidestNativeType; // Widest integer type created [sz]ext
  695. bool IsSigned; // Was a sext user seen before a zext?
  696. WideIVInfo() : NarrowIV(nullptr), WidestNativeType(nullptr),
  697. IsSigned(false) {}
  698. };
  699. }
  700. /// visitCast - Update information about the induction variable that is
  701. /// extended by this sign or zero extend operation. This is used to determine
  702. /// the final width of the IV before actually widening it.
  703. static void visitIVCast(CastInst *Cast, WideIVInfo &WI, ScalarEvolution *SE,
  704. const TargetTransformInfo *TTI) {
  705. bool IsSigned = Cast->getOpcode() == Instruction::SExt;
  706. if (!IsSigned && Cast->getOpcode() != Instruction::ZExt)
  707. return;
  708. Type *Ty = Cast->getType();
  709. uint64_t Width = SE->getTypeSizeInBits(Ty);
  710. if (!Cast->getModule()->getDataLayout().isLegalInteger(Width))
  711. return;
  712. // Cast is either an sext or zext up to this point.
  713. // We should not widen an indvar if arithmetics on the wider indvar are more
  714. // expensive than those on the narrower indvar. We check only the cost of ADD
  715. // because at least an ADD is required to increment the induction variable. We
  716. // could compute more comprehensively the cost of all instructions on the
  717. // induction variable when necessary.
  718. if (TTI &&
  719. TTI->getArithmeticInstrCost(Instruction::Add, Ty) >
  720. TTI->getArithmeticInstrCost(Instruction::Add,
  721. Cast->getOperand(0)->getType())) {
  722. return;
  723. }
  724. if (!WI.WidestNativeType) {
  725. WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
  726. WI.IsSigned = IsSigned;
  727. return;
  728. }
  729. // We extend the IV to satisfy the sign of its first user, arbitrarily.
  730. if (WI.IsSigned != IsSigned)
  731. return;
  732. if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
  733. WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
  734. }
  735. namespace {
  736. /// NarrowIVDefUse - Record a link in the Narrow IV def-use chain along with the
  737. /// WideIV that computes the same value as the Narrow IV def. This avoids
  738. /// caching Use* pointers.
  739. struct NarrowIVDefUse {
  740. Instruction *NarrowDef;
  741. Instruction *NarrowUse;
  742. Instruction *WideDef;
  743. NarrowIVDefUse(): NarrowDef(nullptr), NarrowUse(nullptr), WideDef(nullptr) {}
  744. NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD):
  745. NarrowDef(ND), NarrowUse(NU), WideDef(WD) {}
  746. };
  747. /// WidenIV - The goal of this transform is to remove sign and zero extends
  748. /// without creating any new induction variables. To do this, it creates a new
  749. /// phi of the wider type and redirects all users, either removing extends or
  750. /// inserting truncs whenever we stop propagating the type.
  751. ///
  752. class WidenIV {
  753. // Parameters
  754. PHINode *OrigPhi;
  755. Type *WideType;
  756. bool IsSigned;
  757. // Context
  758. LoopInfo *LI;
  759. Loop *L;
  760. ScalarEvolution *SE;
  761. DominatorTree *DT;
  762. // Result
  763. PHINode *WidePhi;
  764. Instruction *WideInc;
  765. const SCEV *WideIncExpr;
  766. SmallVectorImpl<WeakVH> &DeadInsts;
  767. SmallPtrSet<Instruction*,16> Widened;
  768. SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
  769. public:
  770. WidenIV(const WideIVInfo &WI, LoopInfo *LInfo,
  771. ScalarEvolution *SEv, DominatorTree *DTree,
  772. SmallVectorImpl<WeakVH> &DI) :
  773. OrigPhi(WI.NarrowIV),
  774. WideType(WI.WidestNativeType),
  775. IsSigned(WI.IsSigned),
  776. LI(LInfo),
  777. L(LI->getLoopFor(OrigPhi->getParent())),
  778. SE(SEv),
  779. DT(DTree),
  780. WidePhi(nullptr),
  781. WideInc(nullptr),
  782. WideIncExpr(nullptr),
  783. DeadInsts(DI) {
  784. assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
  785. }
  786. PHINode *CreateWideIV(SCEVExpander &Rewriter);
  787. protected:
  788. Value *getExtend(Value *NarrowOper, Type *WideType, bool IsSigned,
  789. Instruction *Use);
  790. Instruction *CloneIVUser(NarrowIVDefUse DU);
  791. const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
  792. const SCEVAddRecExpr* GetExtendedOperandRecurrence(NarrowIVDefUse DU);
  793. const SCEV *GetSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
  794. unsigned OpCode) const;
  795. Instruction *WidenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter);
  796. bool WidenLoopCompare(NarrowIVDefUse DU);
  797. void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
  798. };
  799. } // anonymous namespace
  800. /// isLoopInvariant - Perform a quick domtree based check for loop invariance
  801. /// assuming that V is used within the loop. LoopInfo::isLoopInvariant() seems
  802. /// gratuitous for this purpose.
  803. static bool isLoopInvariant(Value *V, const Loop *L, const DominatorTree *DT) {
  804. Instruction *Inst = dyn_cast<Instruction>(V);
  805. if (!Inst)
  806. return true;
  807. return DT->properlyDominates(Inst->getParent(), L->getHeader());
  808. }
  809. Value *WidenIV::getExtend(Value *NarrowOper, Type *WideType, bool IsSigned,
  810. Instruction *Use) {
  811. // Set the debug location and conservative insertion point.
  812. IRBuilder<> Builder(Use);
  813. // Hoist the insertion point into loop preheaders as far as possible.
  814. for (const Loop *L = LI->getLoopFor(Use->getParent());
  815. L && L->getLoopPreheader() && isLoopInvariant(NarrowOper, L, DT);
  816. L = L->getParentLoop())
  817. Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
  818. return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
  819. Builder.CreateZExt(NarrowOper, WideType);
  820. }
  821. /// CloneIVUser - Instantiate a wide operation to replace a narrow
  822. /// operation. This only needs to handle operations that can evaluation to
  823. /// SCEVAddRec. It can safely return 0 for any operation we decide not to clone.
  824. Instruction *WidenIV::CloneIVUser(NarrowIVDefUse DU) {
  825. unsigned Opcode = DU.NarrowUse->getOpcode();
  826. switch (Opcode) {
  827. default:
  828. return nullptr;
  829. case Instruction::Add:
  830. case Instruction::Mul:
  831. case Instruction::UDiv:
  832. case Instruction::Sub:
  833. case Instruction::And:
  834. case Instruction::Or:
  835. case Instruction::Xor:
  836. case Instruction::Shl:
  837. case Instruction::LShr:
  838. case Instruction::AShr:
  839. DEBUG(dbgs() << "Cloning IVUser: " << *DU.NarrowUse << "\n");
  840. // Replace NarrowDef operands with WideDef. Otherwise, we don't know
  841. // anything about the narrow operand yet so must insert a [sz]ext. It is
  842. // probably loop invariant and will be folded or hoisted. If it actually
  843. // comes from a widened IV, it should be removed during a future call to
  844. // WidenIVUse.
  845. Value *LHS = (DU.NarrowUse->getOperand(0) == DU.NarrowDef) ? DU.WideDef :
  846. getExtend(DU.NarrowUse->getOperand(0), WideType, IsSigned, DU.NarrowUse);
  847. Value *RHS = (DU.NarrowUse->getOperand(1) == DU.NarrowDef) ? DU.WideDef :
  848. getExtend(DU.NarrowUse->getOperand(1), WideType, IsSigned, DU.NarrowUse);
  849. BinaryOperator *NarrowBO = cast<BinaryOperator>(DU.NarrowUse);
  850. BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
  851. LHS, RHS,
  852. NarrowBO->getName());
  853. IRBuilder<> Builder(DU.NarrowUse);
  854. Builder.Insert(WideBO);
  855. if (const OverflowingBinaryOperator *OBO =
  856. dyn_cast<OverflowingBinaryOperator>(NarrowBO)) {
  857. if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
  858. if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
  859. }
  860. return WideBO;
  861. }
  862. }
  863. const SCEV *WidenIV::GetSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
  864. unsigned OpCode) const {
  865. if (OpCode == Instruction::Add)
  866. return SE->getAddExpr(LHS, RHS);
  867. if (OpCode == Instruction::Sub)
  868. return SE->getMinusSCEV(LHS, RHS);
  869. if (OpCode == Instruction::Mul)
  870. return SE->getMulExpr(LHS, RHS);
  871. llvm_unreachable("Unsupported opcode.");
  872. }
  873. /// No-wrap operations can transfer sign extension of their result to their
  874. /// operands. Generate the SCEV value for the widened operation without
  875. /// actually modifying the IR yet. If the expression after extending the
  876. /// operands is an AddRec for this loop, return it.
  877. const SCEVAddRecExpr* WidenIV::GetExtendedOperandRecurrence(NarrowIVDefUse DU) {
  878. // Handle the common case of add<nsw/nuw>
  879. const unsigned OpCode = DU.NarrowUse->getOpcode();
  880. // Only Add/Sub/Mul instructions supported yet.
  881. if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
  882. OpCode != Instruction::Mul)
  883. return nullptr;
  884. // One operand (NarrowDef) has already been extended to WideDef. Now determine
  885. // if extending the other will lead to a recurrence.
  886. const unsigned ExtendOperIdx =
  887. DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
  888. assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU");
  889. const SCEV *ExtendOperExpr = nullptr;
  890. const OverflowingBinaryOperator *OBO =
  891. cast<OverflowingBinaryOperator>(DU.NarrowUse);
  892. if (IsSigned && OBO->hasNoSignedWrap())
  893. ExtendOperExpr = SE->getSignExtendExpr(
  894. SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
  895. else if(!IsSigned && OBO->hasNoUnsignedWrap())
  896. ExtendOperExpr = SE->getZeroExtendExpr(
  897. SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
  898. else
  899. return nullptr;
  900. // When creating this SCEV expr, don't apply the current operations NSW or NUW
  901. // flags. This instruction may be guarded by control flow that the no-wrap
  902. // behavior depends on. Non-control-equivalent instructions can be mapped to
  903. // the same SCEV expression, and it would be incorrect to transfer NSW/NUW
  904. // semantics to those operations.
  905. const SCEV *lhs = SE->getSCEV(DU.WideDef);
  906. const SCEV *rhs = ExtendOperExpr;
  907. // Let's swap operands to the initial order for the case of non-commutative
  908. // operations, like SUB. See PR21014.
  909. if (ExtendOperIdx == 0)
  910. std::swap(lhs, rhs);
  911. const SCEVAddRecExpr *AddRec =
  912. dyn_cast<SCEVAddRecExpr>(GetSCEVByOpCode(lhs, rhs, OpCode));
  913. if (!AddRec || AddRec->getLoop() != L)
  914. return nullptr;
  915. return AddRec;
  916. }
  917. /// GetWideRecurrence - Is this instruction potentially interesting for further
  918. /// simplification after widening it's type? In other words, can the
  919. /// extend be safely hoisted out of the loop with SCEV reducing the value to a
  920. /// recurrence on the same loop. If so, return the sign or zero extended
  921. /// recurrence. Otherwise return NULL.
  922. const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
  923. if (!SE->isSCEVable(NarrowUse->getType()))
  924. return nullptr;
  925. const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
  926. if (SE->getTypeSizeInBits(NarrowExpr->getType())
  927. >= SE->getTypeSizeInBits(WideType)) {
  928. // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
  929. // index. So don't follow this use.
  930. return nullptr;
  931. }
  932. const SCEV *WideExpr = IsSigned ?
  933. SE->getSignExtendExpr(NarrowExpr, WideType) :
  934. SE->getZeroExtendExpr(NarrowExpr, WideType);
  935. const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
  936. if (!AddRec || AddRec->getLoop() != L)
  937. return nullptr;
  938. return AddRec;
  939. }
  940. /// This IV user cannot be widen. Replace this use of the original narrow IV
  941. /// with a truncation of the new wide IV to isolate and eliminate the narrow IV.
  942. static void truncateIVUse(NarrowIVDefUse DU, DominatorTree *DT) {
  943. DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef
  944. << " for user " << *DU.NarrowUse << "\n");
  945. IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT));
  946. Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
  947. DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
  948. }
  949. /// If the narrow use is a compare instruction, then widen the compare
  950. // (and possibly the other operand). The extend operation is hoisted into the
  951. // loop preheader as far as possible.
  952. bool WidenIV::WidenLoopCompare(NarrowIVDefUse DU) {
  953. ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse);
  954. if (!Cmp)
  955. return false;
  956. // Sign of IV user and compare must match.
  957. if (IsSigned != CmpInst::isSigned(Cmp->getPredicate()))
  958. return false;
  959. Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0);
  960. unsigned CastWidth = SE->getTypeSizeInBits(Op->getType());
  961. unsigned IVWidth = SE->getTypeSizeInBits(WideType);
  962. assert (CastWidth <= IVWidth && "Unexpected width while widening compare.");
  963. // Widen the compare instruction.
  964. IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT));
  965. DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
  966. // Widen the other operand of the compare, if necessary.
  967. if (CastWidth < IVWidth) {
  968. Value *ExtOp = getExtend(Op, WideType, IsSigned, Cmp);
  969. DU.NarrowUse->replaceUsesOfWith(Op, ExtOp);
  970. }
  971. return true;
  972. }
  973. /// WidenIVUse - Determine whether an individual user of the narrow IV can be
  974. /// widened. If so, return the wide clone of the user.
  975. Instruction *WidenIV::WidenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter) {
  976. // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
  977. if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
  978. if (LI->getLoopFor(UsePhi->getParent()) != L) {
  979. // For LCSSA phis, sink the truncate outside the loop.
  980. // After SimplifyCFG most loop exit targets have a single predecessor.
  981. // Otherwise fall back to a truncate within the loop.
  982. if (UsePhi->getNumOperands() != 1)
  983. truncateIVUse(DU, DT);
  984. else {
  985. PHINode *WidePhi =
  986. PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
  987. UsePhi);
  988. WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
  989. IRBuilder<> Builder(WidePhi->getParent()->getFirstInsertionPt());
  990. Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
  991. UsePhi->replaceAllUsesWith(Trunc);
  992. DeadInsts.emplace_back(UsePhi);
  993. DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi
  994. << " to " << *WidePhi << "\n");
  995. }
  996. return nullptr;
  997. }
  998. }
  999. // Our raison d'etre! Eliminate sign and zero extension.
  1000. if (IsSigned ? isa<SExtInst>(DU.NarrowUse) : isa<ZExtInst>(DU.NarrowUse)) {
  1001. Value *NewDef = DU.WideDef;
  1002. if (DU.NarrowUse->getType() != WideType) {
  1003. unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
  1004. unsigned IVWidth = SE->getTypeSizeInBits(WideType);
  1005. if (CastWidth < IVWidth) {
  1006. // The cast isn't as wide as the IV, so insert a Trunc.
  1007. IRBuilder<> Builder(DU.NarrowUse);
  1008. NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
  1009. }
  1010. else {
  1011. // A wider extend was hidden behind a narrower one. This may induce
  1012. // another round of IV widening in which the intermediate IV becomes
  1013. // dead. It should be very rare.
  1014. DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
  1015. << " not wide enough to subsume " << *DU.NarrowUse << "\n");
  1016. DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
  1017. NewDef = DU.NarrowUse;
  1018. }
  1019. }
  1020. if (NewDef != DU.NarrowUse) {
  1021. DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
  1022. << " replaced by " << *DU.WideDef << "\n");
  1023. ++NumElimExt;
  1024. DU.NarrowUse->replaceAllUsesWith(NewDef);
  1025. DeadInsts.emplace_back(DU.NarrowUse);
  1026. }
  1027. // Now that the extend is gone, we want to expose it's uses for potential
  1028. // further simplification. We don't need to directly inform SimplifyIVUsers
  1029. // of the new users, because their parent IV will be processed later as a
  1030. // new loop phi. If we preserved IVUsers analysis, we would also want to
  1031. // push the uses of WideDef here.
  1032. // No further widening is needed. The deceased [sz]ext had done it for us.
  1033. return nullptr;
  1034. }
  1035. // Does this user itself evaluate to a recurrence after widening?
  1036. const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(DU.NarrowUse);
  1037. if (!WideAddRec)
  1038. WideAddRec = GetExtendedOperandRecurrence(DU);
  1039. if (!WideAddRec) {
  1040. // If use is a loop condition, try to promote the condition instead of
  1041. // truncating the IV first.
  1042. if (WidenLoopCompare(DU))
  1043. return nullptr;
  1044. // This user does not evaluate to a recurence after widening, so don't
  1045. // follow it. Instead insert a Trunc to kill off the original use,
  1046. // eventually isolating the original narrow IV so it can be removed.
  1047. truncateIVUse(DU, DT);
  1048. return nullptr;
  1049. }
  1050. // Assume block terminators cannot evaluate to a recurrence. We can't to
  1051. // insert a Trunc after a terminator if there happens to be a critical edge.
  1052. assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
  1053. "SCEV is not expected to evaluate a block terminator");
  1054. // Reuse the IV increment that SCEVExpander created as long as it dominates
  1055. // NarrowUse.
  1056. Instruction *WideUse = nullptr;
  1057. if (WideAddRec == WideIncExpr
  1058. && Rewriter.hoistIVInc(WideInc, DU.NarrowUse))
  1059. WideUse = WideInc;
  1060. else {
  1061. WideUse = CloneIVUser(DU);
  1062. if (!WideUse)
  1063. return nullptr;
  1064. }
  1065. // Evaluation of WideAddRec ensured that the narrow expression could be
  1066. // extended outside the loop without overflow. This suggests that the wide use
  1067. // evaluates to the same expression as the extended narrow use, but doesn't
  1068. // absolutely guarantee it. Hence the following failsafe check. In rare cases
  1069. // where it fails, we simply throw away the newly created wide use.
  1070. if (WideAddRec != SE->getSCEV(WideUse)) {
  1071. DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
  1072. << ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
  1073. DeadInsts.emplace_back(WideUse);
  1074. return nullptr;
  1075. }
  1076. // Returning WideUse pushes it on the worklist.
  1077. return WideUse;
  1078. }
  1079. /// pushNarrowIVUsers - Add eligible users of NarrowDef to NarrowIVUsers.
  1080. ///
  1081. void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
  1082. for (User *U : NarrowDef->users()) {
  1083. Instruction *NarrowUser = cast<Instruction>(U);
  1084. // Handle data flow merges and bizarre phi cycles.
  1085. if (!Widened.insert(NarrowUser).second)
  1086. continue;
  1087. NarrowIVUsers.push_back(NarrowIVDefUse(NarrowDef, NarrowUser, WideDef));
  1088. }
  1089. }
  1090. /// CreateWideIV - Process a single induction variable. First use the
  1091. /// SCEVExpander to create a wide induction variable that evaluates to the same
  1092. /// recurrence as the original narrow IV. Then use a worklist to forward
  1093. /// traverse the narrow IV's def-use chain. After WidenIVUse has processed all
  1094. /// interesting IV users, the narrow IV will be isolated for removal by
  1095. /// DeleteDeadPHIs.
  1096. ///
  1097. /// It would be simpler to delete uses as they are processed, but we must avoid
  1098. /// invalidating SCEV expressions.
  1099. ///
  1100. PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
  1101. // Is this phi an induction variable?
  1102. const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
  1103. if (!AddRec)
  1104. return nullptr;
  1105. // Widen the induction variable expression.
  1106. const SCEV *WideIVExpr = IsSigned ?
  1107. SE->getSignExtendExpr(AddRec, WideType) :
  1108. SE->getZeroExtendExpr(AddRec, WideType);
  1109. assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
  1110. "Expect the new IV expression to preserve its type");
  1111. // Can the IV be extended outside the loop without overflow?
  1112. AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
  1113. if (!AddRec || AddRec->getLoop() != L)
  1114. return nullptr;
  1115. // An AddRec must have loop-invariant operands. Since this AddRec is
  1116. // materialized by a loop header phi, the expression cannot have any post-loop
  1117. // operands, so they must dominate the loop header.
  1118. assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
  1119. SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
  1120. && "Loop header phi recurrence inputs do not dominate the loop");
  1121. // The rewriter provides a value for the desired IV expression. This may
  1122. // either find an existing phi or materialize a new one. Either way, we
  1123. // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
  1124. // of the phi-SCC dominates the loop entry.
  1125. Instruction *InsertPt = L->getHeader()->begin();
  1126. WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
  1127. // Remembering the WideIV increment generated by SCEVExpander allows
  1128. // WidenIVUse to reuse it when widening the narrow IV's increment. We don't
  1129. // employ a general reuse mechanism because the call above is the only call to
  1130. // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
  1131. if (BasicBlock *LatchBlock = L->getLoopLatch()) {
  1132. WideInc =
  1133. cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
  1134. WideIncExpr = SE->getSCEV(WideInc);
  1135. }
  1136. DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
  1137. ++NumWidened;
  1138. // Traverse the def-use chain using a worklist starting at the original IV.
  1139. assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
  1140. Widened.insert(OrigPhi);
  1141. pushNarrowIVUsers(OrigPhi, WidePhi);
  1142. while (!NarrowIVUsers.empty()) {
  1143. NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
  1144. // Process a def-use edge. This may replace the use, so don't hold a
  1145. // use_iterator across it.
  1146. Instruction *WideUse = WidenIVUse(DU, Rewriter);
  1147. // Follow all def-use edges from the previous narrow use.
  1148. if (WideUse)
  1149. pushNarrowIVUsers(DU.NarrowUse, WideUse);
  1150. // WidenIVUse may have removed the def-use edge.
  1151. if (DU.NarrowDef->use_empty())
  1152. DeadInsts.emplace_back(DU.NarrowDef);
  1153. }
  1154. return WidePhi;
  1155. }
  1156. //===----------------------------------------------------------------------===//
  1157. // Live IV Reduction - Minimize IVs live across the loop.
  1158. //===----------------------------------------------------------------------===//
  1159. //===----------------------------------------------------------------------===//
  1160. // Simplification of IV users based on SCEV evaluation.
  1161. //===----------------------------------------------------------------------===//
  1162. namespace {
  1163. class IndVarSimplifyVisitor : public IVVisitor {
  1164. ScalarEvolution *SE;
  1165. const TargetTransformInfo *TTI;
  1166. PHINode *IVPhi;
  1167. public:
  1168. WideIVInfo WI;
  1169. IndVarSimplifyVisitor(PHINode *IV, ScalarEvolution *SCEV,
  1170. const TargetTransformInfo *TTI,
  1171. const DominatorTree *DTree)
  1172. : SE(SCEV), TTI(TTI), IVPhi(IV) {
  1173. DT = DTree;
  1174. WI.NarrowIV = IVPhi;
  1175. if (ReduceLiveIVs)
  1176. setSplitOverflowIntrinsics();
  1177. }
  1178. // Implement the interface used by simplifyUsersOfIV.
  1179. void visitCast(CastInst *Cast) override { visitIVCast(Cast, WI, SE, TTI); }
  1180. };
  1181. }
  1182. /// SimplifyAndExtend - Iteratively perform simplification on a worklist of IV
  1183. /// users. Each successive simplification may push more users which may
  1184. /// themselves be candidates for simplification.
  1185. ///
  1186. /// Sign/Zero extend elimination is interleaved with IV simplification.
  1187. ///
  1188. void IndVarSimplify::SimplifyAndExtend(Loop *L,
  1189. SCEVExpander &Rewriter,
  1190. LPPassManager &LPM) {
  1191. SmallVector<WideIVInfo, 8> WideIVs;
  1192. SmallVector<PHINode*, 8> LoopPhis;
  1193. for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
  1194. LoopPhis.push_back(cast<PHINode>(I));
  1195. }
  1196. // Each round of simplification iterates through the SimplifyIVUsers worklist
  1197. // for all current phis, then determines whether any IVs can be
  1198. // widened. Widening adds new phis to LoopPhis, inducing another round of
  1199. // simplification on the wide IVs.
  1200. while (!LoopPhis.empty()) {
  1201. // Evaluate as many IV expressions as possible before widening any IVs. This
  1202. // forces SCEV to set no-wrap flags before evaluating sign/zero
  1203. // extension. The first time SCEV attempts to normalize sign/zero extension,
  1204. // the result becomes final. So for the most predictable results, we delay
  1205. // evaluation of sign/zero extend evaluation until needed, and avoid running
  1206. // other SCEV based analysis prior to SimplifyAndExtend.
  1207. do {
  1208. PHINode *CurrIV = LoopPhis.pop_back_val();
  1209. // Information about sign/zero extensions of CurrIV.
  1210. IndVarSimplifyVisitor Visitor(CurrIV, SE, TTI, DT);
  1211. Changed |= simplifyUsersOfIV(CurrIV, SE, &LPM, DeadInsts, &Visitor);
  1212. if (Visitor.WI.WidestNativeType) {
  1213. WideIVs.push_back(Visitor.WI);
  1214. }
  1215. } while(!LoopPhis.empty());
  1216. for (; !WideIVs.empty(); WideIVs.pop_back()) {
  1217. WidenIV Widener(WideIVs.back(), LI, SE, DT, DeadInsts);
  1218. if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) {
  1219. Changed = true;
  1220. LoopPhis.push_back(WidePhi);
  1221. }
  1222. }
  1223. }
  1224. }
  1225. //===----------------------------------------------------------------------===//
  1226. // LinearFunctionTestReplace and its kin. Rewrite the loop exit condition.
  1227. //===----------------------------------------------------------------------===//
  1228. /// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
  1229. /// count expression can be safely and cheaply expanded into an instruction
  1230. /// sequence that can be used by LinearFunctionTestReplace.
  1231. ///
  1232. /// TODO: This fails for pointer-type loop counters with greater than one byte
  1233. /// strides, consequently preventing LFTR from running. For the purpose of LFTR
  1234. /// we could skip this check in the case that the LFTR loop counter (chosen by
  1235. /// FindLoopCounter) is also pointer type. Instead, we could directly convert
  1236. /// the loop test to an inequality test by checking the target data's alignment
  1237. /// of element types (given that the initial pointer value originates from or is
  1238. /// used by ABI constrained operation, as opposed to inttoptr/ptrtoint).
  1239. /// However, we don't yet have a strong motivation for converting loop tests
  1240. /// into inequality tests.
  1241. static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE,
  1242. SCEVExpander &Rewriter) {
  1243. const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
  1244. if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
  1245. BackedgeTakenCount->isZero())
  1246. return false;
  1247. if (!L->getExitingBlock())
  1248. return false;
  1249. // Can't rewrite non-branch yet.
  1250. if (!isa<BranchInst>(L->getExitingBlock()->getTerminator()))
  1251. return false;
  1252. if (Rewriter.isHighCostExpansion(BackedgeTakenCount, L))
  1253. return false;
  1254. return true;
  1255. }
  1256. /// getLoopPhiForCounter - Return the loop header phi IFF IncV adds a loop
  1257. /// invariant value to the phi.
  1258. static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) {
  1259. Instruction *IncI = dyn_cast<Instruction>(IncV);
  1260. if (!IncI)
  1261. return nullptr;
  1262. switch (IncI->getOpcode()) {
  1263. case Instruction::Add:
  1264. case Instruction::Sub:
  1265. break;
  1266. case Instruction::GetElementPtr:
  1267. // An IV counter must preserve its type.
  1268. if (IncI->getNumOperands() == 2)
  1269. break;
  1270. default:
  1271. return nullptr;
  1272. }
  1273. PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
  1274. if (Phi && Phi->getParent() == L->getHeader()) {
  1275. if (isLoopInvariant(IncI->getOperand(1), L, DT))
  1276. return Phi;
  1277. return nullptr;
  1278. }
  1279. if (IncI->getOpcode() == Instruction::GetElementPtr)
  1280. return nullptr;
  1281. // Allow add/sub to be commuted.
  1282. Phi = dyn_cast<PHINode>(IncI->getOperand(1));
  1283. if (Phi && Phi->getParent() == L->getHeader()) {
  1284. if (isLoopInvariant(IncI->getOperand(0), L, DT))
  1285. return Phi;
  1286. }
  1287. return nullptr;
  1288. }
  1289. /// Return the compare guarding the loop latch, or NULL for unrecognized tests.
  1290. static ICmpInst *getLoopTest(Loop *L) {
  1291. assert(L->getExitingBlock() && "expected loop exit");
  1292. BasicBlock *LatchBlock = L->getLoopLatch();
  1293. // Don't bother with LFTR if the loop is not properly simplified.
  1294. if (!LatchBlock)
  1295. return nullptr;
  1296. BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
  1297. assert(BI && "expected exit branch");
  1298. return dyn_cast<ICmpInst>(BI->getCondition());
  1299. }
  1300. /// needsLFTR - LinearFunctionTestReplace policy. Return true unless we can show
  1301. /// that the current exit test is already sufficiently canonical.
  1302. static bool needsLFTR(Loop *L, DominatorTree *DT) {
  1303. // Do LFTR to simplify the exit condition to an ICMP.
  1304. ICmpInst *Cond = getLoopTest(L);
  1305. if (!Cond)
  1306. return true;
  1307. // Do LFTR to simplify the exit ICMP to EQ/NE
  1308. ICmpInst::Predicate Pred = Cond->getPredicate();
  1309. if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
  1310. return true;
  1311. // Look for a loop invariant RHS
  1312. Value *LHS = Cond->getOperand(0);
  1313. Value *RHS = Cond->getOperand(1);
  1314. if (!isLoopInvariant(RHS, L, DT)) {
  1315. if (!isLoopInvariant(LHS, L, DT))
  1316. return true;
  1317. std::swap(LHS, RHS);
  1318. }
  1319. // Look for a simple IV counter LHS
  1320. PHINode *Phi = dyn_cast<PHINode>(LHS);
  1321. if (!Phi)
  1322. Phi = getLoopPhiForCounter(LHS, L, DT);
  1323. if (!Phi)
  1324. return true;
  1325. // Do LFTR if PHI node is defined in the loop, but is *not* a counter.
  1326. int Idx = Phi->getBasicBlockIndex(L->getLoopLatch());
  1327. if (Idx < 0)
  1328. return true;
  1329. // Do LFTR if the exit condition's IV is *not* a simple counter.
  1330. Value *IncV = Phi->getIncomingValue(Idx);
  1331. return Phi != getLoopPhiForCounter(IncV, L, DT);
  1332. }
  1333. /// Recursive helper for hasConcreteDef(). Unfortunately, this currently boils
  1334. /// down to checking that all operands are constant and listing instructions
  1335. /// that may hide undef.
  1336. static bool hasConcreteDefImpl(Value *V, SmallPtrSetImpl<Value*> &Visited,
  1337. unsigned Depth) {
  1338. if (isa<Constant>(V))
  1339. return !isa<UndefValue>(V);
  1340. if (Depth >= 6)
  1341. return false;
  1342. // Conservatively handle non-constant non-instructions. For example, Arguments
  1343. // may be undef.
  1344. Instruction *I = dyn_cast<Instruction>(V);
  1345. if (!I)
  1346. return false;
  1347. // Load and return values may be undef.
  1348. if(I->mayReadFromMemory() || isa<CallInst>(I) || isa<InvokeInst>(I))
  1349. return false;
  1350. // Optimistically handle other instructions.
  1351. for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) {
  1352. if (!Visited.insert(*OI).second)
  1353. continue;
  1354. if (!hasConcreteDefImpl(*OI, Visited, Depth+1))
  1355. return false;
  1356. }
  1357. return true;
  1358. }
  1359. /// Return true if the given value is concrete. We must prove that undef can
  1360. /// never reach it.
  1361. ///
  1362. /// TODO: If we decide that this is a good approach to checking for undef, we
  1363. /// may factor it into a common location.
  1364. static bool hasConcreteDef(Value *V) {
  1365. SmallPtrSet<Value*, 8> Visited;
  1366. Visited.insert(V);
  1367. return hasConcreteDefImpl(V, Visited, 0);
  1368. }
  1369. /// AlmostDeadIV - Return true if this IV has any uses other than the (soon to
  1370. /// be rewritten) loop exit test.
  1371. static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) {
  1372. int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
  1373. Value *IncV = Phi->getIncomingValue(LatchIdx);
  1374. for (User *U : Phi->users())
  1375. if (U != Cond && U != IncV) return false;
  1376. for (User *U : IncV->users())
  1377. if (U != Cond && U != Phi) return false;
  1378. return true;
  1379. }
  1380. /// FindLoopCounter - Find an affine IV in canonical form.
  1381. ///
  1382. /// BECount may be an i8* pointer type. The pointer difference is already
  1383. /// valid count without scaling the address stride, so it remains a pointer
  1384. /// expression as far as SCEV is concerned.
  1385. ///
  1386. /// Currently only valid for LFTR. See the comments on hasConcreteDef below.
  1387. ///
  1388. /// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount
  1389. ///
  1390. /// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride.
  1391. /// This is difficult in general for SCEV because of potential overflow. But we
  1392. /// could at least handle constant BECounts.
  1393. static PHINode *FindLoopCounter(Loop *L, const SCEV *BECount,
  1394. ScalarEvolution *SE, DominatorTree *DT) {
  1395. uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
  1396. Value *Cond =
  1397. cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition();
  1398. // Loop over all of the PHI nodes, looking for a simple counter.
  1399. PHINode *BestPhi = nullptr;
  1400. const SCEV *BestInit = nullptr;
  1401. BasicBlock *LatchBlock = L->getLoopLatch();
  1402. assert(LatchBlock && "needsLFTR should guarantee a loop latch");
  1403. for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
  1404. PHINode *Phi = cast<PHINode>(I);
  1405. if (!SE->isSCEVable(Phi->getType()))
  1406. continue;
  1407. // Avoid comparing an integer IV against a pointer Limit.
  1408. if (BECount->getType()->isPointerTy() && !Phi->getType()->isPointerTy())
  1409. continue;
  1410. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
  1411. if (!AR || AR->getLoop() != L || !AR->isAffine())
  1412. continue;
  1413. // AR may be a pointer type, while BECount is an integer type.
  1414. // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
  1415. // AR may not be a narrower type, or we may never exit.
  1416. uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
  1417. if (PhiWidth < BCWidth ||
  1418. !L->getHeader()->getModule()->getDataLayout().isLegalInteger(PhiWidth))
  1419. continue;
  1420. const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
  1421. if (!Step || !Step->isOne())
  1422. continue;
  1423. int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
  1424. Value *IncV = Phi->getIncomingValue(LatchIdx);
  1425. if (getLoopPhiForCounter(IncV, L, DT) != Phi)
  1426. continue;
  1427. // Avoid reusing a potentially undef value to compute other values that may
  1428. // have originally had a concrete definition.
  1429. if (!hasConcreteDef(Phi)) {
  1430. // We explicitly allow unknown phis as long as they are already used by
  1431. // the loop test. In this case we assume that performing LFTR could not
  1432. // increase the number of undef users.
  1433. if (ICmpInst *Cond = getLoopTest(L)) {
  1434. if (Phi != getLoopPhiForCounter(Cond->getOperand(0), L, DT)
  1435. && Phi != getLoopPhiForCounter(Cond->getOperand(1), L, DT)) {
  1436. continue;
  1437. }
  1438. }
  1439. }
  1440. const SCEV *Init = AR->getStart();
  1441. if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
  1442. // Don't force a live loop counter if another IV can be used.
  1443. if (AlmostDeadIV(Phi, LatchBlock, Cond))
  1444. continue;
  1445. // Prefer to count-from-zero. This is a more "canonical" counter form. It
  1446. // also prefers integer to pointer IVs.
  1447. if (BestInit->isZero() != Init->isZero()) {
  1448. if (BestInit->isZero())
  1449. continue;
  1450. }
  1451. // If two IVs both count from zero or both count from nonzero then the
  1452. // narrower is likely a dead phi that has been widened. Use the wider phi
  1453. // to allow the other to be eliminated.
  1454. else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
  1455. continue;
  1456. }
  1457. BestPhi = Phi;
  1458. BestInit = Init;
  1459. }
  1460. return BestPhi;
  1461. }
  1462. /// genLoopLimit - Help LinearFunctionTestReplace by generating a value that
  1463. /// holds the RHS of the new loop test.
  1464. static Value *genLoopLimit(PHINode *IndVar, const SCEV *IVCount, Loop *L,
  1465. SCEVExpander &Rewriter, ScalarEvolution *SE) {
  1466. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
  1467. assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter");
  1468. const SCEV *IVInit = AR->getStart();
  1469. // IVInit may be a pointer while IVCount is an integer when FindLoopCounter
  1470. // finds a valid pointer IV. Sign extend BECount in order to materialize a
  1471. // GEP. Avoid running SCEVExpander on a new pointer value, instead reusing
  1472. // the existing GEPs whenever possible.
  1473. if (IndVar->getType()->isPointerTy()
  1474. && !IVCount->getType()->isPointerTy()) {
  1475. // IVOffset will be the new GEP offset that is interpreted by GEP as a
  1476. // signed value. IVCount on the other hand represents the loop trip count,
  1477. // which is an unsigned value. FindLoopCounter only allows induction
  1478. // variables that have a positive unit stride of one. This means we don't
  1479. // have to handle the case of negative offsets (yet) and just need to zero
  1480. // extend IVCount.
  1481. Type *OfsTy = SE->getEffectiveSCEVType(IVInit->getType());
  1482. const SCEV *IVOffset = SE->getTruncateOrZeroExtend(IVCount, OfsTy);
  1483. // Expand the code for the iteration count.
  1484. assert(SE->isLoopInvariant(IVOffset, L) &&
  1485. "Computed iteration count is not loop invariant!");
  1486. BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
  1487. Value *GEPOffset = Rewriter.expandCodeFor(IVOffset, OfsTy, BI);
  1488. Value *GEPBase = IndVar->getIncomingValueForBlock(L->getLoopPreheader());
  1489. assert(AR->getStart() == SE->getSCEV(GEPBase) && "bad loop counter");
  1490. // We could handle pointer IVs other than i8*, but we need to compensate for
  1491. // gep index scaling. See canExpandBackedgeTakenCount comments.
  1492. assert(SE->getSizeOfExpr(IntegerType::getInt64Ty(IndVar->getContext()),
  1493. cast<PointerType>(GEPBase->getType())->getElementType())->isOne()
  1494. && "unit stride pointer IV must be i8*");
  1495. IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
  1496. return Builder.CreateGEP(nullptr, GEPBase, GEPOffset, "lftr.limit");
  1497. }
  1498. else {
  1499. // In any other case, convert both IVInit and IVCount to integers before
  1500. // comparing. This may result in SCEV expension of pointers, but in practice
  1501. // SCEV will fold the pointer arithmetic away as such:
  1502. // BECount = (IVEnd - IVInit - 1) => IVLimit = IVInit (postinc).
  1503. //
  1504. // Valid Cases: (1) both integers is most common; (2) both may be pointers
  1505. // for simple memset-style loops.
  1506. //
  1507. // IVInit integer and IVCount pointer would only occur if a canonical IV
  1508. // were generated on top of case #2, which is not expected.
  1509. const SCEV *IVLimit = nullptr;
  1510. // For unit stride, IVCount = Start + BECount with 2's complement overflow.
  1511. // For non-zero Start, compute IVCount here.
  1512. if (AR->getStart()->isZero())
  1513. IVLimit = IVCount;
  1514. else {
  1515. assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
  1516. const SCEV *IVInit = AR->getStart();
  1517. // For integer IVs, truncate the IV before computing IVInit + BECount.
  1518. if (SE->getTypeSizeInBits(IVInit->getType())
  1519. > SE->getTypeSizeInBits(IVCount->getType()))
  1520. IVInit = SE->getTruncateExpr(IVInit, IVCount->getType());
  1521. IVLimit = SE->getAddExpr(IVInit, IVCount);
  1522. }
  1523. // Expand the code for the iteration count.
  1524. BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
  1525. IRBuilder<> Builder(BI);
  1526. assert(SE->isLoopInvariant(IVLimit, L) &&
  1527. "Computed iteration count is not loop invariant!");
  1528. // Ensure that we generate the same type as IndVar, or a smaller integer
  1529. // type. In the presence of null pointer values, we have an integer type
  1530. // SCEV expression (IVInit) for a pointer type IV value (IndVar).
  1531. Type *LimitTy = IVCount->getType()->isPointerTy() ?
  1532. IndVar->getType() : IVCount->getType();
  1533. return Rewriter.expandCodeFor(IVLimit, LimitTy, BI);
  1534. }
  1535. }
  1536. /// LinearFunctionTestReplace - This method rewrites the exit condition of the
  1537. /// loop to be a canonical != comparison against the incremented loop induction
  1538. /// variable. This pass is able to rewrite the exit tests of any loop where the
  1539. /// SCEV analysis can determine a loop-invariant trip count of the loop, which
  1540. /// is actually a much broader range than just linear tests.
  1541. Value *IndVarSimplify::
  1542. LinearFunctionTestReplace(Loop *L,
  1543. const SCEV *BackedgeTakenCount,
  1544. PHINode *IndVar,
  1545. SCEVExpander &Rewriter) {
  1546. assert(canExpandBackedgeTakenCount(L, SE, Rewriter) && "precondition");
  1547. // Initialize CmpIndVar and IVCount to their preincremented values.
  1548. Value *CmpIndVar = IndVar;
  1549. const SCEV *IVCount = BackedgeTakenCount;
  1550. // If the exiting block is the same as the backedge block, we prefer to
  1551. // compare against the post-incremented value, otherwise we must compare
  1552. // against the preincremented value.
  1553. if (L->getExitingBlock() == L->getLoopLatch()) {
  1554. // Add one to the "backedge-taken" count to get the trip count.
  1555. // This addition may overflow, which is valid as long as the comparison is
  1556. // truncated to BackedgeTakenCount->getType().
  1557. IVCount = SE->getAddExpr(BackedgeTakenCount,
  1558. SE->getConstant(BackedgeTakenCount->getType(), 1));
  1559. // The BackedgeTaken expression contains the number of times that the
  1560. // backedge branches to the loop header. This is one less than the
  1561. // number of times the loop executes, so use the incremented indvar.
  1562. CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
  1563. }
  1564. Value *ExitCnt = genLoopLimit(IndVar, IVCount, L, Rewriter, SE);
  1565. assert(ExitCnt->getType()->isPointerTy() == IndVar->getType()->isPointerTy()
  1566. && "genLoopLimit missed a cast");
  1567. // Insert a new icmp_ne or icmp_eq instruction before the branch.
  1568. BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
  1569. ICmpInst::Predicate P;
  1570. if (L->contains(BI->getSuccessor(0)))
  1571. P = ICmpInst::ICMP_NE;
  1572. else
  1573. P = ICmpInst::ICMP_EQ;
  1574. DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
  1575. << " LHS:" << *CmpIndVar << '\n'
  1576. << " op:\t"
  1577. << (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
  1578. << " RHS:\t" << *ExitCnt << "\n"
  1579. << " IVCount:\t" << *IVCount << "\n");
  1580. IRBuilder<> Builder(BI);
  1581. // LFTR can ignore IV overflow and truncate to the width of
  1582. // BECount. This avoids materializing the add(zext(add)) expression.
  1583. unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->getType());
  1584. unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->getType());
  1585. if (CmpIndVarSize > ExitCntSize) {
  1586. const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
  1587. const SCEV *ARStart = AR->getStart();
  1588. const SCEV *ARStep = AR->getStepRecurrence(*SE);
  1589. // For constant IVCount, avoid truncation.
  1590. if (isa<SCEVConstant>(ARStart) && isa<SCEVConstant>(IVCount)) {
  1591. const APInt &Start = cast<SCEVConstant>(ARStart)->getValue()->getValue();
  1592. APInt Count = cast<SCEVConstant>(IVCount)->getValue()->getValue();
  1593. // Note that the post-inc value of BackedgeTakenCount may have overflowed
  1594. // above such that IVCount is now zero.
  1595. if (IVCount != BackedgeTakenCount && Count == 0) {
  1596. Count = APInt::getMaxValue(Count.getBitWidth()).zext(CmpIndVarSize);
  1597. ++Count;
  1598. }
  1599. else
  1600. Count = Count.zext(CmpIndVarSize);
  1601. APInt NewLimit;
  1602. if (cast<SCEVConstant>(ARStep)->getValue()->isNegative())
  1603. NewLimit = Start - Count;
  1604. else
  1605. NewLimit = Start + Count;
  1606. ExitCnt = ConstantInt::get(CmpIndVar->getType(), NewLimit);
  1607. DEBUG(dbgs() << " Widen RHS:\t" << *ExitCnt << "\n");
  1608. } else {
  1609. CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(),
  1610. "lftr.wideiv");
  1611. }
  1612. }
  1613. Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
  1614. Value *OrigCond = BI->getCondition();
  1615. // It's tempting to use replaceAllUsesWith here to fully replace the old
  1616. // comparison, but that's not immediately safe, since users of the old
  1617. // comparison may not be dominated by the new comparison. Instead, just
  1618. // update the branch to use the new comparison; in the common case this
  1619. // will make old comparison dead.
  1620. BI->setCondition(Cond);
  1621. DeadInsts.push_back(OrigCond);
  1622. ++NumLFTR;
  1623. Changed = true;
  1624. return Cond;
  1625. }
  1626. //===----------------------------------------------------------------------===//
  1627. // SinkUnusedInvariants. A late subpass to cleanup loop preheaders.
  1628. //===----------------------------------------------------------------------===//
  1629. /// If there's a single exit block, sink any loop-invariant values that
  1630. /// were defined in the preheader but not used inside the loop into the
  1631. /// exit block to reduce register pressure in the loop.
  1632. void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
  1633. BasicBlock *ExitBlock = L->getExitBlock();
  1634. if (!ExitBlock) return;
  1635. BasicBlock *Preheader = L->getLoopPreheader();
  1636. if (!Preheader) return;
  1637. Instruction *InsertPt = ExitBlock->getFirstInsertionPt();
  1638. BasicBlock::iterator I = Preheader->getTerminator();
  1639. while (I != Preheader->begin()) {
  1640. --I;
  1641. // New instructions were inserted at the end of the preheader.
  1642. if (isa<PHINode>(I))
  1643. break;
  1644. // Don't move instructions which might have side effects, since the side
  1645. // effects need to complete before instructions inside the loop. Also don't
  1646. // move instructions which might read memory, since the loop may modify
  1647. // memory. Note that it's okay if the instruction might have undefined
  1648. // behavior: LoopSimplify guarantees that the preheader dominates the exit
  1649. // block.
  1650. if (I->mayHaveSideEffects() || I->mayReadFromMemory())
  1651. continue;
  1652. // Skip debug info intrinsics.
  1653. if (isa<DbgInfoIntrinsic>(I))
  1654. continue;
  1655. // Skip landingpad instructions.
  1656. if (isa<LandingPadInst>(I))
  1657. continue;
  1658. // Don't sink alloca: we never want to sink static alloca's out of the
  1659. // entry block, and correctly sinking dynamic alloca's requires
  1660. // checks for stacksave/stackrestore intrinsics.
  1661. // FIXME: Refactor this check somehow?
  1662. if (isa<AllocaInst>(I))
  1663. continue;
  1664. // Determine if there is a use in or before the loop (direct or
  1665. // otherwise).
  1666. bool UsedInLoop = false;
  1667. for (Use &U : I->uses()) {
  1668. Instruction *User = cast<Instruction>(U.getUser());
  1669. BasicBlock *UseBB = User->getParent();
  1670. if (PHINode *P = dyn_cast<PHINode>(User)) {
  1671. unsigned i =
  1672. PHINode::getIncomingValueNumForOperand(U.getOperandNo());
  1673. UseBB = P->getIncomingBlock(i);
  1674. }
  1675. if (UseBB == Preheader || L->contains(UseBB)) {
  1676. UsedInLoop = true;
  1677. break;
  1678. }
  1679. }
  1680. // If there is, the def must remain in the preheader.
  1681. if (UsedInLoop)
  1682. continue;
  1683. // Otherwise, sink it to the exit block.
  1684. Instruction *ToMove = I;
  1685. bool Done = false;
  1686. if (I != Preheader->begin()) {
  1687. // Skip debug info intrinsics.
  1688. do {
  1689. --I;
  1690. } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
  1691. if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
  1692. Done = true;
  1693. } else {
  1694. Done = true;
  1695. }
  1696. ToMove->moveBefore(InsertPt);
  1697. if (Done) break;
  1698. InsertPt = ToMove;
  1699. }
  1700. }
  1701. //===----------------------------------------------------------------------===//
  1702. // IndVarSimplify driver. Manage several subpasses of IV simplification.
  1703. //===----------------------------------------------------------------------===//
  1704. bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
  1705. if (skipOptnoneFunction(L))
  1706. return false;
  1707. // If LoopSimplify form is not available, stay out of trouble. Some notes:
  1708. // - LSR currently only supports LoopSimplify-form loops. Indvars'
  1709. // canonicalization can be a pessimization without LSR to "clean up"
  1710. // afterwards.
  1711. // - We depend on having a preheader; in particular,
  1712. // Loop::getCanonicalInductionVariable only supports loops with preheaders,
  1713. // and we're in trouble if we can't find the induction variable even when
  1714. // we've manually inserted one.
  1715. if (!L->isLoopSimplifyForm())
  1716. return false;
  1717. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  1718. SE = &getAnalysis<ScalarEvolution>();
  1719. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1720. auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  1721. TLI = TLIP ? &TLIP->getTLI() : nullptr;
  1722. auto *TTIP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
  1723. TTI = TTIP ? &TTIP->getTTI(*L->getHeader()->getParent()) : nullptr;
  1724. const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
  1725. DeadInsts.clear();
  1726. Changed = false;
  1727. // If there are any floating-point recurrences, attempt to
  1728. // transform them to use integer recurrences.
  1729. RewriteNonIntegerIVs(L);
  1730. const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
  1731. // Create a rewriter object which we'll use to transform the code with.
  1732. SCEVExpander Rewriter(*SE, DL, "indvars");
  1733. #ifndef NDEBUG
  1734. Rewriter.setDebugType(DEBUG_TYPE);
  1735. #endif
  1736. // Eliminate redundant IV users.
  1737. //
  1738. // Simplification works best when run before other consumers of SCEV. We
  1739. // attempt to avoid evaluating SCEVs for sign/zero extend operations until
  1740. // other expressions involving loop IVs have been evaluated. This helps SCEV
  1741. // set no-wrap flags before normalizing sign/zero extension.
  1742. Rewriter.disableCanonicalMode();
  1743. SimplifyAndExtend(L, Rewriter, LPM);
  1744. // Check to see if this loop has a computable loop-invariant execution count.
  1745. // If so, this means that we can compute the final value of any expressions
  1746. // that are recurrent in the loop, and substitute the exit values from the
  1747. // loop into any instructions outside of the loop that use the final values of
  1748. // the current expressions.
  1749. //
  1750. if (ReplaceExitValue != NeverRepl &&
  1751. !isa<SCEVCouldNotCompute>(BackedgeTakenCount))
  1752. RewriteLoopExitValues(L, Rewriter);
  1753. // Eliminate redundant IV cycles.
  1754. NumElimIV += Rewriter.replaceCongruentIVs(L, DT, DeadInsts);
  1755. // If we have a trip count expression, rewrite the loop's exit condition
  1756. // using it. We can currently only handle loops with a single exit.
  1757. if (canExpandBackedgeTakenCount(L, SE, Rewriter) && needsLFTR(L, DT)) {
  1758. PHINode *IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT);
  1759. if (IndVar) {
  1760. // Check preconditions for proper SCEVExpander operation. SCEV does not
  1761. // express SCEVExpander's dependencies, such as LoopSimplify. Instead any
  1762. // pass that uses the SCEVExpander must do it. This does not work well for
  1763. // loop passes because SCEVExpander makes assumptions about all loops,
  1764. // while LoopPassManager only forces the current loop to be simplified.
  1765. //
  1766. // FIXME: SCEV expansion has no way to bail out, so the caller must
  1767. // explicitly check any assumptions made by SCEV. Brittle.
  1768. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount);
  1769. if (!AR || AR->getLoop()->getLoopPreheader())
  1770. (void)LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
  1771. Rewriter);
  1772. }
  1773. }
  1774. // Clear the rewriter cache, because values that are in the rewriter's cache
  1775. // can be deleted in the loop below, causing the AssertingVH in the cache to
  1776. // trigger.
  1777. Rewriter.clear();
  1778. // Now that we're done iterating through lists, clean up any instructions
  1779. // which are now dead.
  1780. while (!DeadInsts.empty())
  1781. if (Instruction *Inst =
  1782. dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
  1783. RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
  1784. // The Rewriter may not be used from this point on.
  1785. // Loop-invariant instructions in the preheader that aren't used in the
  1786. // loop may be sunk below the loop to reduce register pressure.
  1787. SinkUnusedInvariants(L);
  1788. // Clean up dead instructions.
  1789. Changed |= DeleteDeadPHIs(L->getHeader(), TLI);
  1790. // Check a post-condition.
  1791. assert(L->isLCSSAForm(*DT) &&
  1792. "Indvars did not leave the loop in lcssa form!");
  1793. #if 0 // HLSL Change Starts - option pending
  1794. // Verify that LFTR, and any other change have not interfered with SCEV's
  1795. // ability to compute trip count.
  1796. #ifndef NDEBUG
  1797. if (VerifyIndvars && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
  1798. SE->forgetLoop(L);
  1799. const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
  1800. if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
  1801. SE->getTypeSizeInBits(NewBECount->getType()))
  1802. NewBECount = SE->getTruncateOrNoop(NewBECount,
  1803. BackedgeTakenCount->getType());
  1804. else
  1805. BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
  1806. NewBECount->getType());
  1807. assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV");
  1808. }
  1809. #endif
  1810. #endif // HLSL Change Ends - option pending
  1811. return Changed;
  1812. }