ScalarEvolutionExpander.cpp 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806
  1. //===- ScalarEvolutionExpander.cpp - Scalar Evolution Analysis ------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains the implementation of the scalar evolution expander,
  10. // which is used to generate the code corresponding to a given scalar evolution
  11. // expression.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SmallSet.h"
  17. #include "llvm/Analysis/InstructionSimplify.h"
  18. #include "llvm/Analysis/LoopInfo.h"
  19. #include "llvm/Analysis/TargetTransformInfo.h"
  20. #include "llvm/Analysis/ValueTracking.h"
  21. #include "llvm/IR/DataLayout.h"
  22. #include "llvm/IR/Dominators.h"
  23. #include "llvm/IR/IntrinsicInst.h"
  24. #include "llvm/IR/LLVMContext.h"
  25. #include "llvm/IR/Module.h"
  26. #include "llvm/IR/PatternMatch.h"
  27. #include "llvm/Support/CommandLine.h"
  28. #include "llvm/Support/Debug.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include "llvm/Transforms/Utils/LoopUtils.h"
  31. #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
  32. #define SCEV_DEBUG_WITH_TYPE(TYPE, X) DEBUG_WITH_TYPE(TYPE, X)
  33. #else
  34. #define SCEV_DEBUG_WITH_TYPE(TYPE, X)
  35. #endif
  36. using namespace llvm;
  37. cl::opt<unsigned> llvm::SCEVCheapExpansionBudget(
  38. "scev-cheap-expansion-budget", cl::Hidden, cl::init(4),
  39. cl::desc("When performing SCEV expansion only if it is cheap to do, this "
  40. "controls the budget that is considered cheap (default = 4)"));
  41. using namespace PatternMatch;
  42. /// ReuseOrCreateCast - Arrange for there to be a cast of V to Ty at IP,
  43. /// reusing an existing cast if a suitable one (= dominating IP) exists, or
  44. /// creating a new one.
  45. Value *SCEVExpander::ReuseOrCreateCast(Value *V, Type *Ty,
  46. Instruction::CastOps Op,
  47. BasicBlock::iterator IP) {
  48. // This function must be called with the builder having a valid insertion
  49. // point. It doesn't need to be the actual IP where the uses of the returned
  50. // cast will be added, but it must dominate such IP.
  51. // We use this precondition to produce a cast that will dominate all its
  52. // uses. In particular, this is crucial for the case where the builder's
  53. // insertion point *is* the point where we were asked to put the cast.
  54. // Since we don't know the builder's insertion point is actually
  55. // where the uses will be added (only that it dominates it), we are
  56. // not allowed to move it.
  57. BasicBlock::iterator BIP = Builder.GetInsertPoint();
  58. Value *Ret = nullptr;
  59. // Check to see if there is already a cast!
  60. for (User *U : V->users()) {
  61. if (U->getType() != Ty)
  62. continue;
  63. CastInst *CI = dyn_cast<CastInst>(U);
  64. if (!CI || CI->getOpcode() != Op)
  65. continue;
  66. // Found a suitable cast that is at IP or comes before IP. Use it. Note that
  67. // the cast must also properly dominate the Builder's insertion point.
  68. if (IP->getParent() == CI->getParent() && &*BIP != CI &&
  69. (&*IP == CI || CI->comesBefore(&*IP))) {
  70. Ret = CI;
  71. break;
  72. }
  73. }
  74. // Create a new cast.
  75. if (!Ret) {
  76. SCEVInsertPointGuard Guard(Builder, this);
  77. Builder.SetInsertPoint(&*IP);
  78. Ret = Builder.CreateCast(Op, V, Ty, V->getName());
  79. }
  80. // We assert at the end of the function since IP might point to an
  81. // instruction with different dominance properties than a cast
  82. // (an invoke for example) and not dominate BIP (but the cast does).
  83. assert(!isa<Instruction>(Ret) ||
  84. SE.DT.dominates(cast<Instruction>(Ret), &*BIP));
  85. return Ret;
  86. }
  87. BasicBlock::iterator
  88. SCEVExpander::findInsertPointAfter(Instruction *I,
  89. Instruction *MustDominate) const {
  90. BasicBlock::iterator IP = ++I->getIterator();
  91. if (auto *II = dyn_cast<InvokeInst>(I))
  92. IP = II->getNormalDest()->begin();
  93. while (isa<PHINode>(IP))
  94. ++IP;
  95. if (isa<FuncletPadInst>(IP) || isa<LandingPadInst>(IP)) {
  96. ++IP;
  97. } else if (isa<CatchSwitchInst>(IP)) {
  98. IP = MustDominate->getParent()->getFirstInsertionPt();
  99. } else {
  100. assert(!IP->isEHPad() && "unexpected eh pad!");
  101. }
  102. // Adjust insert point to be after instructions inserted by the expander, so
  103. // we can re-use already inserted instructions. Avoid skipping past the
  104. // original \p MustDominate, in case it is an inserted instruction.
  105. while (isInsertedInstruction(&*IP) && &*IP != MustDominate)
  106. ++IP;
  107. return IP;
  108. }
  109. BasicBlock::iterator
  110. SCEVExpander::GetOptimalInsertionPointForCastOf(Value *V) const {
  111. // Cast the argument at the beginning of the entry block, after
  112. // any bitcasts of other arguments.
  113. if (Argument *A = dyn_cast<Argument>(V)) {
  114. BasicBlock::iterator IP = A->getParent()->getEntryBlock().begin();
  115. while ((isa<BitCastInst>(IP) &&
  116. isa<Argument>(cast<BitCastInst>(IP)->getOperand(0)) &&
  117. cast<BitCastInst>(IP)->getOperand(0) != A) ||
  118. isa<DbgInfoIntrinsic>(IP))
  119. ++IP;
  120. return IP;
  121. }
  122. // Cast the instruction immediately after the instruction.
  123. if (Instruction *I = dyn_cast<Instruction>(V))
  124. return findInsertPointAfter(I, &*Builder.GetInsertPoint());
  125. // Otherwise, this must be some kind of a constant,
  126. // so let's plop this cast into the function's entry block.
  127. assert(isa<Constant>(V) &&
  128. "Expected the cast argument to be a global/constant");
  129. return Builder.GetInsertBlock()
  130. ->getParent()
  131. ->getEntryBlock()
  132. .getFirstInsertionPt();
  133. }
  134. /// InsertNoopCastOfTo - Insert a cast of V to the specified type,
  135. /// which must be possible with a noop cast, doing what we can to share
  136. /// the casts.
  137. Value *SCEVExpander::InsertNoopCastOfTo(Value *V, Type *Ty) {
  138. Instruction::CastOps Op = CastInst::getCastOpcode(V, false, Ty, false);
  139. assert((Op == Instruction::BitCast ||
  140. Op == Instruction::PtrToInt ||
  141. Op == Instruction::IntToPtr) &&
  142. "InsertNoopCastOfTo cannot perform non-noop casts!");
  143. assert(SE.getTypeSizeInBits(V->getType()) == SE.getTypeSizeInBits(Ty) &&
  144. "InsertNoopCastOfTo cannot change sizes!");
  145. // inttoptr only works for integral pointers. For non-integral pointers, we
  146. // can create a GEP on i8* null with the integral value as index. Note that
  147. // it is safe to use GEP of null instead of inttoptr here, because only
  148. // expressions already based on a GEP of null should be converted to pointers
  149. // during expansion.
  150. if (Op == Instruction::IntToPtr) {
  151. auto *PtrTy = cast<PointerType>(Ty);
  152. if (DL.isNonIntegralPointerType(PtrTy)) {
  153. auto *Int8PtrTy = Builder.getInt8PtrTy(PtrTy->getAddressSpace());
  154. assert(DL.getTypeAllocSize(Builder.getInt8Ty()) == 1 &&
  155. "alloc size of i8 must by 1 byte for the GEP to be correct");
  156. auto *GEP = Builder.CreateGEP(
  157. Builder.getInt8Ty(), Constant::getNullValue(Int8PtrTy), V, "uglygep");
  158. return Builder.CreateBitCast(GEP, Ty);
  159. }
  160. }
  161. // Short-circuit unnecessary bitcasts.
  162. if (Op == Instruction::BitCast) {
  163. if (V->getType() == Ty)
  164. return V;
  165. if (CastInst *CI = dyn_cast<CastInst>(V)) {
  166. if (CI->getOperand(0)->getType() == Ty)
  167. return CI->getOperand(0);
  168. }
  169. }
  170. // Short-circuit unnecessary inttoptr<->ptrtoint casts.
  171. if ((Op == Instruction::PtrToInt || Op == Instruction::IntToPtr) &&
  172. SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(V->getType())) {
  173. if (CastInst *CI = dyn_cast<CastInst>(V))
  174. if ((CI->getOpcode() == Instruction::PtrToInt ||
  175. CI->getOpcode() == Instruction::IntToPtr) &&
  176. SE.getTypeSizeInBits(CI->getType()) ==
  177. SE.getTypeSizeInBits(CI->getOperand(0)->getType()))
  178. return CI->getOperand(0);
  179. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
  180. if ((CE->getOpcode() == Instruction::PtrToInt ||
  181. CE->getOpcode() == Instruction::IntToPtr) &&
  182. SE.getTypeSizeInBits(CE->getType()) ==
  183. SE.getTypeSizeInBits(CE->getOperand(0)->getType()))
  184. return CE->getOperand(0);
  185. }
  186. // Fold a cast of a constant.
  187. if (Constant *C = dyn_cast<Constant>(V))
  188. return ConstantExpr::getCast(Op, C, Ty);
  189. // Try to reuse existing cast, or insert one.
  190. return ReuseOrCreateCast(V, Ty, Op, GetOptimalInsertionPointForCastOf(V));
  191. }
  192. /// InsertBinop - Insert the specified binary operator, doing a small amount
  193. /// of work to avoid inserting an obviously redundant operation, and hoisting
  194. /// to an outer loop when the opportunity is there and it is safe.
  195. Value *SCEVExpander::InsertBinop(Instruction::BinaryOps Opcode,
  196. Value *LHS, Value *RHS,
  197. SCEV::NoWrapFlags Flags, bool IsSafeToHoist) {
  198. // Fold a binop with constant operands.
  199. if (Constant *CLHS = dyn_cast<Constant>(LHS))
  200. if (Constant *CRHS = dyn_cast<Constant>(RHS))
  201. return ConstantExpr::get(Opcode, CLHS, CRHS);
  202. // Do a quick scan to see if we have this binop nearby. If so, reuse it.
  203. unsigned ScanLimit = 6;
  204. BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
  205. // Scanning starts from the last instruction before the insertion point.
  206. BasicBlock::iterator IP = Builder.GetInsertPoint();
  207. if (IP != BlockBegin) {
  208. --IP;
  209. for (; ScanLimit; --IP, --ScanLimit) {
  210. // Don't count dbg.value against the ScanLimit, to avoid perturbing the
  211. // generated code.
  212. if (isa<DbgInfoIntrinsic>(IP))
  213. ScanLimit++;
  214. auto canGenerateIncompatiblePoison = [&Flags](Instruction *I) {
  215. // Ensure that no-wrap flags match.
  216. if (isa<OverflowingBinaryOperator>(I)) {
  217. if (I->hasNoSignedWrap() != (Flags & SCEV::FlagNSW))
  218. return true;
  219. if (I->hasNoUnsignedWrap() != (Flags & SCEV::FlagNUW))
  220. return true;
  221. }
  222. // Conservatively, do not use any instruction which has any of exact
  223. // flags installed.
  224. if (isa<PossiblyExactOperator>(I) && I->isExact())
  225. return true;
  226. return false;
  227. };
  228. if (IP->getOpcode() == (unsigned)Opcode && IP->getOperand(0) == LHS &&
  229. IP->getOperand(1) == RHS && !canGenerateIncompatiblePoison(&*IP))
  230. return &*IP;
  231. if (IP == BlockBegin) break;
  232. }
  233. }
  234. // Save the original insertion point so we can restore it when we're done.
  235. DebugLoc Loc = Builder.GetInsertPoint()->getDebugLoc();
  236. SCEVInsertPointGuard Guard(Builder, this);
  237. if (IsSafeToHoist) {
  238. // Move the insertion point out of as many loops as we can.
  239. while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
  240. if (!L->isLoopInvariant(LHS) || !L->isLoopInvariant(RHS)) break;
  241. BasicBlock *Preheader = L->getLoopPreheader();
  242. if (!Preheader) break;
  243. // Ok, move up a level.
  244. Builder.SetInsertPoint(Preheader->getTerminator());
  245. }
  246. }
  247. // If we haven't found this binop, insert it.
  248. Instruction *BO = cast<Instruction>(Builder.CreateBinOp(Opcode, LHS, RHS));
  249. BO->setDebugLoc(Loc);
  250. if (Flags & SCEV::FlagNUW)
  251. BO->setHasNoUnsignedWrap();
  252. if (Flags & SCEV::FlagNSW)
  253. BO->setHasNoSignedWrap();
  254. return BO;
  255. }
  256. /// FactorOutConstant - Test if S is divisible by Factor, using signed
  257. /// division. If so, update S with Factor divided out and return true.
  258. /// S need not be evenly divisible if a reasonable remainder can be
  259. /// computed.
  260. static bool FactorOutConstant(const SCEV *&S, const SCEV *&Remainder,
  261. const SCEV *Factor, ScalarEvolution &SE,
  262. const DataLayout &DL) {
  263. // Everything is divisible by one.
  264. if (Factor->isOne())
  265. return true;
  266. // x/x == 1.
  267. if (S == Factor) {
  268. S = SE.getConstant(S->getType(), 1);
  269. return true;
  270. }
  271. // For a Constant, check for a multiple of the given factor.
  272. if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
  273. // 0/x == 0.
  274. if (C->isZero())
  275. return true;
  276. // Check for divisibility.
  277. if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor)) {
  278. ConstantInt *CI =
  279. ConstantInt::get(SE.getContext(), C->getAPInt().sdiv(FC->getAPInt()));
  280. // If the quotient is zero and the remainder is non-zero, reject
  281. // the value at this scale. It will be considered for subsequent
  282. // smaller scales.
  283. if (!CI->isZero()) {
  284. const SCEV *Div = SE.getConstant(CI);
  285. S = Div;
  286. Remainder = SE.getAddExpr(
  287. Remainder, SE.getConstant(C->getAPInt().srem(FC->getAPInt())));
  288. return true;
  289. }
  290. }
  291. }
  292. // In a Mul, check if there is a constant operand which is a multiple
  293. // of the given factor.
  294. if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
  295. // Size is known, check if there is a constant operand which is a multiple
  296. // of the given factor. If so, we can factor it.
  297. if (const SCEVConstant *FC = dyn_cast<SCEVConstant>(Factor))
  298. if (const SCEVConstant *C = dyn_cast<SCEVConstant>(M->getOperand(0)))
  299. if (!C->getAPInt().srem(FC->getAPInt())) {
  300. SmallVector<const SCEV *, 4> NewMulOps(M->operands());
  301. NewMulOps[0] = SE.getConstant(C->getAPInt().sdiv(FC->getAPInt()));
  302. S = SE.getMulExpr(NewMulOps);
  303. return true;
  304. }
  305. }
  306. // In an AddRec, check if both start and step are divisible.
  307. if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
  308. const SCEV *Step = A->getStepRecurrence(SE);
  309. const SCEV *StepRem = SE.getConstant(Step->getType(), 0);
  310. if (!FactorOutConstant(Step, StepRem, Factor, SE, DL))
  311. return false;
  312. if (!StepRem->isZero())
  313. return false;
  314. const SCEV *Start = A->getStart();
  315. if (!FactorOutConstant(Start, Remainder, Factor, SE, DL))
  316. return false;
  317. S = SE.getAddRecExpr(Start, Step, A->getLoop(),
  318. A->getNoWrapFlags(SCEV::FlagNW));
  319. return true;
  320. }
  321. return false;
  322. }
  323. /// SimplifyAddOperands - Sort and simplify a list of add operands. NumAddRecs
  324. /// is the number of SCEVAddRecExprs present, which are kept at the end of
  325. /// the list.
  326. ///
  327. static void SimplifyAddOperands(SmallVectorImpl<const SCEV *> &Ops,
  328. Type *Ty,
  329. ScalarEvolution &SE) {
  330. unsigned NumAddRecs = 0;
  331. for (unsigned i = Ops.size(); i > 0 && isa<SCEVAddRecExpr>(Ops[i-1]); --i)
  332. ++NumAddRecs;
  333. // Group Ops into non-addrecs and addrecs.
  334. SmallVector<const SCEV *, 8> NoAddRecs(Ops.begin(), Ops.end() - NumAddRecs);
  335. SmallVector<const SCEV *, 8> AddRecs(Ops.end() - NumAddRecs, Ops.end());
  336. // Let ScalarEvolution sort and simplify the non-addrecs list.
  337. const SCEV *Sum = NoAddRecs.empty() ?
  338. SE.getConstant(Ty, 0) :
  339. SE.getAddExpr(NoAddRecs);
  340. // If it returned an add, use the operands. Otherwise it simplified
  341. // the sum into a single value, so just use that.
  342. Ops.clear();
  343. if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Sum))
  344. Ops.append(Add->op_begin(), Add->op_end());
  345. else if (!Sum->isZero())
  346. Ops.push_back(Sum);
  347. // Then append the addrecs.
  348. Ops.append(AddRecs.begin(), AddRecs.end());
  349. }
  350. /// SplitAddRecs - Flatten a list of add operands, moving addrec start values
  351. /// out to the top level. For example, convert {a + b,+,c} to a, b, {0,+,d}.
  352. /// This helps expose more opportunities for folding parts of the expressions
  353. /// into GEP indices.
  354. ///
  355. static void SplitAddRecs(SmallVectorImpl<const SCEV *> &Ops,
  356. Type *Ty,
  357. ScalarEvolution &SE) {
  358. // Find the addrecs.
  359. SmallVector<const SCEV *, 8> AddRecs;
  360. for (unsigned i = 0, e = Ops.size(); i != e; ++i)
  361. while (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(Ops[i])) {
  362. const SCEV *Start = A->getStart();
  363. if (Start->isZero()) break;
  364. const SCEV *Zero = SE.getConstant(Ty, 0);
  365. AddRecs.push_back(SE.getAddRecExpr(Zero,
  366. A->getStepRecurrence(SE),
  367. A->getLoop(),
  368. A->getNoWrapFlags(SCEV::FlagNW)));
  369. if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Start)) {
  370. Ops[i] = Zero;
  371. Ops.append(Add->op_begin(), Add->op_end());
  372. e += Add->getNumOperands();
  373. } else {
  374. Ops[i] = Start;
  375. }
  376. }
  377. if (!AddRecs.empty()) {
  378. // Add the addrecs onto the end of the list.
  379. Ops.append(AddRecs.begin(), AddRecs.end());
  380. // Resort the operand list, moving any constants to the front.
  381. SimplifyAddOperands(Ops, Ty, SE);
  382. }
  383. }
  384. /// expandAddToGEP - Expand an addition expression with a pointer type into
  385. /// a GEP instead of using ptrtoint+arithmetic+inttoptr. This helps
  386. /// BasicAliasAnalysis and other passes analyze the result. See the rules
  387. /// for getelementptr vs. inttoptr in
  388. /// http://llvm.org/docs/LangRef.html#pointeraliasing
  389. /// for details.
  390. ///
  391. /// Design note: The correctness of using getelementptr here depends on
  392. /// ScalarEvolution not recognizing inttoptr and ptrtoint operators, as
  393. /// they may introduce pointer arithmetic which may not be safely converted
  394. /// into getelementptr.
  395. ///
  396. /// Design note: It might seem desirable for this function to be more
  397. /// loop-aware. If some of the indices are loop-invariant while others
  398. /// aren't, it might seem desirable to emit multiple GEPs, keeping the
  399. /// loop-invariant portions of the overall computation outside the loop.
  400. /// However, there are a few reasons this is not done here. Hoisting simple
  401. /// arithmetic is a low-level optimization that often isn't very
  402. /// important until late in the optimization process. In fact, passes
  403. /// like InstructionCombining will combine GEPs, even if it means
  404. /// pushing loop-invariant computation down into loops, so even if the
  405. /// GEPs were split here, the work would quickly be undone. The
  406. /// LoopStrengthReduction pass, which is usually run quite late (and
  407. /// after the last InstructionCombining pass), takes care of hoisting
  408. /// loop-invariant portions of expressions, after considering what
  409. /// can be folded using target addressing modes.
  410. ///
  411. Value *SCEVExpander::expandAddToGEP(const SCEV *const *op_begin,
  412. const SCEV *const *op_end,
  413. PointerType *PTy,
  414. Type *Ty,
  415. Value *V) {
  416. SmallVector<Value *, 4> GepIndices;
  417. SmallVector<const SCEV *, 8> Ops(op_begin, op_end);
  418. bool AnyNonZeroIndices = false;
  419. // Split AddRecs up into parts as either of the parts may be usable
  420. // without the other.
  421. SplitAddRecs(Ops, Ty, SE);
  422. Type *IntIdxTy = DL.getIndexType(PTy);
  423. // For opaque pointers, always generate i8 GEP.
  424. if (!PTy->isOpaque()) {
  425. // Descend down the pointer's type and attempt to convert the other
  426. // operands into GEP indices, at each level. The first index in a GEP
  427. // indexes into the array implied by the pointer operand; the rest of
  428. // the indices index into the element or field type selected by the
  429. // preceding index.
  430. Type *ElTy = PTy->getNonOpaquePointerElementType();
  431. for (;;) {
  432. // If the scale size is not 0, attempt to factor out a scale for
  433. // array indexing.
  434. SmallVector<const SCEV *, 8> ScaledOps;
  435. if (ElTy->isSized()) {
  436. const SCEV *ElSize = SE.getSizeOfExpr(IntIdxTy, ElTy);
  437. if (!ElSize->isZero()) {
  438. SmallVector<const SCEV *, 8> NewOps;
  439. for (const SCEV *Op : Ops) {
  440. const SCEV *Remainder = SE.getConstant(Ty, 0);
  441. if (FactorOutConstant(Op, Remainder, ElSize, SE, DL)) {
  442. // Op now has ElSize factored out.
  443. ScaledOps.push_back(Op);
  444. if (!Remainder->isZero())
  445. NewOps.push_back(Remainder);
  446. AnyNonZeroIndices = true;
  447. } else {
  448. // The operand was not divisible, so add it to the list of
  449. // operands we'll scan next iteration.
  450. NewOps.push_back(Op);
  451. }
  452. }
  453. // If we made any changes, update Ops.
  454. if (!ScaledOps.empty()) {
  455. Ops = NewOps;
  456. SimplifyAddOperands(Ops, Ty, SE);
  457. }
  458. }
  459. }
  460. // Record the scaled array index for this level of the type. If
  461. // we didn't find any operands that could be factored, tentatively
  462. // assume that element zero was selected (since the zero offset
  463. // would obviously be folded away).
  464. Value *Scaled =
  465. ScaledOps.empty()
  466. ? Constant::getNullValue(Ty)
  467. : expandCodeForImpl(SE.getAddExpr(ScaledOps), Ty, false);
  468. GepIndices.push_back(Scaled);
  469. // Collect struct field index operands.
  470. while (StructType *STy = dyn_cast<StructType>(ElTy)) {
  471. bool FoundFieldNo = false;
  472. // An empty struct has no fields.
  473. if (STy->getNumElements() == 0) break;
  474. // Field offsets are known. See if a constant offset falls within any of
  475. // the struct fields.
  476. if (Ops.empty())
  477. break;
  478. if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[0]))
  479. if (SE.getTypeSizeInBits(C->getType()) <= 64) {
  480. const StructLayout &SL = *DL.getStructLayout(STy);
  481. uint64_t FullOffset = C->getValue()->getZExtValue();
  482. if (FullOffset < SL.getSizeInBytes()) {
  483. unsigned ElIdx = SL.getElementContainingOffset(FullOffset);
  484. GepIndices.push_back(
  485. ConstantInt::get(Type::getInt32Ty(Ty->getContext()), ElIdx));
  486. ElTy = STy->getTypeAtIndex(ElIdx);
  487. Ops[0] =
  488. SE.getConstant(Ty, FullOffset - SL.getElementOffset(ElIdx));
  489. AnyNonZeroIndices = true;
  490. FoundFieldNo = true;
  491. }
  492. }
  493. // If no struct field offsets were found, tentatively assume that
  494. // field zero was selected (since the zero offset would obviously
  495. // be folded away).
  496. if (!FoundFieldNo) {
  497. ElTy = STy->getTypeAtIndex(0u);
  498. GepIndices.push_back(
  499. Constant::getNullValue(Type::getInt32Ty(Ty->getContext())));
  500. }
  501. }
  502. if (ArrayType *ATy = dyn_cast<ArrayType>(ElTy))
  503. ElTy = ATy->getElementType();
  504. else
  505. // FIXME: Handle VectorType.
  506. // E.g., If ElTy is scalable vector, then ElSize is not a compile-time
  507. // constant, therefore can not be factored out. The generated IR is less
  508. // ideal with base 'V' cast to i8* and do ugly getelementptr over that.
  509. break;
  510. }
  511. }
  512. // If none of the operands were convertible to proper GEP indices, cast
  513. // the base to i8* and do an ugly getelementptr with that. It's still
  514. // better than ptrtoint+arithmetic+inttoptr at least.
  515. if (!AnyNonZeroIndices) {
  516. // Cast the base to i8*.
  517. if (!PTy->isOpaque())
  518. V = InsertNoopCastOfTo(V,
  519. Type::getInt8PtrTy(Ty->getContext(), PTy->getAddressSpace()));
  520. assert(!isa<Instruction>(V) ||
  521. SE.DT.dominates(cast<Instruction>(V), &*Builder.GetInsertPoint()));
  522. // Expand the operands for a plain byte offset.
  523. Value *Idx = expandCodeForImpl(SE.getAddExpr(Ops), Ty, false);
  524. // Fold a GEP with constant operands.
  525. if (Constant *CLHS = dyn_cast<Constant>(V))
  526. if (Constant *CRHS = dyn_cast<Constant>(Idx))
  527. return ConstantExpr::getGetElementPtr(Type::getInt8Ty(Ty->getContext()),
  528. CLHS, CRHS);
  529. // Do a quick scan to see if we have this GEP nearby. If so, reuse it.
  530. unsigned ScanLimit = 6;
  531. BasicBlock::iterator BlockBegin = Builder.GetInsertBlock()->begin();
  532. // Scanning starts from the last instruction before the insertion point.
  533. BasicBlock::iterator IP = Builder.GetInsertPoint();
  534. if (IP != BlockBegin) {
  535. --IP;
  536. for (; ScanLimit; --IP, --ScanLimit) {
  537. // Don't count dbg.value against the ScanLimit, to avoid perturbing the
  538. // generated code.
  539. if (isa<DbgInfoIntrinsic>(IP))
  540. ScanLimit++;
  541. if (IP->getOpcode() == Instruction::GetElementPtr &&
  542. IP->getOperand(0) == V && IP->getOperand(1) == Idx)
  543. return &*IP;
  544. if (IP == BlockBegin) break;
  545. }
  546. }
  547. // Save the original insertion point so we can restore it when we're done.
  548. SCEVInsertPointGuard Guard(Builder, this);
  549. // Move the insertion point out of as many loops as we can.
  550. while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
  551. if (!L->isLoopInvariant(V) || !L->isLoopInvariant(Idx)) break;
  552. BasicBlock *Preheader = L->getLoopPreheader();
  553. if (!Preheader) break;
  554. // Ok, move up a level.
  555. Builder.SetInsertPoint(Preheader->getTerminator());
  556. }
  557. // Emit a GEP.
  558. return Builder.CreateGEP(Builder.getInt8Ty(), V, Idx, "uglygep");
  559. }
  560. {
  561. SCEVInsertPointGuard Guard(Builder, this);
  562. // Move the insertion point out of as many loops as we can.
  563. while (const Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock())) {
  564. if (!L->isLoopInvariant(V)) break;
  565. bool AnyIndexNotLoopInvariant = any_of(
  566. GepIndices, [L](Value *Op) { return !L->isLoopInvariant(Op); });
  567. if (AnyIndexNotLoopInvariant)
  568. break;
  569. BasicBlock *Preheader = L->getLoopPreheader();
  570. if (!Preheader) break;
  571. // Ok, move up a level.
  572. Builder.SetInsertPoint(Preheader->getTerminator());
  573. }
  574. // Insert a pretty getelementptr. Note that this GEP is not marked inbounds,
  575. // because ScalarEvolution may have changed the address arithmetic to
  576. // compute a value which is beyond the end of the allocated object.
  577. Value *Casted = V;
  578. if (V->getType() != PTy)
  579. Casted = InsertNoopCastOfTo(Casted, PTy);
  580. Value *GEP = Builder.CreateGEP(PTy->getNonOpaquePointerElementType(),
  581. Casted, GepIndices, "scevgep");
  582. Ops.push_back(SE.getUnknown(GEP));
  583. }
  584. return expand(SE.getAddExpr(Ops));
  585. }
  586. Value *SCEVExpander::expandAddToGEP(const SCEV *Op, PointerType *PTy, Type *Ty,
  587. Value *V) {
  588. const SCEV *const Ops[1] = {Op};
  589. return expandAddToGEP(Ops, Ops + 1, PTy, Ty, V);
  590. }
  591. /// PickMostRelevantLoop - Given two loops pick the one that's most relevant for
  592. /// SCEV expansion. If they are nested, this is the most nested. If they are
  593. /// neighboring, pick the later.
  594. static const Loop *PickMostRelevantLoop(const Loop *A, const Loop *B,
  595. DominatorTree &DT) {
  596. if (!A) return B;
  597. if (!B) return A;
  598. if (A->contains(B)) return B;
  599. if (B->contains(A)) return A;
  600. if (DT.dominates(A->getHeader(), B->getHeader())) return B;
  601. if (DT.dominates(B->getHeader(), A->getHeader())) return A;
  602. return A; // Arbitrarily break the tie.
  603. }
  604. /// getRelevantLoop - Get the most relevant loop associated with the given
  605. /// expression, according to PickMostRelevantLoop.
  606. const Loop *SCEVExpander::getRelevantLoop(const SCEV *S) {
  607. // Test whether we've already computed the most relevant loop for this SCEV.
  608. auto Pair = RelevantLoops.insert(std::make_pair(S, nullptr));
  609. if (!Pair.second)
  610. return Pair.first->second;
  611. if (isa<SCEVConstant>(S))
  612. // A constant has no relevant loops.
  613. return nullptr;
  614. if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
  615. if (const Instruction *I = dyn_cast<Instruction>(U->getValue()))
  616. return Pair.first->second = SE.LI.getLoopFor(I->getParent());
  617. // A non-instruction has no relevant loops.
  618. return nullptr;
  619. }
  620. if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) {
  621. const Loop *L = nullptr;
  622. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
  623. L = AR->getLoop();
  624. for (const SCEV *Op : N->operands())
  625. L = PickMostRelevantLoop(L, getRelevantLoop(Op), SE.DT);
  626. return RelevantLoops[N] = L;
  627. }
  628. if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S)) {
  629. const Loop *Result = getRelevantLoop(C->getOperand());
  630. return RelevantLoops[C] = Result;
  631. }
  632. if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
  633. const Loop *Result = PickMostRelevantLoop(
  634. getRelevantLoop(D->getLHS()), getRelevantLoop(D->getRHS()), SE.DT);
  635. return RelevantLoops[D] = Result;
  636. }
  637. llvm_unreachable("Unexpected SCEV type!");
  638. }
  639. namespace {
  640. /// LoopCompare - Compare loops by PickMostRelevantLoop.
  641. class LoopCompare {
  642. DominatorTree &DT;
  643. public:
  644. explicit LoopCompare(DominatorTree &dt) : DT(dt) {}
  645. bool operator()(std::pair<const Loop *, const SCEV *> LHS,
  646. std::pair<const Loop *, const SCEV *> RHS) const {
  647. // Keep pointer operands sorted at the end.
  648. if (LHS.second->getType()->isPointerTy() !=
  649. RHS.second->getType()->isPointerTy())
  650. return LHS.second->getType()->isPointerTy();
  651. // Compare loops with PickMostRelevantLoop.
  652. if (LHS.first != RHS.first)
  653. return PickMostRelevantLoop(LHS.first, RHS.first, DT) != LHS.first;
  654. // If one operand is a non-constant negative and the other is not,
  655. // put the non-constant negative on the right so that a sub can
  656. // be used instead of a negate and add.
  657. if (LHS.second->isNonConstantNegative()) {
  658. if (!RHS.second->isNonConstantNegative())
  659. return false;
  660. } else if (RHS.second->isNonConstantNegative())
  661. return true;
  662. // Otherwise they are equivalent according to this comparison.
  663. return false;
  664. }
  665. };
  666. }
  667. Value *SCEVExpander::visitAddExpr(const SCEVAddExpr *S) {
  668. Type *Ty = SE.getEffectiveSCEVType(S->getType());
  669. // Collect all the add operands in a loop, along with their associated loops.
  670. // Iterate in reverse so that constants are emitted last, all else equal, and
  671. // so that pointer operands are inserted first, which the code below relies on
  672. // to form more involved GEPs.
  673. SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
  674. for (const SCEV *Op : reverse(S->operands()))
  675. OpsAndLoops.push_back(std::make_pair(getRelevantLoop(Op), Op));
  676. // Sort by loop. Use a stable sort so that constants follow non-constants and
  677. // pointer operands precede non-pointer operands.
  678. llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
  679. // Emit instructions to add all the operands. Hoist as much as possible
  680. // out of loops, and form meaningful getelementptrs where possible.
  681. Value *Sum = nullptr;
  682. for (auto I = OpsAndLoops.begin(), E = OpsAndLoops.end(); I != E;) {
  683. const Loop *CurLoop = I->first;
  684. const SCEV *Op = I->second;
  685. if (!Sum) {
  686. // This is the first operand. Just expand it.
  687. Sum = expand(Op);
  688. ++I;
  689. continue;
  690. }
  691. assert(!Op->getType()->isPointerTy() && "Only first op can be pointer");
  692. if (PointerType *PTy = dyn_cast<PointerType>(Sum->getType())) {
  693. // The running sum expression is a pointer. Try to form a getelementptr
  694. // at this level with that as the base.
  695. SmallVector<const SCEV *, 4> NewOps;
  696. for (; I != E && I->first == CurLoop; ++I) {
  697. // If the operand is SCEVUnknown and not instructions, peek through
  698. // it, to enable more of it to be folded into the GEP.
  699. const SCEV *X = I->second;
  700. if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(X))
  701. if (!isa<Instruction>(U->getValue()))
  702. X = SE.getSCEV(U->getValue());
  703. NewOps.push_back(X);
  704. }
  705. Sum = expandAddToGEP(NewOps.begin(), NewOps.end(), PTy, Ty, Sum);
  706. } else if (Op->isNonConstantNegative()) {
  707. // Instead of doing a negate and add, just do a subtract.
  708. Value *W = expandCodeForImpl(SE.getNegativeSCEV(Op), Ty, false);
  709. Sum = InsertNoopCastOfTo(Sum, Ty);
  710. Sum = InsertBinop(Instruction::Sub, Sum, W, SCEV::FlagAnyWrap,
  711. /*IsSafeToHoist*/ true);
  712. ++I;
  713. } else {
  714. // A simple add.
  715. Value *W = expandCodeForImpl(Op, Ty, false);
  716. Sum = InsertNoopCastOfTo(Sum, Ty);
  717. // Canonicalize a constant to the RHS.
  718. if (isa<Constant>(Sum)) std::swap(Sum, W);
  719. Sum = InsertBinop(Instruction::Add, Sum, W, S->getNoWrapFlags(),
  720. /*IsSafeToHoist*/ true);
  721. ++I;
  722. }
  723. }
  724. return Sum;
  725. }
  726. Value *SCEVExpander::visitMulExpr(const SCEVMulExpr *S) {
  727. Type *Ty = SE.getEffectiveSCEVType(S->getType());
  728. // Collect all the mul operands in a loop, along with their associated loops.
  729. // Iterate in reverse so that constants are emitted last, all else equal.
  730. SmallVector<std::pair<const Loop *, const SCEV *>, 8> OpsAndLoops;
  731. for (const SCEV *Op : reverse(S->operands()))
  732. OpsAndLoops.push_back(std::make_pair(getRelevantLoop(Op), Op));
  733. // Sort by loop. Use a stable sort so that constants follow non-constants.
  734. llvm::stable_sort(OpsAndLoops, LoopCompare(SE.DT));
  735. // Emit instructions to mul all the operands. Hoist as much as possible
  736. // out of loops.
  737. Value *Prod = nullptr;
  738. auto I = OpsAndLoops.begin();
  739. // Expand the calculation of X pow N in the following manner:
  740. // Let N = P1 + P2 + ... + PK, where all P are powers of 2. Then:
  741. // X pow N = (X pow P1) * (X pow P2) * ... * (X pow PK).
  742. const auto ExpandOpBinPowN = [this, &I, &OpsAndLoops, &Ty]() {
  743. auto E = I;
  744. // Calculate how many times the same operand from the same loop is included
  745. // into this power.
  746. uint64_t Exponent = 0;
  747. const uint64_t MaxExponent = UINT64_MAX >> 1;
  748. // No one sane will ever try to calculate such huge exponents, but if we
  749. // need this, we stop on UINT64_MAX / 2 because we need to exit the loop
  750. // below when the power of 2 exceeds our Exponent, and we want it to be
  751. // 1u << 31 at most to not deal with unsigned overflow.
  752. while (E != OpsAndLoops.end() && *I == *E && Exponent != MaxExponent) {
  753. ++Exponent;
  754. ++E;
  755. }
  756. assert(Exponent > 0 && "Trying to calculate a zeroth exponent of operand?");
  757. // Calculate powers with exponents 1, 2, 4, 8 etc. and include those of them
  758. // that are needed into the result.
  759. Value *P = expandCodeForImpl(I->second, Ty, false);
  760. Value *Result = nullptr;
  761. if (Exponent & 1)
  762. Result = P;
  763. for (uint64_t BinExp = 2; BinExp <= Exponent; BinExp <<= 1) {
  764. P = InsertBinop(Instruction::Mul, P, P, SCEV::FlagAnyWrap,
  765. /*IsSafeToHoist*/ true);
  766. if (Exponent & BinExp)
  767. Result = Result ? InsertBinop(Instruction::Mul, Result, P,
  768. SCEV::FlagAnyWrap,
  769. /*IsSafeToHoist*/ true)
  770. : P;
  771. }
  772. I = E;
  773. assert(Result && "Nothing was expanded?");
  774. return Result;
  775. };
  776. while (I != OpsAndLoops.end()) {
  777. if (!Prod) {
  778. // This is the first operand. Just expand it.
  779. Prod = ExpandOpBinPowN();
  780. } else if (I->second->isAllOnesValue()) {
  781. // Instead of doing a multiply by negative one, just do a negate.
  782. Prod = InsertNoopCastOfTo(Prod, Ty);
  783. Prod = InsertBinop(Instruction::Sub, Constant::getNullValue(Ty), Prod,
  784. SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true);
  785. ++I;
  786. } else {
  787. // A simple mul.
  788. Value *W = ExpandOpBinPowN();
  789. Prod = InsertNoopCastOfTo(Prod, Ty);
  790. // Canonicalize a constant to the RHS.
  791. if (isa<Constant>(Prod)) std::swap(Prod, W);
  792. const APInt *RHS;
  793. if (match(W, m_Power2(RHS))) {
  794. // Canonicalize Prod*(1<<C) to Prod<<C.
  795. assert(!Ty->isVectorTy() && "vector types are not SCEVable");
  796. auto NWFlags = S->getNoWrapFlags();
  797. // clear nsw flag if shl will produce poison value.
  798. if (RHS->logBase2() == RHS->getBitWidth() - 1)
  799. NWFlags = ScalarEvolution::clearFlags(NWFlags, SCEV::FlagNSW);
  800. Prod = InsertBinop(Instruction::Shl, Prod,
  801. ConstantInt::get(Ty, RHS->logBase2()), NWFlags,
  802. /*IsSafeToHoist*/ true);
  803. } else {
  804. Prod = InsertBinop(Instruction::Mul, Prod, W, S->getNoWrapFlags(),
  805. /*IsSafeToHoist*/ true);
  806. }
  807. }
  808. }
  809. return Prod;
  810. }
  811. Value *SCEVExpander::visitUDivExpr(const SCEVUDivExpr *S) {
  812. Type *Ty = SE.getEffectiveSCEVType(S->getType());
  813. Value *LHS = expandCodeForImpl(S->getLHS(), Ty, false);
  814. if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(S->getRHS())) {
  815. const APInt &RHS = SC->getAPInt();
  816. if (RHS.isPowerOf2())
  817. return InsertBinop(Instruction::LShr, LHS,
  818. ConstantInt::get(Ty, RHS.logBase2()),
  819. SCEV::FlagAnyWrap, /*IsSafeToHoist*/ true);
  820. }
  821. Value *RHS = expandCodeForImpl(S->getRHS(), Ty, false);
  822. return InsertBinop(Instruction::UDiv, LHS, RHS, SCEV::FlagAnyWrap,
  823. /*IsSafeToHoist*/ SE.isKnownNonZero(S->getRHS()));
  824. }
  825. /// Determine if this is a well-behaved chain of instructions leading back to
  826. /// the PHI. If so, it may be reused by expanded expressions.
  827. bool SCEVExpander::isNormalAddRecExprPHI(PHINode *PN, Instruction *IncV,
  828. const Loop *L) {
  829. if (IncV->getNumOperands() == 0 || isa<PHINode>(IncV) ||
  830. (isa<CastInst>(IncV) && !isa<BitCastInst>(IncV)))
  831. return false;
  832. // If any of the operands don't dominate the insert position, bail.
  833. // Addrec operands are always loop-invariant, so this can only happen
  834. // if there are instructions which haven't been hoisted.
  835. if (L == IVIncInsertLoop) {
  836. for (Use &Op : llvm::drop_begin(IncV->operands()))
  837. if (Instruction *OInst = dyn_cast<Instruction>(Op))
  838. if (!SE.DT.dominates(OInst, IVIncInsertPos))
  839. return false;
  840. }
  841. // Advance to the next instruction.
  842. IncV = dyn_cast<Instruction>(IncV->getOperand(0));
  843. if (!IncV)
  844. return false;
  845. if (IncV->mayHaveSideEffects())
  846. return false;
  847. if (IncV == PN)
  848. return true;
  849. return isNormalAddRecExprPHI(PN, IncV, L);
  850. }
  851. /// getIVIncOperand returns an induction variable increment's induction
  852. /// variable operand.
  853. ///
  854. /// If allowScale is set, any type of GEP is allowed as long as the nonIV
  855. /// operands dominate InsertPos.
  856. ///
  857. /// If allowScale is not set, ensure that a GEP increment conforms to one of the
  858. /// simple patterns generated by getAddRecExprPHILiterally and
  859. /// expandAddtoGEP. If the pattern isn't recognized, return NULL.
  860. Instruction *SCEVExpander::getIVIncOperand(Instruction *IncV,
  861. Instruction *InsertPos,
  862. bool allowScale) {
  863. if (IncV == InsertPos)
  864. return nullptr;
  865. switch (IncV->getOpcode()) {
  866. default:
  867. return nullptr;
  868. // Check for a simple Add/Sub or GEP of a loop invariant step.
  869. case Instruction::Add:
  870. case Instruction::Sub: {
  871. Instruction *OInst = dyn_cast<Instruction>(IncV->getOperand(1));
  872. if (!OInst || SE.DT.dominates(OInst, InsertPos))
  873. return dyn_cast<Instruction>(IncV->getOperand(0));
  874. return nullptr;
  875. }
  876. case Instruction::BitCast:
  877. return dyn_cast<Instruction>(IncV->getOperand(0));
  878. case Instruction::GetElementPtr:
  879. for (Use &U : llvm::drop_begin(IncV->operands())) {
  880. if (isa<Constant>(U))
  881. continue;
  882. if (Instruction *OInst = dyn_cast<Instruction>(U)) {
  883. if (!SE.DT.dominates(OInst, InsertPos))
  884. return nullptr;
  885. }
  886. if (allowScale) {
  887. // allow any kind of GEP as long as it can be hoisted.
  888. continue;
  889. }
  890. // This must be a pointer addition of constants (pretty), which is already
  891. // handled, or some number of address-size elements (ugly). Ugly geps
  892. // have 2 operands. i1* is used by the expander to represent an
  893. // address-size element.
  894. if (IncV->getNumOperands() != 2)
  895. return nullptr;
  896. unsigned AS = cast<PointerType>(IncV->getType())->getAddressSpace();
  897. if (IncV->getType() != Type::getInt1PtrTy(SE.getContext(), AS)
  898. && IncV->getType() != Type::getInt8PtrTy(SE.getContext(), AS))
  899. return nullptr;
  900. break;
  901. }
  902. return dyn_cast<Instruction>(IncV->getOperand(0));
  903. }
  904. }
  905. /// If the insert point of the current builder or any of the builders on the
  906. /// stack of saved builders has 'I' as its insert point, update it to point to
  907. /// the instruction after 'I'. This is intended to be used when the instruction
  908. /// 'I' is being moved. If this fixup is not done and 'I' is moved to a
  909. /// different block, the inconsistent insert point (with a mismatched
  910. /// Instruction and Block) can lead to an instruction being inserted in a block
  911. /// other than its parent.
  912. void SCEVExpander::fixupInsertPoints(Instruction *I) {
  913. BasicBlock::iterator It(*I);
  914. BasicBlock::iterator NewInsertPt = std::next(It);
  915. if (Builder.GetInsertPoint() == It)
  916. Builder.SetInsertPoint(&*NewInsertPt);
  917. for (auto *InsertPtGuard : InsertPointGuards)
  918. if (InsertPtGuard->GetInsertPoint() == It)
  919. InsertPtGuard->SetInsertPoint(NewInsertPt);
  920. }
  921. /// hoistStep - Attempt to hoist a simple IV increment above InsertPos to make
  922. /// it available to other uses in this loop. Recursively hoist any operands,
  923. /// until we reach a value that dominates InsertPos.
  924. bool SCEVExpander::hoistIVInc(Instruction *IncV, Instruction *InsertPos) {
  925. if (SE.DT.dominates(IncV, InsertPos))
  926. return true;
  927. // InsertPos must itself dominate IncV so that IncV's new position satisfies
  928. // its existing users.
  929. if (isa<PHINode>(InsertPos) ||
  930. !SE.DT.dominates(InsertPos->getParent(), IncV->getParent()))
  931. return false;
  932. if (!SE.LI.movementPreservesLCSSAForm(IncV, InsertPos))
  933. return false;
  934. // Check that the chain of IV operands leading back to Phi can be hoisted.
  935. SmallVector<Instruction*, 4> IVIncs;
  936. for(;;) {
  937. Instruction *Oper = getIVIncOperand(IncV, InsertPos, /*allowScale*/true);
  938. if (!Oper)
  939. return false;
  940. // IncV is safe to hoist.
  941. IVIncs.push_back(IncV);
  942. IncV = Oper;
  943. if (SE.DT.dominates(IncV, InsertPos))
  944. break;
  945. }
  946. for (Instruction *I : llvm::reverse(IVIncs)) {
  947. fixupInsertPoints(I);
  948. I->moveBefore(InsertPos);
  949. }
  950. return true;
  951. }
  952. /// Determine if this cyclic phi is in a form that would have been generated by
  953. /// LSR. We don't care if the phi was actually expanded in this pass, as long
  954. /// as it is in a low-cost form, for example, no implied multiplication. This
  955. /// should match any patterns generated by getAddRecExprPHILiterally and
  956. /// expandAddtoGEP.
  957. bool SCEVExpander::isExpandedAddRecExprPHI(PHINode *PN, Instruction *IncV,
  958. const Loop *L) {
  959. for(Instruction *IVOper = IncV;
  960. (IVOper = getIVIncOperand(IVOper, L->getLoopPreheader()->getTerminator(),
  961. /*allowScale=*/false));) {
  962. if (IVOper == PN)
  963. return true;
  964. }
  965. return false;
  966. }
  967. /// expandIVInc - Expand an IV increment at Builder's current InsertPos.
  968. /// Typically this is the LatchBlock terminator or IVIncInsertPos, but we may
  969. /// need to materialize IV increments elsewhere to handle difficult situations.
  970. Value *SCEVExpander::expandIVInc(PHINode *PN, Value *StepV, const Loop *L,
  971. Type *ExpandTy, Type *IntTy,
  972. bool useSubtract) {
  973. Value *IncV;
  974. // If the PHI is a pointer, use a GEP, otherwise use an add or sub.
  975. if (ExpandTy->isPointerTy()) {
  976. PointerType *GEPPtrTy = cast<PointerType>(ExpandTy);
  977. // If the step isn't constant, don't use an implicitly scaled GEP, because
  978. // that would require a multiply inside the loop.
  979. if (!isa<ConstantInt>(StepV))
  980. GEPPtrTy = PointerType::get(Type::getInt1Ty(SE.getContext()),
  981. GEPPtrTy->getAddressSpace());
  982. IncV = expandAddToGEP(SE.getSCEV(StepV), GEPPtrTy, IntTy, PN);
  983. if (IncV->getType() != PN->getType())
  984. IncV = Builder.CreateBitCast(IncV, PN->getType());
  985. } else {
  986. IncV = useSubtract ?
  987. Builder.CreateSub(PN, StepV, Twine(IVName) + ".iv.next") :
  988. Builder.CreateAdd(PN, StepV, Twine(IVName) + ".iv.next");
  989. }
  990. return IncV;
  991. }
  992. /// Check whether we can cheaply express the requested SCEV in terms of
  993. /// the available PHI SCEV by truncation and/or inversion of the step.
  994. static bool canBeCheaplyTransformed(ScalarEvolution &SE,
  995. const SCEVAddRecExpr *Phi,
  996. const SCEVAddRecExpr *Requested,
  997. bool &InvertStep) {
  998. // We can't transform to match a pointer PHI.
  999. if (Phi->getType()->isPointerTy())
  1000. return false;
  1001. Type *PhiTy = SE.getEffectiveSCEVType(Phi->getType());
  1002. Type *RequestedTy = SE.getEffectiveSCEVType(Requested->getType());
  1003. if (RequestedTy->getIntegerBitWidth() > PhiTy->getIntegerBitWidth())
  1004. return false;
  1005. // Try truncate it if necessary.
  1006. Phi = dyn_cast<SCEVAddRecExpr>(SE.getTruncateOrNoop(Phi, RequestedTy));
  1007. if (!Phi)
  1008. return false;
  1009. // Check whether truncation will help.
  1010. if (Phi == Requested) {
  1011. InvertStep = false;
  1012. return true;
  1013. }
  1014. // Check whether inverting will help: {R,+,-1} == R - {0,+,1}.
  1015. if (SE.getMinusSCEV(Requested->getStart(), Requested) == Phi) {
  1016. InvertStep = true;
  1017. return true;
  1018. }
  1019. return false;
  1020. }
  1021. static bool IsIncrementNSW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
  1022. if (!isa<IntegerType>(AR->getType()))
  1023. return false;
  1024. unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
  1025. Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
  1026. const SCEV *Step = AR->getStepRecurrence(SE);
  1027. const SCEV *OpAfterExtend = SE.getAddExpr(SE.getSignExtendExpr(Step, WideTy),
  1028. SE.getSignExtendExpr(AR, WideTy));
  1029. const SCEV *ExtendAfterOp =
  1030. SE.getSignExtendExpr(SE.getAddExpr(AR, Step), WideTy);
  1031. return ExtendAfterOp == OpAfterExtend;
  1032. }
  1033. static bool IsIncrementNUW(ScalarEvolution &SE, const SCEVAddRecExpr *AR) {
  1034. if (!isa<IntegerType>(AR->getType()))
  1035. return false;
  1036. unsigned BitWidth = cast<IntegerType>(AR->getType())->getBitWidth();
  1037. Type *WideTy = IntegerType::get(AR->getType()->getContext(), BitWidth * 2);
  1038. const SCEV *Step = AR->getStepRecurrence(SE);
  1039. const SCEV *OpAfterExtend = SE.getAddExpr(SE.getZeroExtendExpr(Step, WideTy),
  1040. SE.getZeroExtendExpr(AR, WideTy));
  1041. const SCEV *ExtendAfterOp =
  1042. SE.getZeroExtendExpr(SE.getAddExpr(AR, Step), WideTy);
  1043. return ExtendAfterOp == OpAfterExtend;
  1044. }
  1045. /// getAddRecExprPHILiterally - Helper for expandAddRecExprLiterally. Expand
  1046. /// the base addrec, which is the addrec without any non-loop-dominating
  1047. /// values, and return the PHI.
  1048. PHINode *
  1049. SCEVExpander::getAddRecExprPHILiterally(const SCEVAddRecExpr *Normalized,
  1050. const Loop *L,
  1051. Type *ExpandTy,
  1052. Type *IntTy,
  1053. Type *&TruncTy,
  1054. bool &InvertStep) {
  1055. assert((!IVIncInsertLoop||IVIncInsertPos) && "Uninitialized insert position");
  1056. // Reuse a previously-inserted PHI, if present.
  1057. BasicBlock *LatchBlock = L->getLoopLatch();
  1058. if (LatchBlock) {
  1059. PHINode *AddRecPhiMatch = nullptr;
  1060. Instruction *IncV = nullptr;
  1061. TruncTy = nullptr;
  1062. InvertStep = false;
  1063. // Only try partially matching scevs that need truncation and/or
  1064. // step-inversion if we know this loop is outside the current loop.
  1065. bool TryNonMatchingSCEV =
  1066. IVIncInsertLoop &&
  1067. SE.DT.properlyDominates(LatchBlock, IVIncInsertLoop->getHeader());
  1068. for (PHINode &PN : L->getHeader()->phis()) {
  1069. if (!SE.isSCEVable(PN.getType()))
  1070. continue;
  1071. // We should not look for a incomplete PHI. Getting SCEV for a incomplete
  1072. // PHI has no meaning at all.
  1073. if (!PN.isComplete()) {
  1074. SCEV_DEBUG_WITH_TYPE(
  1075. DebugType, dbgs() << "One incomplete PHI is found: " << PN << "\n");
  1076. continue;
  1077. }
  1078. const SCEVAddRecExpr *PhiSCEV = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(&PN));
  1079. if (!PhiSCEV)
  1080. continue;
  1081. bool IsMatchingSCEV = PhiSCEV == Normalized;
  1082. // We only handle truncation and inversion of phi recurrences for the
  1083. // expanded expression if the expanded expression's loop dominates the
  1084. // loop we insert to. Check now, so we can bail out early.
  1085. if (!IsMatchingSCEV && !TryNonMatchingSCEV)
  1086. continue;
  1087. // TODO: this possibly can be reworked to avoid this cast at all.
  1088. Instruction *TempIncV =
  1089. dyn_cast<Instruction>(PN.getIncomingValueForBlock(LatchBlock));
  1090. if (!TempIncV)
  1091. continue;
  1092. // Check whether we can reuse this PHI node.
  1093. if (LSRMode) {
  1094. if (!isExpandedAddRecExprPHI(&PN, TempIncV, L))
  1095. continue;
  1096. } else {
  1097. if (!isNormalAddRecExprPHI(&PN, TempIncV, L))
  1098. continue;
  1099. }
  1100. // Stop if we have found an exact match SCEV.
  1101. if (IsMatchingSCEV) {
  1102. IncV = TempIncV;
  1103. TruncTy = nullptr;
  1104. InvertStep = false;
  1105. AddRecPhiMatch = &PN;
  1106. break;
  1107. }
  1108. // Try whether the phi can be translated into the requested form
  1109. // (truncated and/or offset by a constant).
  1110. if ((!TruncTy || InvertStep) &&
  1111. canBeCheaplyTransformed(SE, PhiSCEV, Normalized, InvertStep)) {
  1112. // Record the phi node. But don't stop we might find an exact match
  1113. // later.
  1114. AddRecPhiMatch = &PN;
  1115. IncV = TempIncV;
  1116. TruncTy = SE.getEffectiveSCEVType(Normalized->getType());
  1117. }
  1118. }
  1119. if (AddRecPhiMatch) {
  1120. // Ok, the add recurrence looks usable.
  1121. // Remember this PHI, even in post-inc mode.
  1122. InsertedValues.insert(AddRecPhiMatch);
  1123. // Remember the increment.
  1124. rememberInstruction(IncV);
  1125. // Those values were not actually inserted but re-used.
  1126. ReusedValues.insert(AddRecPhiMatch);
  1127. ReusedValues.insert(IncV);
  1128. return AddRecPhiMatch;
  1129. }
  1130. }
  1131. // Save the original insertion point so we can restore it when we're done.
  1132. SCEVInsertPointGuard Guard(Builder, this);
  1133. // Another AddRec may need to be recursively expanded below. For example, if
  1134. // this AddRec is quadratic, the StepV may itself be an AddRec in this
  1135. // loop. Remove this loop from the PostIncLoops set before expanding such
  1136. // AddRecs. Otherwise, we cannot find a valid position for the step
  1137. // (i.e. StepV can never dominate its loop header). Ideally, we could do
  1138. // SavedIncLoops.swap(PostIncLoops), but we generally have a single element,
  1139. // so it's not worth implementing SmallPtrSet::swap.
  1140. PostIncLoopSet SavedPostIncLoops = PostIncLoops;
  1141. PostIncLoops.clear();
  1142. // Expand code for the start value into the loop preheader.
  1143. assert(L->getLoopPreheader() &&
  1144. "Can't expand add recurrences without a loop preheader!");
  1145. Value *StartV =
  1146. expandCodeForImpl(Normalized->getStart(), ExpandTy,
  1147. L->getLoopPreheader()->getTerminator(), false);
  1148. // StartV must have been be inserted into L's preheader to dominate the new
  1149. // phi.
  1150. assert(!isa<Instruction>(StartV) ||
  1151. SE.DT.properlyDominates(cast<Instruction>(StartV)->getParent(),
  1152. L->getHeader()));
  1153. // Expand code for the step value. Do this before creating the PHI so that PHI
  1154. // reuse code doesn't see an incomplete PHI.
  1155. const SCEV *Step = Normalized->getStepRecurrence(SE);
  1156. // If the stride is negative, insert a sub instead of an add for the increment
  1157. // (unless it's a constant, because subtracts of constants are canonicalized
  1158. // to adds).
  1159. bool useSubtract = !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
  1160. if (useSubtract)
  1161. Step = SE.getNegativeSCEV(Step);
  1162. // Expand the step somewhere that dominates the loop header.
  1163. Value *StepV = expandCodeForImpl(
  1164. Step, IntTy, &*L->getHeader()->getFirstInsertionPt(), false);
  1165. // The no-wrap behavior proved by IsIncrement(NUW|NSW) is only applicable if
  1166. // we actually do emit an addition. It does not apply if we emit a
  1167. // subtraction.
  1168. bool IncrementIsNUW = !useSubtract && IsIncrementNUW(SE, Normalized);
  1169. bool IncrementIsNSW = !useSubtract && IsIncrementNSW(SE, Normalized);
  1170. // Create the PHI.
  1171. BasicBlock *Header = L->getHeader();
  1172. Builder.SetInsertPoint(Header, Header->begin());
  1173. pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
  1174. PHINode *PN = Builder.CreatePHI(ExpandTy, std::distance(HPB, HPE),
  1175. Twine(IVName) + ".iv");
  1176. // Create the step instructions and populate the PHI.
  1177. for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
  1178. BasicBlock *Pred = *HPI;
  1179. // Add a start value.
  1180. if (!L->contains(Pred)) {
  1181. PN->addIncoming(StartV, Pred);
  1182. continue;
  1183. }
  1184. // Create a step value and add it to the PHI.
  1185. // If IVIncInsertLoop is non-null and equal to the addrec's loop, insert the
  1186. // instructions at IVIncInsertPos.
  1187. Instruction *InsertPos = L == IVIncInsertLoop ?
  1188. IVIncInsertPos : Pred->getTerminator();
  1189. Builder.SetInsertPoint(InsertPos);
  1190. Value *IncV = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
  1191. if (isa<OverflowingBinaryOperator>(IncV)) {
  1192. if (IncrementIsNUW)
  1193. cast<BinaryOperator>(IncV)->setHasNoUnsignedWrap();
  1194. if (IncrementIsNSW)
  1195. cast<BinaryOperator>(IncV)->setHasNoSignedWrap();
  1196. }
  1197. PN->addIncoming(IncV, Pred);
  1198. }
  1199. // After expanding subexpressions, restore the PostIncLoops set so the caller
  1200. // can ensure that IVIncrement dominates the current uses.
  1201. PostIncLoops = SavedPostIncLoops;
  1202. // Remember this PHI, even in post-inc mode. LSR SCEV-based salvaging is most
  1203. // effective when we are able to use an IV inserted here, so record it.
  1204. InsertedValues.insert(PN);
  1205. InsertedIVs.push_back(PN);
  1206. return PN;
  1207. }
  1208. Value *SCEVExpander::expandAddRecExprLiterally(const SCEVAddRecExpr *S) {
  1209. Type *STy = S->getType();
  1210. Type *IntTy = SE.getEffectiveSCEVType(STy);
  1211. const Loop *L = S->getLoop();
  1212. // Determine a normalized form of this expression, which is the expression
  1213. // before any post-inc adjustment is made.
  1214. const SCEVAddRecExpr *Normalized = S;
  1215. if (PostIncLoops.count(L)) {
  1216. PostIncLoopSet Loops;
  1217. Loops.insert(L);
  1218. Normalized = cast<SCEVAddRecExpr>(normalizeForPostIncUse(S, Loops, SE));
  1219. }
  1220. // Strip off any non-loop-dominating component from the addrec start.
  1221. const SCEV *Start = Normalized->getStart();
  1222. const SCEV *PostLoopOffset = nullptr;
  1223. if (!SE.properlyDominates(Start, L->getHeader())) {
  1224. PostLoopOffset = Start;
  1225. Start = SE.getConstant(Normalized->getType(), 0);
  1226. Normalized = cast<SCEVAddRecExpr>(
  1227. SE.getAddRecExpr(Start, Normalized->getStepRecurrence(SE),
  1228. Normalized->getLoop(),
  1229. Normalized->getNoWrapFlags(SCEV::FlagNW)));
  1230. }
  1231. // Strip off any non-loop-dominating component from the addrec step.
  1232. const SCEV *Step = Normalized->getStepRecurrence(SE);
  1233. const SCEV *PostLoopScale = nullptr;
  1234. if (!SE.dominates(Step, L->getHeader())) {
  1235. PostLoopScale = Step;
  1236. Step = SE.getConstant(Normalized->getType(), 1);
  1237. if (!Start->isZero()) {
  1238. // The normalization below assumes that Start is constant zero, so if
  1239. // it isn't re-associate Start to PostLoopOffset.
  1240. assert(!PostLoopOffset && "Start not-null but PostLoopOffset set?");
  1241. PostLoopOffset = Start;
  1242. Start = SE.getConstant(Normalized->getType(), 0);
  1243. }
  1244. Normalized =
  1245. cast<SCEVAddRecExpr>(SE.getAddRecExpr(
  1246. Start, Step, Normalized->getLoop(),
  1247. Normalized->getNoWrapFlags(SCEV::FlagNW)));
  1248. }
  1249. // Expand the core addrec. If we need post-loop scaling, force it to
  1250. // expand to an integer type to avoid the need for additional casting.
  1251. Type *ExpandTy = PostLoopScale ? IntTy : STy;
  1252. // We can't use a pointer type for the addrec if the pointer type is
  1253. // non-integral.
  1254. Type *AddRecPHIExpandTy =
  1255. DL.isNonIntegralPointerType(STy) ? Normalized->getType() : ExpandTy;
  1256. // In some cases, we decide to reuse an existing phi node but need to truncate
  1257. // it and/or invert the step.
  1258. Type *TruncTy = nullptr;
  1259. bool InvertStep = false;
  1260. PHINode *PN = getAddRecExprPHILiterally(Normalized, L, AddRecPHIExpandTy,
  1261. IntTy, TruncTy, InvertStep);
  1262. // Accommodate post-inc mode, if necessary.
  1263. Value *Result;
  1264. if (!PostIncLoops.count(L))
  1265. Result = PN;
  1266. else {
  1267. // In PostInc mode, use the post-incremented value.
  1268. BasicBlock *LatchBlock = L->getLoopLatch();
  1269. assert(LatchBlock && "PostInc mode requires a unique loop latch!");
  1270. Result = PN->getIncomingValueForBlock(LatchBlock);
  1271. // We might be introducing a new use of the post-inc IV that is not poison
  1272. // safe, in which case we should drop poison generating flags. Only keep
  1273. // those flags for which SCEV has proven that they always hold.
  1274. if (isa<OverflowingBinaryOperator>(Result)) {
  1275. auto *I = cast<Instruction>(Result);
  1276. if (!S->hasNoUnsignedWrap())
  1277. I->setHasNoUnsignedWrap(false);
  1278. if (!S->hasNoSignedWrap())
  1279. I->setHasNoSignedWrap(false);
  1280. }
  1281. // For an expansion to use the postinc form, the client must call
  1282. // expandCodeFor with an InsertPoint that is either outside the PostIncLoop
  1283. // or dominated by IVIncInsertPos.
  1284. if (isa<Instruction>(Result) &&
  1285. !SE.DT.dominates(cast<Instruction>(Result),
  1286. &*Builder.GetInsertPoint())) {
  1287. // The induction variable's postinc expansion does not dominate this use.
  1288. // IVUsers tries to prevent this case, so it is rare. However, it can
  1289. // happen when an IVUser outside the loop is not dominated by the latch
  1290. // block. Adjusting IVIncInsertPos before expansion begins cannot handle
  1291. // all cases. Consider a phi outside whose operand is replaced during
  1292. // expansion with the value of the postinc user. Without fundamentally
  1293. // changing the way postinc users are tracked, the only remedy is
  1294. // inserting an extra IV increment. StepV might fold into PostLoopOffset,
  1295. // but hopefully expandCodeFor handles that.
  1296. bool useSubtract =
  1297. !ExpandTy->isPointerTy() && Step->isNonConstantNegative();
  1298. if (useSubtract)
  1299. Step = SE.getNegativeSCEV(Step);
  1300. Value *StepV;
  1301. {
  1302. // Expand the step somewhere that dominates the loop header.
  1303. SCEVInsertPointGuard Guard(Builder, this);
  1304. StepV = expandCodeForImpl(
  1305. Step, IntTy, &*L->getHeader()->getFirstInsertionPt(), false);
  1306. }
  1307. Result = expandIVInc(PN, StepV, L, ExpandTy, IntTy, useSubtract);
  1308. }
  1309. }
  1310. // We have decided to reuse an induction variable of a dominating loop. Apply
  1311. // truncation and/or inversion of the step.
  1312. if (TruncTy) {
  1313. Type *ResTy = Result->getType();
  1314. // Normalize the result type.
  1315. if (ResTy != SE.getEffectiveSCEVType(ResTy))
  1316. Result = InsertNoopCastOfTo(Result, SE.getEffectiveSCEVType(ResTy));
  1317. // Truncate the result.
  1318. if (TruncTy != Result->getType())
  1319. Result = Builder.CreateTrunc(Result, TruncTy);
  1320. // Invert the result.
  1321. if (InvertStep)
  1322. Result = Builder.CreateSub(
  1323. expandCodeForImpl(Normalized->getStart(), TruncTy, false), Result);
  1324. }
  1325. // Re-apply any non-loop-dominating scale.
  1326. if (PostLoopScale) {
  1327. assert(S->isAffine() && "Can't linearly scale non-affine recurrences.");
  1328. Result = InsertNoopCastOfTo(Result, IntTy);
  1329. Result = Builder.CreateMul(Result,
  1330. expandCodeForImpl(PostLoopScale, IntTy, false));
  1331. }
  1332. // Re-apply any non-loop-dominating offset.
  1333. if (PostLoopOffset) {
  1334. if (PointerType *PTy = dyn_cast<PointerType>(ExpandTy)) {
  1335. if (Result->getType()->isIntegerTy()) {
  1336. Value *Base = expandCodeForImpl(PostLoopOffset, ExpandTy, false);
  1337. Result = expandAddToGEP(SE.getUnknown(Result), PTy, IntTy, Base);
  1338. } else {
  1339. Result = expandAddToGEP(PostLoopOffset, PTy, IntTy, Result);
  1340. }
  1341. } else {
  1342. Result = InsertNoopCastOfTo(Result, IntTy);
  1343. Result = Builder.CreateAdd(
  1344. Result, expandCodeForImpl(PostLoopOffset, IntTy, false));
  1345. }
  1346. }
  1347. return Result;
  1348. }
  1349. Value *SCEVExpander::visitAddRecExpr(const SCEVAddRecExpr *S) {
  1350. // In canonical mode we compute the addrec as an expression of a canonical IV
  1351. // using evaluateAtIteration and expand the resulting SCEV expression. This
  1352. // way we avoid introducing new IVs to carry on the comutation of the addrec
  1353. // throughout the loop.
  1354. //
  1355. // For nested addrecs evaluateAtIteration might need a canonical IV of a
  1356. // type wider than the addrec itself. Emitting a canonical IV of the
  1357. // proper type might produce non-legal types, for example expanding an i64
  1358. // {0,+,2,+,1} addrec would need an i65 canonical IV. To avoid this just fall
  1359. // back to non-canonical mode for nested addrecs.
  1360. if (!CanonicalMode || (S->getNumOperands() > 2))
  1361. return expandAddRecExprLiterally(S);
  1362. Type *Ty = SE.getEffectiveSCEVType(S->getType());
  1363. const Loop *L = S->getLoop();
  1364. // First check for an existing canonical IV in a suitable type.
  1365. PHINode *CanonicalIV = nullptr;
  1366. if (PHINode *PN = L->getCanonicalInductionVariable())
  1367. if (SE.getTypeSizeInBits(PN->getType()) >= SE.getTypeSizeInBits(Ty))
  1368. CanonicalIV = PN;
  1369. // Rewrite an AddRec in terms of the canonical induction variable, if
  1370. // its type is more narrow.
  1371. if (CanonicalIV &&
  1372. SE.getTypeSizeInBits(CanonicalIV->getType()) > SE.getTypeSizeInBits(Ty) &&
  1373. !S->getType()->isPointerTy()) {
  1374. SmallVector<const SCEV *, 4> NewOps(S->getNumOperands());
  1375. for (unsigned i = 0, e = S->getNumOperands(); i != e; ++i)
  1376. NewOps[i] = SE.getAnyExtendExpr(S->op_begin()[i], CanonicalIV->getType());
  1377. Value *V = expand(SE.getAddRecExpr(NewOps, S->getLoop(),
  1378. S->getNoWrapFlags(SCEV::FlagNW)));
  1379. BasicBlock::iterator NewInsertPt =
  1380. findInsertPointAfter(cast<Instruction>(V), &*Builder.GetInsertPoint());
  1381. V = expandCodeForImpl(SE.getTruncateExpr(SE.getUnknown(V), Ty), nullptr,
  1382. &*NewInsertPt, false);
  1383. return V;
  1384. }
  1385. // {X,+,F} --> X + {0,+,F}
  1386. if (!S->getStart()->isZero()) {
  1387. if (PointerType *PTy = dyn_cast<PointerType>(S->getType())) {
  1388. Value *StartV = expand(SE.getPointerBase(S));
  1389. assert(StartV->getType() == PTy && "Pointer type mismatch for GEP!");
  1390. return expandAddToGEP(SE.removePointerBase(S), PTy, Ty, StartV);
  1391. }
  1392. SmallVector<const SCEV *, 4> NewOps(S->operands());
  1393. NewOps[0] = SE.getConstant(Ty, 0);
  1394. const SCEV *Rest = SE.getAddRecExpr(NewOps, L,
  1395. S->getNoWrapFlags(SCEV::FlagNW));
  1396. // Just do a normal add. Pre-expand the operands to suppress folding.
  1397. //
  1398. // The LHS and RHS values are factored out of the expand call to make the
  1399. // output independent of the argument evaluation order.
  1400. const SCEV *AddExprLHS = SE.getUnknown(expand(S->getStart()));
  1401. const SCEV *AddExprRHS = SE.getUnknown(expand(Rest));
  1402. return expand(SE.getAddExpr(AddExprLHS, AddExprRHS));
  1403. }
  1404. // If we don't yet have a canonical IV, create one.
  1405. if (!CanonicalIV) {
  1406. // Create and insert the PHI node for the induction variable in the
  1407. // specified loop.
  1408. BasicBlock *Header = L->getHeader();
  1409. pred_iterator HPB = pred_begin(Header), HPE = pred_end(Header);
  1410. CanonicalIV = PHINode::Create(Ty, std::distance(HPB, HPE), "indvar",
  1411. &Header->front());
  1412. rememberInstruction(CanonicalIV);
  1413. SmallSet<BasicBlock *, 4> PredSeen;
  1414. Constant *One = ConstantInt::get(Ty, 1);
  1415. for (pred_iterator HPI = HPB; HPI != HPE; ++HPI) {
  1416. BasicBlock *HP = *HPI;
  1417. if (!PredSeen.insert(HP).second) {
  1418. // There must be an incoming value for each predecessor, even the
  1419. // duplicates!
  1420. CanonicalIV->addIncoming(CanonicalIV->getIncomingValueForBlock(HP), HP);
  1421. continue;
  1422. }
  1423. if (L->contains(HP)) {
  1424. // Insert a unit add instruction right before the terminator
  1425. // corresponding to the back-edge.
  1426. Instruction *Add = BinaryOperator::CreateAdd(CanonicalIV, One,
  1427. "indvar.next",
  1428. HP->getTerminator());
  1429. Add->setDebugLoc(HP->getTerminator()->getDebugLoc());
  1430. rememberInstruction(Add);
  1431. CanonicalIV->addIncoming(Add, HP);
  1432. } else {
  1433. CanonicalIV->addIncoming(Constant::getNullValue(Ty), HP);
  1434. }
  1435. }
  1436. }
  1437. // {0,+,1} --> Insert a canonical induction variable into the loop!
  1438. if (S->isAffine() && S->getOperand(1)->isOne()) {
  1439. assert(Ty == SE.getEffectiveSCEVType(CanonicalIV->getType()) &&
  1440. "IVs with types different from the canonical IV should "
  1441. "already have been handled!");
  1442. return CanonicalIV;
  1443. }
  1444. // {0,+,F} --> {0,+,1} * F
  1445. // If this is a simple linear addrec, emit it now as a special case.
  1446. if (S->isAffine()) // {0,+,F} --> i*F
  1447. return
  1448. expand(SE.getTruncateOrNoop(
  1449. SE.getMulExpr(SE.getUnknown(CanonicalIV),
  1450. SE.getNoopOrAnyExtend(S->getOperand(1),
  1451. CanonicalIV->getType())),
  1452. Ty));
  1453. // If this is a chain of recurrences, turn it into a closed form, using the
  1454. // folders, then expandCodeFor the closed form. This allows the folders to
  1455. // simplify the expression without having to build a bunch of special code
  1456. // into this folder.
  1457. const SCEV *IH = SE.getUnknown(CanonicalIV); // Get I as a "symbolic" SCEV.
  1458. // Promote S up to the canonical IV type, if the cast is foldable.
  1459. const SCEV *NewS = S;
  1460. const SCEV *Ext = SE.getNoopOrAnyExtend(S, CanonicalIV->getType());
  1461. if (isa<SCEVAddRecExpr>(Ext))
  1462. NewS = Ext;
  1463. const SCEV *V = cast<SCEVAddRecExpr>(NewS)->evaluateAtIteration(IH, SE);
  1464. //cerr << "Evaluated: " << *this << "\n to: " << *V << "\n";
  1465. // Truncate the result down to the original type, if needed.
  1466. const SCEV *T = SE.getTruncateOrNoop(V, Ty);
  1467. return expand(T);
  1468. }
  1469. Value *SCEVExpander::visitPtrToIntExpr(const SCEVPtrToIntExpr *S) {
  1470. Value *V =
  1471. expandCodeForImpl(S->getOperand(), S->getOperand()->getType(), false);
  1472. return ReuseOrCreateCast(V, S->getType(), CastInst::PtrToInt,
  1473. GetOptimalInsertionPointForCastOf(V));
  1474. }
  1475. Value *SCEVExpander::visitTruncateExpr(const SCEVTruncateExpr *S) {
  1476. Type *Ty = SE.getEffectiveSCEVType(S->getType());
  1477. Value *V = expandCodeForImpl(
  1478. S->getOperand(), SE.getEffectiveSCEVType(S->getOperand()->getType()),
  1479. false);
  1480. return Builder.CreateTrunc(V, Ty);
  1481. }
  1482. Value *SCEVExpander::visitZeroExtendExpr(const SCEVZeroExtendExpr *S) {
  1483. Type *Ty = SE.getEffectiveSCEVType(S->getType());
  1484. Value *V = expandCodeForImpl(
  1485. S->getOperand(), SE.getEffectiveSCEVType(S->getOperand()->getType()),
  1486. false);
  1487. return Builder.CreateZExt(V, Ty);
  1488. }
  1489. Value *SCEVExpander::visitSignExtendExpr(const SCEVSignExtendExpr *S) {
  1490. Type *Ty = SE.getEffectiveSCEVType(S->getType());
  1491. Value *V = expandCodeForImpl(
  1492. S->getOperand(), SE.getEffectiveSCEVType(S->getOperand()->getType()),
  1493. false);
  1494. return Builder.CreateSExt(V, Ty);
  1495. }
  1496. Value *SCEVExpander::expandSMaxExpr(const SCEVNAryExpr *S) {
  1497. Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
  1498. Type *Ty = LHS->getType();
  1499. for (int i = S->getNumOperands()-2; i >= 0; --i) {
  1500. // In the case of mixed integer and pointer types, do the
  1501. // rest of the comparisons as integer.
  1502. Type *OpTy = S->getOperand(i)->getType();
  1503. if (OpTy->isIntegerTy() != Ty->isIntegerTy()) {
  1504. Ty = SE.getEffectiveSCEVType(Ty);
  1505. LHS = InsertNoopCastOfTo(LHS, Ty);
  1506. }
  1507. Value *RHS = expandCodeForImpl(S->getOperand(i), Ty, false);
  1508. Value *Sel;
  1509. if (Ty->isIntegerTy())
  1510. Sel = Builder.CreateIntrinsic(Intrinsic::smax, {Ty}, {LHS, RHS},
  1511. /*FMFSource=*/nullptr, "smax");
  1512. else {
  1513. Value *ICmp = Builder.CreateICmpSGT(LHS, RHS);
  1514. Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smax");
  1515. }
  1516. LHS = Sel;
  1517. }
  1518. // In the case of mixed integer and pointer types, cast the
  1519. // final result back to the pointer type.
  1520. if (LHS->getType() != S->getType())
  1521. LHS = InsertNoopCastOfTo(LHS, S->getType());
  1522. return LHS;
  1523. }
  1524. Value *SCEVExpander::expandUMaxExpr(const SCEVNAryExpr *S) {
  1525. Value *LHS = expand(S->getOperand(S->getNumOperands()-1));
  1526. Type *Ty = LHS->getType();
  1527. for (int i = S->getNumOperands()-2; i >= 0; --i) {
  1528. // In the case of mixed integer and pointer types, do the
  1529. // rest of the comparisons as integer.
  1530. Type *OpTy = S->getOperand(i)->getType();
  1531. if (OpTy->isIntegerTy() != Ty->isIntegerTy()) {
  1532. Ty = SE.getEffectiveSCEVType(Ty);
  1533. LHS = InsertNoopCastOfTo(LHS, Ty);
  1534. }
  1535. Value *RHS = expandCodeForImpl(S->getOperand(i), Ty, false);
  1536. Value *Sel;
  1537. if (Ty->isIntegerTy())
  1538. Sel = Builder.CreateIntrinsic(Intrinsic::umax, {Ty}, {LHS, RHS},
  1539. /*FMFSource=*/nullptr, "umax");
  1540. else {
  1541. Value *ICmp = Builder.CreateICmpUGT(LHS, RHS);
  1542. Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umax");
  1543. }
  1544. LHS = Sel;
  1545. }
  1546. // In the case of mixed integer and pointer types, cast the
  1547. // final result back to the pointer type.
  1548. if (LHS->getType() != S->getType())
  1549. LHS = InsertNoopCastOfTo(LHS, S->getType());
  1550. return LHS;
  1551. }
  1552. Value *SCEVExpander::expandSMinExpr(const SCEVNAryExpr *S) {
  1553. Value *LHS = expand(S->getOperand(S->getNumOperands() - 1));
  1554. Type *Ty = LHS->getType();
  1555. for (int i = S->getNumOperands() - 2; i >= 0; --i) {
  1556. // In the case of mixed integer and pointer types, do the
  1557. // rest of the comparisons as integer.
  1558. Type *OpTy = S->getOperand(i)->getType();
  1559. if (OpTy->isIntegerTy() != Ty->isIntegerTy()) {
  1560. Ty = SE.getEffectiveSCEVType(Ty);
  1561. LHS = InsertNoopCastOfTo(LHS, Ty);
  1562. }
  1563. Value *RHS = expandCodeForImpl(S->getOperand(i), Ty, false);
  1564. Value *Sel;
  1565. if (Ty->isIntegerTy())
  1566. Sel = Builder.CreateIntrinsic(Intrinsic::smin, {Ty}, {LHS, RHS},
  1567. /*FMFSource=*/nullptr, "smin");
  1568. else {
  1569. Value *ICmp = Builder.CreateICmpSLT(LHS, RHS);
  1570. Sel = Builder.CreateSelect(ICmp, LHS, RHS, "smin");
  1571. }
  1572. LHS = Sel;
  1573. }
  1574. // In the case of mixed integer and pointer types, cast the
  1575. // final result back to the pointer type.
  1576. if (LHS->getType() != S->getType())
  1577. LHS = InsertNoopCastOfTo(LHS, S->getType());
  1578. return LHS;
  1579. }
  1580. Value *SCEVExpander::expandUMinExpr(const SCEVNAryExpr *S) {
  1581. Value *LHS = expand(S->getOperand(S->getNumOperands() - 1));
  1582. Type *Ty = LHS->getType();
  1583. for (int i = S->getNumOperands() - 2; i >= 0; --i) {
  1584. // In the case of mixed integer and pointer types, do the
  1585. // rest of the comparisons as integer.
  1586. Type *OpTy = S->getOperand(i)->getType();
  1587. if (OpTy->isIntegerTy() != Ty->isIntegerTy()) {
  1588. Ty = SE.getEffectiveSCEVType(Ty);
  1589. LHS = InsertNoopCastOfTo(LHS, Ty);
  1590. }
  1591. Value *RHS = expandCodeForImpl(S->getOperand(i), Ty, false);
  1592. Value *Sel;
  1593. if (Ty->isIntegerTy())
  1594. Sel = Builder.CreateIntrinsic(Intrinsic::umin, {Ty}, {LHS, RHS},
  1595. /*FMFSource=*/nullptr, "umin");
  1596. else {
  1597. Value *ICmp = Builder.CreateICmpULT(LHS, RHS);
  1598. Sel = Builder.CreateSelect(ICmp, LHS, RHS, "umin");
  1599. }
  1600. LHS = Sel;
  1601. }
  1602. // In the case of mixed integer and pointer types, cast the
  1603. // final result back to the pointer type.
  1604. if (LHS->getType() != S->getType())
  1605. LHS = InsertNoopCastOfTo(LHS, S->getType());
  1606. return LHS;
  1607. }
  1608. Value *SCEVExpander::visitSMaxExpr(const SCEVSMaxExpr *S) {
  1609. return expandSMaxExpr(S);
  1610. }
  1611. Value *SCEVExpander::visitUMaxExpr(const SCEVUMaxExpr *S) {
  1612. return expandUMaxExpr(S);
  1613. }
  1614. Value *SCEVExpander::visitSMinExpr(const SCEVSMinExpr *S) {
  1615. return expandSMinExpr(S);
  1616. }
  1617. Value *SCEVExpander::visitUMinExpr(const SCEVUMinExpr *S) {
  1618. return expandUMinExpr(S);
  1619. }
  1620. Value *SCEVExpander::visitSequentialUMinExpr(const SCEVSequentialUMinExpr *S) {
  1621. SmallVector<Value *> Ops;
  1622. for (const SCEV *Op : S->operands())
  1623. Ops.emplace_back(expand(Op));
  1624. Value *SaturationPoint =
  1625. MinMaxIntrinsic::getSaturationPoint(Intrinsic::umin, S->getType());
  1626. SmallVector<Value *> OpIsZero;
  1627. for (Value *Op : ArrayRef<Value *>(Ops).drop_back())
  1628. OpIsZero.emplace_back(Builder.CreateICmpEQ(Op, SaturationPoint));
  1629. Value *AnyOpIsZero = Builder.CreateLogicalOr(OpIsZero);
  1630. Value *NaiveUMin = expandUMinExpr(S);
  1631. return Builder.CreateSelect(AnyOpIsZero, SaturationPoint, NaiveUMin);
  1632. }
  1633. Value *SCEVExpander::expandCodeForImpl(const SCEV *SH, Type *Ty,
  1634. Instruction *IP, bool Root) {
  1635. setInsertPoint(IP);
  1636. Value *V = expandCodeForImpl(SH, Ty, Root);
  1637. return V;
  1638. }
  1639. Value *SCEVExpander::expandCodeForImpl(const SCEV *SH, Type *Ty, bool Root) {
  1640. // Expand the code for this SCEV.
  1641. Value *V = expand(SH);
  1642. if (PreserveLCSSA) {
  1643. if (auto *Inst = dyn_cast<Instruction>(V)) {
  1644. // Create a temporary instruction to at the current insertion point, so we
  1645. // can hand it off to the helper to create LCSSA PHIs if required for the
  1646. // new use.
  1647. // FIXME: Ideally formLCSSAForInstructions (used in fixupLCSSAFormFor)
  1648. // would accept a insertion point and return an LCSSA phi for that
  1649. // insertion point, so there is no need to insert & remove the temporary
  1650. // instruction.
  1651. Instruction *Tmp;
  1652. if (Inst->getType()->isIntegerTy())
  1653. Tmp = cast<Instruction>(Builder.CreateIntToPtr(
  1654. Inst, Inst->getType()->getPointerTo(), "tmp.lcssa.user"));
  1655. else {
  1656. assert(Inst->getType()->isPointerTy());
  1657. Tmp = cast<Instruction>(Builder.CreatePtrToInt(
  1658. Inst, Type::getInt32Ty(Inst->getContext()), "tmp.lcssa.user"));
  1659. }
  1660. V = fixupLCSSAFormFor(Tmp, 0);
  1661. // Clean up temporary instruction.
  1662. InsertedValues.erase(Tmp);
  1663. InsertedPostIncValues.erase(Tmp);
  1664. Tmp->eraseFromParent();
  1665. }
  1666. }
  1667. InsertedExpressions[std::make_pair(SH, &*Builder.GetInsertPoint())] = V;
  1668. if (Ty) {
  1669. assert(SE.getTypeSizeInBits(Ty) == SE.getTypeSizeInBits(SH->getType()) &&
  1670. "non-trivial casts should be done with the SCEVs directly!");
  1671. V = InsertNoopCastOfTo(V, Ty);
  1672. }
  1673. return V;
  1674. }
  1675. ScalarEvolution::ValueOffsetPair
  1676. SCEVExpander::FindValueInExprValueMap(const SCEV *S,
  1677. const Instruction *InsertPt) {
  1678. auto *Set = SE.getSCEVValues(S);
  1679. // If the expansion is not in CanonicalMode, and the SCEV contains any
  1680. // sub scAddRecExpr type SCEV, it is required to expand the SCEV literally.
  1681. if (CanonicalMode || !SE.containsAddRecurrence(S)) {
  1682. // If S is scConstant, it may be worse to reuse an existing Value.
  1683. if (S->getSCEVType() != scConstant && Set) {
  1684. // Choose a Value from the set which dominates the InsertPt.
  1685. // InsertPt should be inside the Value's parent loop so as not to break
  1686. // the LCSSA form.
  1687. for (auto const &VOPair : *Set) {
  1688. Value *V = VOPair.first;
  1689. ConstantInt *Offset = VOPair.second;
  1690. Instruction *EntInst = dyn_cast_or_null<Instruction>(V);
  1691. if (!EntInst)
  1692. continue;
  1693. assert(EntInst->getFunction() == InsertPt->getFunction());
  1694. if (S->getType() == V->getType() &&
  1695. SE.DT.dominates(EntInst, InsertPt) &&
  1696. (SE.LI.getLoopFor(EntInst->getParent()) == nullptr ||
  1697. SE.LI.getLoopFor(EntInst->getParent())->contains(InsertPt)))
  1698. return {V, Offset};
  1699. }
  1700. }
  1701. }
  1702. return {nullptr, nullptr};
  1703. }
  1704. // The expansion of SCEV will either reuse a previous Value in ExprValueMap,
  1705. // or expand the SCEV literally. Specifically, if the expansion is in LSRMode,
  1706. // and the SCEV contains any sub scAddRecExpr type SCEV, it will be expanded
  1707. // literally, to prevent LSR's transformed SCEV from being reverted. Otherwise,
  1708. // the expansion will try to reuse Value from ExprValueMap, and only when it
  1709. // fails, expand the SCEV literally.
  1710. Value *SCEVExpander::expand(const SCEV *S) {
  1711. // Compute an insertion point for this SCEV object. Hoist the instructions
  1712. // as far out in the loop nest as possible.
  1713. Instruction *InsertPt = &*Builder.GetInsertPoint();
  1714. // We can move insertion point only if there is no div or rem operations
  1715. // otherwise we are risky to move it over the check for zero denominator.
  1716. auto SafeToHoist = [](const SCEV *S) {
  1717. return !SCEVExprContains(S, [](const SCEV *S) {
  1718. if (const auto *D = dyn_cast<SCEVUDivExpr>(S)) {
  1719. if (const auto *SC = dyn_cast<SCEVConstant>(D->getRHS()))
  1720. // Division by non-zero constants can be hoisted.
  1721. return SC->getValue()->isZero();
  1722. // All other divisions should not be moved as they may be
  1723. // divisions by zero and should be kept within the
  1724. // conditions of the surrounding loops that guard their
  1725. // execution (see PR35406).
  1726. return true;
  1727. }
  1728. return false;
  1729. });
  1730. };
  1731. if (SafeToHoist(S)) {
  1732. for (Loop *L = SE.LI.getLoopFor(Builder.GetInsertBlock());;
  1733. L = L->getParentLoop()) {
  1734. if (SE.isLoopInvariant(S, L)) {
  1735. if (!L) break;
  1736. if (BasicBlock *Preheader = L->getLoopPreheader())
  1737. InsertPt = Preheader->getTerminator();
  1738. else
  1739. // LSR sets the insertion point for AddRec start/step values to the
  1740. // block start to simplify value reuse, even though it's an invalid
  1741. // position. SCEVExpander must correct for this in all cases.
  1742. InsertPt = &*L->getHeader()->getFirstInsertionPt();
  1743. } else {
  1744. // If the SCEV is computable at this level, insert it into the header
  1745. // after the PHIs (and after any other instructions that we've inserted
  1746. // there) so that it is guaranteed to dominate any user inside the loop.
  1747. if (L && SE.hasComputableLoopEvolution(S, L) && !PostIncLoops.count(L))
  1748. InsertPt = &*L->getHeader()->getFirstInsertionPt();
  1749. while (InsertPt->getIterator() != Builder.GetInsertPoint() &&
  1750. (isInsertedInstruction(InsertPt) ||
  1751. isa<DbgInfoIntrinsic>(InsertPt))) {
  1752. InsertPt = &*std::next(InsertPt->getIterator());
  1753. }
  1754. break;
  1755. }
  1756. }
  1757. }
  1758. // Check to see if we already expanded this here.
  1759. auto I = InsertedExpressions.find(std::make_pair(S, InsertPt));
  1760. if (I != InsertedExpressions.end())
  1761. return I->second;
  1762. SCEVInsertPointGuard Guard(Builder, this);
  1763. Builder.SetInsertPoint(InsertPt);
  1764. // Expand the expression into instructions.
  1765. ScalarEvolution::ValueOffsetPair VO = FindValueInExprValueMap(S, InsertPt);
  1766. Value *V = VO.first;
  1767. if (!V)
  1768. V = visit(S);
  1769. else {
  1770. // If we're reusing an existing instruction, we are effectively CSEing two
  1771. // copies of the instruction (with potentially different flags). As such,
  1772. // we need to drop any poison generating flags unless we can prove that
  1773. // said flags must be valid for all new users.
  1774. if (auto *I = dyn_cast<Instruction>(V))
  1775. if (I->hasPoisonGeneratingFlags() && !programUndefinedIfPoison(I))
  1776. I->dropPoisonGeneratingFlags();
  1777. if (VO.second) {
  1778. if (PointerType *Vty = dyn_cast<PointerType>(V->getType())) {
  1779. int64_t Offset = VO.second->getSExtValue();
  1780. ConstantInt *Idx =
  1781. ConstantInt::getSigned(VO.second->getType(), -Offset);
  1782. unsigned AS = Vty->getAddressSpace();
  1783. V = Builder.CreateBitCast(V, Type::getInt8PtrTy(SE.getContext(), AS));
  1784. V = Builder.CreateGEP(Type::getInt8Ty(SE.getContext()), V, Idx,
  1785. "uglygep");
  1786. V = Builder.CreateBitCast(V, Vty);
  1787. } else {
  1788. V = Builder.CreateSub(V, VO.second);
  1789. }
  1790. }
  1791. }
  1792. // Remember the expanded value for this SCEV at this location.
  1793. //
  1794. // This is independent of PostIncLoops. The mapped value simply materializes
  1795. // the expression at this insertion point. If the mapped value happened to be
  1796. // a postinc expansion, it could be reused by a non-postinc user, but only if
  1797. // its insertion point was already at the head of the loop.
  1798. InsertedExpressions[std::make_pair(S, InsertPt)] = V;
  1799. return V;
  1800. }
  1801. void SCEVExpander::rememberInstruction(Value *I) {
  1802. auto DoInsert = [this](Value *V) {
  1803. if (!PostIncLoops.empty())
  1804. InsertedPostIncValues.insert(V);
  1805. else
  1806. InsertedValues.insert(V);
  1807. };
  1808. DoInsert(I);
  1809. if (!PreserveLCSSA)
  1810. return;
  1811. if (auto *Inst = dyn_cast<Instruction>(I)) {
  1812. // A new instruction has been added, which might introduce new uses outside
  1813. // a defining loop. Fix LCSSA from for each operand of the new instruction,
  1814. // if required.
  1815. for (unsigned OpIdx = 0, OpEnd = Inst->getNumOperands(); OpIdx != OpEnd;
  1816. OpIdx++)
  1817. fixupLCSSAFormFor(Inst, OpIdx);
  1818. }
  1819. }
  1820. /// replaceCongruentIVs - Check for congruent phis in this loop header and
  1821. /// replace them with their most canonical representative. Return the number of
  1822. /// phis eliminated.
  1823. ///
  1824. /// This does not depend on any SCEVExpander state but should be used in
  1825. /// the same context that SCEVExpander is used.
  1826. unsigned
  1827. SCEVExpander::replaceCongruentIVs(Loop *L, const DominatorTree *DT,
  1828. SmallVectorImpl<WeakTrackingVH> &DeadInsts,
  1829. const TargetTransformInfo *TTI) {
  1830. // Find integer phis in order of increasing width.
  1831. SmallVector<PHINode*, 8> Phis;
  1832. for (PHINode &PN : L->getHeader()->phis())
  1833. Phis.push_back(&PN);
  1834. if (TTI)
  1835. // Use stable_sort to preserve order of equivalent PHIs, so the order
  1836. // of the sorted Phis is the same from run to run on the same loop.
  1837. llvm::stable_sort(Phis, [](Value *LHS, Value *RHS) {
  1838. // Put pointers at the back and make sure pointer < pointer = false.
  1839. if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy())
  1840. return RHS->getType()->isIntegerTy() && !LHS->getType()->isIntegerTy();
  1841. return RHS->getType()->getPrimitiveSizeInBits().getFixedSize() <
  1842. LHS->getType()->getPrimitiveSizeInBits().getFixedSize();
  1843. });
  1844. unsigned NumElim = 0;
  1845. DenseMap<const SCEV *, PHINode *> ExprToIVMap;
  1846. // Process phis from wide to narrow. Map wide phis to their truncation
  1847. // so narrow phis can reuse them.
  1848. for (PHINode *Phi : Phis) {
  1849. auto SimplifyPHINode = [&](PHINode *PN) -> Value * {
  1850. if (Value *V = SimplifyInstruction(PN, {DL, &SE.TLI, &SE.DT, &SE.AC}))
  1851. return V;
  1852. if (!SE.isSCEVable(PN->getType()))
  1853. return nullptr;
  1854. auto *Const = dyn_cast<SCEVConstant>(SE.getSCEV(PN));
  1855. if (!Const)
  1856. return nullptr;
  1857. return Const->getValue();
  1858. };
  1859. // Fold constant phis. They may be congruent to other constant phis and
  1860. // would confuse the logic below that expects proper IVs.
  1861. if (Value *V = SimplifyPHINode(Phi)) {
  1862. if (V->getType() != Phi->getType())
  1863. continue;
  1864. Phi->replaceAllUsesWith(V);
  1865. DeadInsts.emplace_back(Phi);
  1866. ++NumElim;
  1867. SCEV_DEBUG_WITH_TYPE(DebugType,
  1868. dbgs() << "INDVARS: Eliminated constant iv: " << *Phi
  1869. << '\n');
  1870. continue;
  1871. }
  1872. if (!SE.isSCEVable(Phi->getType()))
  1873. continue;
  1874. PHINode *&OrigPhiRef = ExprToIVMap[SE.getSCEV(Phi)];
  1875. if (!OrigPhiRef) {
  1876. OrigPhiRef = Phi;
  1877. if (Phi->getType()->isIntegerTy() && TTI &&
  1878. TTI->isTruncateFree(Phi->getType(), Phis.back()->getType())) {
  1879. // This phi can be freely truncated to the narrowest phi type. Map the
  1880. // truncated expression to it so it will be reused for narrow types.
  1881. const SCEV *TruncExpr =
  1882. SE.getTruncateExpr(SE.getSCEV(Phi), Phis.back()->getType());
  1883. ExprToIVMap[TruncExpr] = Phi;
  1884. }
  1885. continue;
  1886. }
  1887. // Replacing a pointer phi with an integer phi or vice-versa doesn't make
  1888. // sense.
  1889. if (OrigPhiRef->getType()->isPointerTy() != Phi->getType()->isPointerTy())
  1890. continue;
  1891. if (BasicBlock *LatchBlock = L->getLoopLatch()) {
  1892. Instruction *OrigInc = dyn_cast<Instruction>(
  1893. OrigPhiRef->getIncomingValueForBlock(LatchBlock));
  1894. Instruction *IsomorphicInc =
  1895. dyn_cast<Instruction>(Phi->getIncomingValueForBlock(LatchBlock));
  1896. if (OrigInc && IsomorphicInc) {
  1897. // If this phi has the same width but is more canonical, replace the
  1898. // original with it. As part of the "more canonical" determination,
  1899. // respect a prior decision to use an IV chain.
  1900. if (OrigPhiRef->getType() == Phi->getType() &&
  1901. !(ChainedPhis.count(Phi) ||
  1902. isExpandedAddRecExprPHI(OrigPhiRef, OrigInc, L)) &&
  1903. (ChainedPhis.count(Phi) ||
  1904. isExpandedAddRecExprPHI(Phi, IsomorphicInc, L))) {
  1905. std::swap(OrigPhiRef, Phi);
  1906. std::swap(OrigInc, IsomorphicInc);
  1907. }
  1908. // Replacing the congruent phi is sufficient because acyclic
  1909. // redundancy elimination, CSE/GVN, should handle the
  1910. // rest. However, once SCEV proves that a phi is congruent,
  1911. // it's often the head of an IV user cycle that is isomorphic
  1912. // with the original phi. It's worth eagerly cleaning up the
  1913. // common case of a single IV increment so that DeleteDeadPHIs
  1914. // can remove cycles that had postinc uses.
  1915. const SCEV *TruncExpr =
  1916. SE.getTruncateOrNoop(SE.getSCEV(OrigInc), IsomorphicInc->getType());
  1917. if (OrigInc != IsomorphicInc &&
  1918. TruncExpr == SE.getSCEV(IsomorphicInc) &&
  1919. SE.LI.replacementPreservesLCSSAForm(IsomorphicInc, OrigInc) &&
  1920. hoistIVInc(OrigInc, IsomorphicInc)) {
  1921. SCEV_DEBUG_WITH_TYPE(
  1922. DebugType, dbgs() << "INDVARS: Eliminated congruent iv.inc: "
  1923. << *IsomorphicInc << '\n');
  1924. Value *NewInc = OrigInc;
  1925. if (OrigInc->getType() != IsomorphicInc->getType()) {
  1926. Instruction *IP = nullptr;
  1927. if (PHINode *PN = dyn_cast<PHINode>(OrigInc))
  1928. IP = &*PN->getParent()->getFirstInsertionPt();
  1929. else
  1930. IP = OrigInc->getNextNode();
  1931. IRBuilder<> Builder(IP);
  1932. Builder.SetCurrentDebugLocation(IsomorphicInc->getDebugLoc());
  1933. NewInc = Builder.CreateTruncOrBitCast(
  1934. OrigInc, IsomorphicInc->getType(), IVName);
  1935. }
  1936. IsomorphicInc->replaceAllUsesWith(NewInc);
  1937. DeadInsts.emplace_back(IsomorphicInc);
  1938. }
  1939. }
  1940. }
  1941. SCEV_DEBUG_WITH_TYPE(DebugType,
  1942. dbgs() << "INDVARS: Eliminated congruent iv: " << *Phi
  1943. << '\n');
  1944. SCEV_DEBUG_WITH_TYPE(
  1945. DebugType, dbgs() << "INDVARS: Original iv: " << *OrigPhiRef << '\n');
  1946. ++NumElim;
  1947. Value *NewIV = OrigPhiRef;
  1948. if (OrigPhiRef->getType() != Phi->getType()) {
  1949. IRBuilder<> Builder(&*L->getHeader()->getFirstInsertionPt());
  1950. Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
  1951. NewIV = Builder.CreateTruncOrBitCast(OrigPhiRef, Phi->getType(), IVName);
  1952. }
  1953. Phi->replaceAllUsesWith(NewIV);
  1954. DeadInsts.emplace_back(Phi);
  1955. }
  1956. return NumElim;
  1957. }
  1958. Optional<ScalarEvolution::ValueOffsetPair>
  1959. SCEVExpander::getRelatedExistingExpansion(const SCEV *S, const Instruction *At,
  1960. Loop *L) {
  1961. using namespace llvm::PatternMatch;
  1962. SmallVector<BasicBlock *, 4> ExitingBlocks;
  1963. L->getExitingBlocks(ExitingBlocks);
  1964. // Look for suitable value in simple conditions at the loop exits.
  1965. for (BasicBlock *BB : ExitingBlocks) {
  1966. ICmpInst::Predicate Pred;
  1967. Instruction *LHS, *RHS;
  1968. if (!match(BB->getTerminator(),
  1969. m_Br(m_ICmp(Pred, m_Instruction(LHS), m_Instruction(RHS)),
  1970. m_BasicBlock(), m_BasicBlock())))
  1971. continue;
  1972. if (SE.getSCEV(LHS) == S && SE.DT.dominates(LHS, At))
  1973. return ScalarEvolution::ValueOffsetPair(LHS, nullptr);
  1974. if (SE.getSCEV(RHS) == S && SE.DT.dominates(RHS, At))
  1975. return ScalarEvolution::ValueOffsetPair(RHS, nullptr);
  1976. }
  1977. // Use expand's logic which is used for reusing a previous Value in
  1978. // ExprValueMap. Note that we don't currently model the cost of
  1979. // needing to drop poison generating flags on the instruction if we
  1980. // want to reuse it. We effectively assume that has zero cost.
  1981. ScalarEvolution::ValueOffsetPair VO = FindValueInExprValueMap(S, At);
  1982. if (VO.first)
  1983. return VO;
  1984. // There is potential to make this significantly smarter, but this simple
  1985. // heuristic already gets some interesting cases.
  1986. // Can not find suitable value.
  1987. return None;
  1988. }
  1989. template<typename T> static InstructionCost costAndCollectOperands(
  1990. const SCEVOperand &WorkItem, const TargetTransformInfo &TTI,
  1991. TargetTransformInfo::TargetCostKind CostKind,
  1992. SmallVectorImpl<SCEVOperand> &Worklist) {
  1993. const T *S = cast<T>(WorkItem.S);
  1994. InstructionCost Cost = 0;
  1995. // Object to help map SCEV operands to expanded IR instructions.
  1996. struct OperationIndices {
  1997. OperationIndices(unsigned Opc, size_t min, size_t max) :
  1998. Opcode(Opc), MinIdx(min), MaxIdx(max) { }
  1999. unsigned Opcode;
  2000. size_t MinIdx;
  2001. size_t MaxIdx;
  2002. };
  2003. // Collect the operations of all the instructions that will be needed to
  2004. // expand the SCEVExpr. This is so that when we come to cost the operands,
  2005. // we know what the generated user(s) will be.
  2006. SmallVector<OperationIndices, 2> Operations;
  2007. auto CastCost = [&](unsigned Opcode) -> InstructionCost {
  2008. Operations.emplace_back(Opcode, 0, 0);
  2009. return TTI.getCastInstrCost(Opcode, S->getType(),
  2010. S->getOperand(0)->getType(),
  2011. TTI::CastContextHint::None, CostKind);
  2012. };
  2013. auto ArithCost = [&](unsigned Opcode, unsigned NumRequired,
  2014. unsigned MinIdx = 0,
  2015. unsigned MaxIdx = 1) -> InstructionCost {
  2016. Operations.emplace_back(Opcode, MinIdx, MaxIdx);
  2017. return NumRequired *
  2018. TTI.getArithmeticInstrCost(Opcode, S->getType(), CostKind);
  2019. };
  2020. auto CmpSelCost = [&](unsigned Opcode, unsigned NumRequired, unsigned MinIdx,
  2021. unsigned MaxIdx) -> InstructionCost {
  2022. Operations.emplace_back(Opcode, MinIdx, MaxIdx);
  2023. Type *OpType = S->getOperand(0)->getType();
  2024. return NumRequired * TTI.getCmpSelInstrCost(
  2025. Opcode, OpType, CmpInst::makeCmpResultType(OpType),
  2026. CmpInst::BAD_ICMP_PREDICATE, CostKind);
  2027. };
  2028. switch (S->getSCEVType()) {
  2029. case scCouldNotCompute:
  2030. llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
  2031. case scUnknown:
  2032. case scConstant:
  2033. return 0;
  2034. case scPtrToInt:
  2035. Cost = CastCost(Instruction::PtrToInt);
  2036. break;
  2037. case scTruncate:
  2038. Cost = CastCost(Instruction::Trunc);
  2039. break;
  2040. case scZeroExtend:
  2041. Cost = CastCost(Instruction::ZExt);
  2042. break;
  2043. case scSignExtend:
  2044. Cost = CastCost(Instruction::SExt);
  2045. break;
  2046. case scUDivExpr: {
  2047. unsigned Opcode = Instruction::UDiv;
  2048. if (auto *SC = dyn_cast<SCEVConstant>(S->getOperand(1)))
  2049. if (SC->getAPInt().isPowerOf2())
  2050. Opcode = Instruction::LShr;
  2051. Cost = ArithCost(Opcode, 1);
  2052. break;
  2053. }
  2054. case scAddExpr:
  2055. Cost = ArithCost(Instruction::Add, S->getNumOperands() - 1);
  2056. break;
  2057. case scMulExpr:
  2058. // TODO: this is a very pessimistic cost modelling for Mul,
  2059. // because of Bin Pow algorithm actually used by the expander,
  2060. // see SCEVExpander::visitMulExpr(), ExpandOpBinPowN().
  2061. Cost = ArithCost(Instruction::Mul, S->getNumOperands() - 1);
  2062. break;
  2063. case scSMaxExpr:
  2064. case scUMaxExpr:
  2065. case scSMinExpr:
  2066. case scUMinExpr:
  2067. case scSequentialUMinExpr: {
  2068. // FIXME: should this ask the cost for Intrinsic's?
  2069. // The reduction tree.
  2070. Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 1);
  2071. Cost += CmpSelCost(Instruction::Select, S->getNumOperands() - 1, 0, 2);
  2072. switch (S->getSCEVType()) {
  2073. case scSequentialUMinExpr: {
  2074. // The safety net against poison.
  2075. // FIXME: this is broken.
  2076. Cost += CmpSelCost(Instruction::ICmp, S->getNumOperands() - 1, 0, 0);
  2077. Cost += ArithCost(Instruction::Or,
  2078. S->getNumOperands() > 2 ? S->getNumOperands() - 2 : 0);
  2079. Cost += CmpSelCost(Instruction::Select, 1, 0, 1);
  2080. break;
  2081. }
  2082. default:
  2083. assert(!isa<SCEVSequentialMinMaxExpr>(S) &&
  2084. "Unhandled SCEV expression type?");
  2085. break;
  2086. }
  2087. break;
  2088. }
  2089. case scAddRecExpr: {
  2090. // In this polynominal, we may have some zero operands, and we shouldn't
  2091. // really charge for those. So how many non-zero coeffients are there?
  2092. int NumTerms = llvm::count_if(S->operands(), [](const SCEV *Op) {
  2093. return !Op->isZero();
  2094. });
  2095. assert(NumTerms >= 1 && "Polynominal should have at least one term.");
  2096. assert(!(*std::prev(S->operands().end()))->isZero() &&
  2097. "Last operand should not be zero");
  2098. // Ignoring constant term (operand 0), how many of the coeffients are u> 1?
  2099. int NumNonZeroDegreeNonOneTerms =
  2100. llvm::count_if(S->operands(), [](const SCEV *Op) {
  2101. auto *SConst = dyn_cast<SCEVConstant>(Op);
  2102. return !SConst || SConst->getAPInt().ugt(1);
  2103. });
  2104. // Much like with normal add expr, the polynominal will require
  2105. // one less addition than the number of it's terms.
  2106. InstructionCost AddCost = ArithCost(Instruction::Add, NumTerms - 1,
  2107. /*MinIdx*/ 1, /*MaxIdx*/ 1);
  2108. // Here, *each* one of those will require a multiplication.
  2109. InstructionCost MulCost =
  2110. ArithCost(Instruction::Mul, NumNonZeroDegreeNonOneTerms);
  2111. Cost = AddCost + MulCost;
  2112. // What is the degree of this polynominal?
  2113. int PolyDegree = S->getNumOperands() - 1;
  2114. assert(PolyDegree >= 1 && "Should be at least affine.");
  2115. // The final term will be:
  2116. // Op_{PolyDegree} * x ^ {PolyDegree}
  2117. // Where x ^ {PolyDegree} will again require PolyDegree-1 mul operations.
  2118. // Note that x ^ {PolyDegree} = x * x ^ {PolyDegree-1} so charging for
  2119. // x ^ {PolyDegree} will give us x ^ {2} .. x ^ {PolyDegree-1} for free.
  2120. // FIXME: this is conservatively correct, but might be overly pessimistic.
  2121. Cost += MulCost * (PolyDegree - 1);
  2122. break;
  2123. }
  2124. }
  2125. for (auto &CostOp : Operations) {
  2126. for (auto SCEVOp : enumerate(S->operands())) {
  2127. // Clamp the index to account for multiple IR operations being chained.
  2128. size_t MinIdx = std::max(SCEVOp.index(), CostOp.MinIdx);
  2129. size_t OpIdx = std::min(MinIdx, CostOp.MaxIdx);
  2130. Worklist.emplace_back(CostOp.Opcode, OpIdx, SCEVOp.value());
  2131. }
  2132. }
  2133. return Cost;
  2134. }
  2135. bool SCEVExpander::isHighCostExpansionHelper(
  2136. const SCEVOperand &WorkItem, Loop *L, const Instruction &At,
  2137. InstructionCost &Cost, unsigned Budget, const TargetTransformInfo &TTI,
  2138. SmallPtrSetImpl<const SCEV *> &Processed,
  2139. SmallVectorImpl<SCEVOperand> &Worklist) {
  2140. if (Cost > Budget)
  2141. return true; // Already run out of budget, give up.
  2142. const SCEV *S = WorkItem.S;
  2143. // Was the cost of expansion of this expression already accounted for?
  2144. if (!isa<SCEVConstant>(S) && !Processed.insert(S).second)
  2145. return false; // We have already accounted for this expression.
  2146. // If we can find an existing value for this scev available at the point "At"
  2147. // then consider the expression cheap.
  2148. if (getRelatedExistingExpansion(S, &At, L))
  2149. return false; // Consider the expression to be free.
  2150. TargetTransformInfo::TargetCostKind CostKind =
  2151. L->getHeader()->getParent()->hasMinSize()
  2152. ? TargetTransformInfo::TCK_CodeSize
  2153. : TargetTransformInfo::TCK_RecipThroughput;
  2154. switch (S->getSCEVType()) {
  2155. case scCouldNotCompute:
  2156. llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
  2157. case scUnknown:
  2158. // Assume to be zero-cost.
  2159. return false;
  2160. case scConstant: {
  2161. // Only evalulate the costs of constants when optimizing for size.
  2162. if (CostKind != TargetTransformInfo::TCK_CodeSize)
  2163. return false;
  2164. const APInt &Imm = cast<SCEVConstant>(S)->getAPInt();
  2165. Type *Ty = S->getType();
  2166. Cost += TTI.getIntImmCostInst(
  2167. WorkItem.ParentOpcode, WorkItem.OperandIdx, Imm, Ty, CostKind);
  2168. return Cost > Budget;
  2169. }
  2170. case scTruncate:
  2171. case scPtrToInt:
  2172. case scZeroExtend:
  2173. case scSignExtend: {
  2174. Cost +=
  2175. costAndCollectOperands<SCEVCastExpr>(WorkItem, TTI, CostKind, Worklist);
  2176. return false; // Will answer upon next entry into this function.
  2177. }
  2178. case scUDivExpr: {
  2179. // UDivExpr is very likely a UDiv that ScalarEvolution's HowFarToZero or
  2180. // HowManyLessThans produced to compute a precise expression, rather than a
  2181. // UDiv from the user's code. If we can't find a UDiv in the code with some
  2182. // simple searching, we need to account for it's cost.
  2183. // At the beginning of this function we already tried to find existing
  2184. // value for plain 'S'. Now try to lookup 'S + 1' since it is common
  2185. // pattern involving division. This is just a simple search heuristic.
  2186. if (getRelatedExistingExpansion(
  2187. SE.getAddExpr(S, SE.getConstant(S->getType(), 1)), &At, L))
  2188. return false; // Consider it to be free.
  2189. Cost +=
  2190. costAndCollectOperands<SCEVUDivExpr>(WorkItem, TTI, CostKind, Worklist);
  2191. return false; // Will answer upon next entry into this function.
  2192. }
  2193. case scAddExpr:
  2194. case scMulExpr:
  2195. case scUMaxExpr:
  2196. case scSMaxExpr:
  2197. case scUMinExpr:
  2198. case scSMinExpr:
  2199. case scSequentialUMinExpr: {
  2200. assert(cast<SCEVNAryExpr>(S)->getNumOperands() > 1 &&
  2201. "Nary expr should have more than 1 operand.");
  2202. // The simple nary expr will require one less op (or pair of ops)
  2203. // than the number of it's terms.
  2204. Cost +=
  2205. costAndCollectOperands<SCEVNAryExpr>(WorkItem, TTI, CostKind, Worklist);
  2206. return Cost > Budget;
  2207. }
  2208. case scAddRecExpr: {
  2209. assert(cast<SCEVAddRecExpr>(S)->getNumOperands() >= 2 &&
  2210. "Polynomial should be at least linear");
  2211. Cost += costAndCollectOperands<SCEVAddRecExpr>(
  2212. WorkItem, TTI, CostKind, Worklist);
  2213. return Cost > Budget;
  2214. }
  2215. }
  2216. llvm_unreachable("Unknown SCEV kind!");
  2217. }
  2218. Value *SCEVExpander::expandCodeForPredicate(const SCEVPredicate *Pred,
  2219. Instruction *IP) {
  2220. assert(IP);
  2221. switch (Pred->getKind()) {
  2222. case SCEVPredicate::P_Union:
  2223. return expandUnionPredicate(cast<SCEVUnionPredicate>(Pred), IP);
  2224. case SCEVPredicate::P_Equal:
  2225. return expandEqualPredicate(cast<SCEVEqualPredicate>(Pred), IP);
  2226. case SCEVPredicate::P_Wrap: {
  2227. auto *AddRecPred = cast<SCEVWrapPredicate>(Pred);
  2228. return expandWrapPredicate(AddRecPred, IP);
  2229. }
  2230. }
  2231. llvm_unreachable("Unknown SCEV predicate type");
  2232. }
  2233. Value *SCEVExpander::expandEqualPredicate(const SCEVEqualPredicate *Pred,
  2234. Instruction *IP) {
  2235. Value *Expr0 =
  2236. expandCodeForImpl(Pred->getLHS(), Pred->getLHS()->getType(), IP, false);
  2237. Value *Expr1 =
  2238. expandCodeForImpl(Pred->getRHS(), Pred->getRHS()->getType(), IP, false);
  2239. Builder.SetInsertPoint(IP);
  2240. auto *I = Builder.CreateICmpNE(Expr0, Expr1, "ident.check");
  2241. return I;
  2242. }
  2243. Value *SCEVExpander::generateOverflowCheck(const SCEVAddRecExpr *AR,
  2244. Instruction *Loc, bool Signed) {
  2245. assert(AR->isAffine() && "Cannot generate RT check for "
  2246. "non-affine expression");
  2247. SCEVUnionPredicate Pred;
  2248. const SCEV *ExitCount =
  2249. SE.getPredicatedBackedgeTakenCount(AR->getLoop(), Pred);
  2250. assert(!isa<SCEVCouldNotCompute>(ExitCount) && "Invalid loop count");
  2251. const SCEV *Step = AR->getStepRecurrence(SE);
  2252. const SCEV *Start = AR->getStart();
  2253. Type *ARTy = AR->getType();
  2254. unsigned SrcBits = SE.getTypeSizeInBits(ExitCount->getType());
  2255. unsigned DstBits = SE.getTypeSizeInBits(ARTy);
  2256. // The expression {Start,+,Step} has nusw/nssw if
  2257. // Step < 0, Start - |Step| * Backedge <= Start
  2258. // Step >= 0, Start + |Step| * Backedge > Start
  2259. // and |Step| * Backedge doesn't unsigned overflow.
  2260. IntegerType *CountTy = IntegerType::get(Loc->getContext(), SrcBits);
  2261. Builder.SetInsertPoint(Loc);
  2262. Value *TripCountVal = expandCodeForImpl(ExitCount, CountTy, Loc, false);
  2263. IntegerType *Ty =
  2264. IntegerType::get(Loc->getContext(), SE.getTypeSizeInBits(ARTy));
  2265. Value *StepValue = expandCodeForImpl(Step, Ty, Loc, false);
  2266. Value *NegStepValue =
  2267. expandCodeForImpl(SE.getNegativeSCEV(Step), Ty, Loc, false);
  2268. Value *StartValue = expandCodeForImpl(Start, ARTy, Loc, false);
  2269. ConstantInt *Zero =
  2270. ConstantInt::get(Loc->getContext(), APInt::getZero(DstBits));
  2271. Builder.SetInsertPoint(Loc);
  2272. // Compute |Step|
  2273. Value *StepCompare = Builder.CreateICmp(ICmpInst::ICMP_SLT, StepValue, Zero);
  2274. Value *AbsStep = Builder.CreateSelect(StepCompare, NegStepValue, StepValue);
  2275. // Compute |Step| * Backedge
  2276. // Compute:
  2277. // 1. Start + |Step| * Backedge < Start
  2278. // 2. Start - |Step| * Backedge > Start
  2279. //
  2280. // And select either 1. or 2. depending on whether step is positive or
  2281. // negative. If Step is known to be positive or negative, only create
  2282. // either 1. or 2.
  2283. auto ComputeEndCheck = [&]() -> Value * {
  2284. // Checking <u 0 is always false.
  2285. if (!Signed && Start->isZero() && SE.isKnownPositive(Step))
  2286. return ConstantInt::getFalse(Loc->getContext());
  2287. // Get the backedge taken count and truncate or extended to the AR type.
  2288. Value *TruncTripCount = Builder.CreateZExtOrTrunc(TripCountVal, Ty);
  2289. Value *MulV, *OfMul;
  2290. if (Step->isOne()) {
  2291. // Special-case Step of one. Potentially-costly `umul_with_overflow` isn't
  2292. // needed, there is never an overflow, so to avoid artificially inflating
  2293. // the cost of the check, directly emit the optimized IR.
  2294. MulV = TruncTripCount;
  2295. OfMul = ConstantInt::getFalse(MulV->getContext());
  2296. } else {
  2297. auto *MulF = Intrinsic::getDeclaration(Loc->getModule(),
  2298. Intrinsic::umul_with_overflow, Ty);
  2299. CallInst *Mul =
  2300. Builder.CreateCall(MulF, {AbsStep, TruncTripCount}, "mul");
  2301. MulV = Builder.CreateExtractValue(Mul, 0, "mul.result");
  2302. OfMul = Builder.CreateExtractValue(Mul, 1, "mul.overflow");
  2303. }
  2304. Value *Add = nullptr, *Sub = nullptr;
  2305. bool NeedPosCheck = !SE.isKnownNegative(Step);
  2306. bool NeedNegCheck = !SE.isKnownPositive(Step);
  2307. if (PointerType *ARPtrTy = dyn_cast<PointerType>(ARTy)) {
  2308. StartValue = InsertNoopCastOfTo(
  2309. StartValue, Builder.getInt8PtrTy(ARPtrTy->getAddressSpace()));
  2310. Value *NegMulV = Builder.CreateNeg(MulV);
  2311. if (NeedPosCheck)
  2312. Add = Builder.CreateGEP(Builder.getInt8Ty(), StartValue, MulV);
  2313. if (NeedNegCheck)
  2314. Sub = Builder.CreateGEP(Builder.getInt8Ty(), StartValue, NegMulV);
  2315. } else {
  2316. if (NeedPosCheck)
  2317. Add = Builder.CreateAdd(StartValue, MulV);
  2318. if (NeedNegCheck)
  2319. Sub = Builder.CreateSub(StartValue, MulV);
  2320. }
  2321. Value *EndCompareLT = nullptr;
  2322. Value *EndCompareGT = nullptr;
  2323. Value *EndCheck = nullptr;
  2324. if (NeedPosCheck)
  2325. EndCheck = EndCompareLT = Builder.CreateICmp(
  2326. Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT, Add, StartValue);
  2327. if (NeedNegCheck)
  2328. EndCheck = EndCompareGT = Builder.CreateICmp(
  2329. Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT, Sub, StartValue);
  2330. if (NeedPosCheck && NeedNegCheck) {
  2331. // Select the answer based on the sign of Step.
  2332. EndCheck = Builder.CreateSelect(StepCompare, EndCompareGT, EndCompareLT);
  2333. }
  2334. return Builder.CreateOr(EndCheck, OfMul);
  2335. };
  2336. Value *EndCheck = ComputeEndCheck();
  2337. // If the backedge taken count type is larger than the AR type,
  2338. // check that we don't drop any bits by truncating it. If we are
  2339. // dropping bits, then we have overflow (unless the step is zero).
  2340. if (SE.getTypeSizeInBits(CountTy) > SE.getTypeSizeInBits(Ty)) {
  2341. auto MaxVal = APInt::getMaxValue(DstBits).zext(SrcBits);
  2342. auto *BackedgeCheck =
  2343. Builder.CreateICmp(ICmpInst::ICMP_UGT, TripCountVal,
  2344. ConstantInt::get(Loc->getContext(), MaxVal));
  2345. BackedgeCheck = Builder.CreateAnd(
  2346. BackedgeCheck, Builder.CreateICmp(ICmpInst::ICMP_NE, StepValue, Zero));
  2347. EndCheck = Builder.CreateOr(EndCheck, BackedgeCheck);
  2348. }
  2349. return EndCheck;
  2350. }
  2351. Value *SCEVExpander::expandWrapPredicate(const SCEVWrapPredicate *Pred,
  2352. Instruction *IP) {
  2353. const auto *A = cast<SCEVAddRecExpr>(Pred->getExpr());
  2354. Value *NSSWCheck = nullptr, *NUSWCheck = nullptr;
  2355. // Add a check for NUSW
  2356. if (Pred->getFlags() & SCEVWrapPredicate::IncrementNUSW)
  2357. NUSWCheck = generateOverflowCheck(A, IP, false);
  2358. // Add a check for NSSW
  2359. if (Pred->getFlags() & SCEVWrapPredicate::IncrementNSSW)
  2360. NSSWCheck = generateOverflowCheck(A, IP, true);
  2361. if (NUSWCheck && NSSWCheck)
  2362. return Builder.CreateOr(NUSWCheck, NSSWCheck);
  2363. if (NUSWCheck)
  2364. return NUSWCheck;
  2365. if (NSSWCheck)
  2366. return NSSWCheck;
  2367. return ConstantInt::getFalse(IP->getContext());
  2368. }
  2369. Value *SCEVExpander::expandUnionPredicate(const SCEVUnionPredicate *Union,
  2370. Instruction *IP) {
  2371. // Loop over all checks in this set.
  2372. SmallVector<Value *> Checks;
  2373. for (auto Pred : Union->getPredicates()) {
  2374. Checks.push_back(expandCodeForPredicate(Pred, IP));
  2375. Builder.SetInsertPoint(IP);
  2376. }
  2377. if (Checks.empty())
  2378. return ConstantInt::getFalse(IP->getContext());
  2379. return Builder.CreateOr(Checks);
  2380. }
  2381. Value *SCEVExpander::fixupLCSSAFormFor(Instruction *User, unsigned OpIdx) {
  2382. assert(PreserveLCSSA);
  2383. SmallVector<Instruction *, 1> ToUpdate;
  2384. auto *OpV = User->getOperand(OpIdx);
  2385. auto *OpI = dyn_cast<Instruction>(OpV);
  2386. if (!OpI)
  2387. return OpV;
  2388. Loop *DefLoop = SE.LI.getLoopFor(OpI->getParent());
  2389. Loop *UseLoop = SE.LI.getLoopFor(User->getParent());
  2390. if (!DefLoop || UseLoop == DefLoop || DefLoop->contains(UseLoop))
  2391. return OpV;
  2392. ToUpdate.push_back(OpI);
  2393. SmallVector<PHINode *, 16> PHIsToRemove;
  2394. formLCSSAForInstructions(ToUpdate, SE.DT, SE.LI, &SE, Builder, &PHIsToRemove);
  2395. for (PHINode *PN : PHIsToRemove) {
  2396. if (!PN->use_empty())
  2397. continue;
  2398. InsertedValues.erase(PN);
  2399. InsertedPostIncValues.erase(PN);
  2400. PN->eraseFromParent();
  2401. }
  2402. return User->getOperand(OpIdx);
  2403. }
  2404. namespace {
  2405. // Search for a SCEV subexpression that is not safe to expand. Any expression
  2406. // that may expand to a !isSafeToSpeculativelyExecute value is unsafe, namely
  2407. // UDiv expressions. We don't know if the UDiv is derived from an IR divide
  2408. // instruction, but the important thing is that we prove the denominator is
  2409. // nonzero before expansion.
  2410. //
  2411. // IVUsers already checks that IV-derived expressions are safe. So this check is
  2412. // only needed when the expression includes some subexpression that is not IV
  2413. // derived.
  2414. //
  2415. // Currently, we only allow division by a nonzero constant here. If this is
  2416. // inadequate, we could easily allow division by SCEVUnknown by using
  2417. // ValueTracking to check isKnownNonZero().
  2418. //
  2419. // We cannot generally expand recurrences unless the step dominates the loop
  2420. // header. The expander handles the special case of affine recurrences by
  2421. // scaling the recurrence outside the loop, but this technique isn't generally
  2422. // applicable. Expanding a nested recurrence outside a loop requires computing
  2423. // binomial coefficients. This could be done, but the recurrence has to be in a
  2424. // perfectly reduced form, which can't be guaranteed.
  2425. struct SCEVFindUnsafe {
  2426. ScalarEvolution &SE;
  2427. bool CanonicalMode;
  2428. bool IsUnsafe;
  2429. SCEVFindUnsafe(ScalarEvolution &SE, bool CanonicalMode)
  2430. : SE(SE), CanonicalMode(CanonicalMode), IsUnsafe(false) {}
  2431. bool follow(const SCEV *S) {
  2432. if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
  2433. const SCEVConstant *SC = dyn_cast<SCEVConstant>(D->getRHS());
  2434. if (!SC || SC->getValue()->isZero()) {
  2435. IsUnsafe = true;
  2436. return false;
  2437. }
  2438. }
  2439. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
  2440. const SCEV *Step = AR->getStepRecurrence(SE);
  2441. if (!AR->isAffine() && !SE.dominates(Step, AR->getLoop()->getHeader())) {
  2442. IsUnsafe = true;
  2443. return false;
  2444. }
  2445. // For non-affine addrecs or in non-canonical mode we need a preheader
  2446. // to insert into.
  2447. if (!AR->getLoop()->getLoopPreheader() &&
  2448. (!CanonicalMode || !AR->isAffine())) {
  2449. IsUnsafe = true;
  2450. return false;
  2451. }
  2452. }
  2453. return true;
  2454. }
  2455. bool isDone() const { return IsUnsafe; }
  2456. };
  2457. }
  2458. namespace llvm {
  2459. bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE, bool CanonicalMode) {
  2460. SCEVFindUnsafe Search(SE, CanonicalMode);
  2461. visitAll(S, Search);
  2462. return !Search.IsUnsafe;
  2463. }
  2464. bool isSafeToExpandAt(const SCEV *S, const Instruction *InsertionPoint,
  2465. ScalarEvolution &SE) {
  2466. if (!isSafeToExpand(S, SE))
  2467. return false;
  2468. // We have to prove that the expanded site of S dominates InsertionPoint.
  2469. // This is easy when not in the same block, but hard when S is an instruction
  2470. // to be expanded somewhere inside the same block as our insertion point.
  2471. // What we really need here is something analogous to an OrderedBasicBlock,
  2472. // but for the moment, we paper over the problem by handling two common and
  2473. // cheap to check cases.
  2474. if (SE.properlyDominates(S, InsertionPoint->getParent()))
  2475. return true;
  2476. if (SE.dominates(S, InsertionPoint->getParent())) {
  2477. if (InsertionPoint->getParent()->getTerminator() == InsertionPoint)
  2478. return true;
  2479. if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
  2480. if (llvm::is_contained(InsertionPoint->operand_values(), U->getValue()))
  2481. return true;
  2482. }
  2483. return false;
  2484. }
  2485. void SCEVExpanderCleaner::cleanup() {
  2486. // Result is used, nothing to remove.
  2487. if (ResultUsed)
  2488. return;
  2489. auto InsertedInstructions = Expander.getAllInsertedInstructions();
  2490. #ifndef NDEBUG
  2491. SmallPtrSet<Instruction *, 8> InsertedSet(InsertedInstructions.begin(),
  2492. InsertedInstructions.end());
  2493. (void)InsertedSet;
  2494. #endif
  2495. // Remove sets with value handles.
  2496. Expander.clear();
  2497. // Remove all inserted instructions.
  2498. for (Instruction *I : reverse(InsertedInstructions)) {
  2499. #ifndef NDEBUG
  2500. assert(all_of(I->users(),
  2501. [&InsertedSet](Value *U) {
  2502. return InsertedSet.contains(cast<Instruction>(U));
  2503. }) &&
  2504. "removed instruction should only be used by instructions inserted "
  2505. "during expansion");
  2506. #endif
  2507. assert(!I->getType()->isVoidTy() &&
  2508. "inserted instruction should have non-void types");
  2509. I->replaceAllUsesWith(UndefValue::get(I->getType()));
  2510. I->eraseFromParent();
  2511. }
  2512. }
  2513. }