IndVarSimplify.cpp 82 KB

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