LICM.cpp 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364
  1. //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
  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 pass performs loop invariant code motion, attempting to remove as much
  10. // code from the body of a loop as possible. It does this by either hoisting
  11. // code into the preheader block, or by sinking code to the exit blocks if it is
  12. // safe. This pass also promotes must-aliased memory locations in the loop to
  13. // live in registers, thus hoisting and sinking "invariant" loads and stores.
  14. //
  15. // Hoisting operations out of loops is a canonicalization transform. It
  16. // enables and simplifies subsequent optimizations in the middle-end.
  17. // Rematerialization of hoisted instructions to reduce register pressure is the
  18. // responsibility of the back-end, which has more accurate information about
  19. // register pressure and also handles other optimizations than LICM that
  20. // increase live-ranges.
  21. //
  22. // This pass uses alias analysis for two purposes:
  23. //
  24. // 1. Moving loop invariant loads and calls out of loops. If we can determine
  25. // that a load or call inside of a loop never aliases anything stored to,
  26. // we can hoist it or sink it like any other instruction.
  27. // 2. Scalar Promotion of Memory - If there is a store instruction inside of
  28. // the loop, we try to move the store to happen AFTER the loop instead of
  29. // inside of the loop. This can only happen if a few conditions are true:
  30. // A. The pointer stored through is loop invariant
  31. // B. There are no stores or loads in the loop which _may_ alias the
  32. // pointer. There are no calls in the loop which mod/ref the pointer.
  33. // If these conditions are true, we can promote the loads and stores in the
  34. // loop of the pointer to use a temporary alloca'd variable. We then use
  35. // the SSAUpdater to construct the appropriate SSA form for the value.
  36. //
  37. //===----------------------------------------------------------------------===//
  38. #include "llvm/Transforms/Scalar/LICM.h"
  39. #include "llvm/ADT/SetOperations.h"
  40. #include "llvm/ADT/Statistic.h"
  41. #include "llvm/Analysis/AliasAnalysis.h"
  42. #include "llvm/Analysis/AliasSetTracker.h"
  43. #include "llvm/Analysis/BasicAliasAnalysis.h"
  44. #include "llvm/Analysis/BlockFrequencyInfo.h"
  45. #include "llvm/Analysis/CaptureTracking.h"
  46. #include "llvm/Analysis/ConstantFolding.h"
  47. #include "llvm/Analysis/GlobalsModRef.h"
  48. #include "llvm/Analysis/GuardUtils.h"
  49. #include "llvm/Analysis/LazyBlockFrequencyInfo.h"
  50. #include "llvm/Analysis/Loads.h"
  51. #include "llvm/Analysis/LoopInfo.h"
  52. #include "llvm/Analysis/LoopIterator.h"
  53. #include "llvm/Analysis/LoopPass.h"
  54. #include "llvm/Analysis/MemoryBuiltins.h"
  55. #include "llvm/Analysis/MemorySSA.h"
  56. #include "llvm/Analysis/MemorySSAUpdater.h"
  57. #include "llvm/Analysis/MustExecute.h"
  58. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  59. #include "llvm/Analysis/ScalarEvolution.h"
  60. #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
  61. #include "llvm/Analysis/TargetLibraryInfo.h"
  62. #include "llvm/Analysis/ValueTracking.h"
  63. #include "llvm/IR/CFG.h"
  64. #include "llvm/IR/Constants.h"
  65. #include "llvm/IR/DataLayout.h"
  66. #include "llvm/IR/DebugInfoMetadata.h"
  67. #include "llvm/IR/DerivedTypes.h"
  68. #include "llvm/IR/Dominators.h"
  69. #include "llvm/IR/Instructions.h"
  70. #include "llvm/IR/IntrinsicInst.h"
  71. #include "llvm/IR/LLVMContext.h"
  72. #include "llvm/IR/Metadata.h"
  73. #include "llvm/IR/PatternMatch.h"
  74. #include "llvm/IR/PredIteratorCache.h"
  75. #include "llvm/InitializePasses.h"
  76. #include "llvm/Support/CommandLine.h"
  77. #include "llvm/Support/Debug.h"
  78. #include "llvm/Support/raw_ostream.h"
  79. #include "llvm/Transforms/Scalar.h"
  80. #include "llvm/Transforms/Scalar/LoopPassManager.h"
  81. #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
  82. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  83. #include "llvm/Transforms/Utils/Local.h"
  84. #include "llvm/Transforms/Utils/LoopUtils.h"
  85. #include "llvm/Transforms/Utils/SSAUpdater.h"
  86. #include <algorithm>
  87. #include <utility>
  88. using namespace llvm;
  89. #define DEBUG_TYPE "licm"
  90. STATISTIC(NumCreatedBlocks, "Number of blocks created");
  91. STATISTIC(NumClonedBranches, "Number of branches cloned");
  92. STATISTIC(NumSunk, "Number of instructions sunk out of loop");
  93. STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
  94. STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
  95. STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
  96. STATISTIC(NumPromoted, "Number of memory locations promoted to registers");
  97. /// Memory promotion is enabled by default.
  98. static cl::opt<bool>
  99. DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false),
  100. cl::desc("Disable memory promotion in LICM pass"));
  101. static cl::opt<bool> ControlFlowHoisting(
  102. "licm-control-flow-hoisting", cl::Hidden, cl::init(false),
  103. cl::desc("Enable control flow (and PHI) hoisting in LICM"));
  104. static cl::opt<uint32_t> MaxNumUsesTraversed(
  105. "licm-max-num-uses-traversed", cl::Hidden, cl::init(8),
  106. cl::desc("Max num uses visited for identifying load "
  107. "invariance in loop using invariant start (default = 8)"));
  108. // Experimental option to allow imprecision in LICM in pathological cases, in
  109. // exchange for faster compile. This is to be removed if MemorySSA starts to
  110. // address the same issue. This flag applies only when LICM uses MemorySSA
  111. // instead on AliasSetTracker. LICM calls MemorySSAWalker's
  112. // getClobberingMemoryAccess, up to the value of the Cap, getting perfect
  113. // accuracy. Afterwards, LICM will call into MemorySSA's getDefiningAccess,
  114. // which may not be precise, since optimizeUses is capped. The result is
  115. // correct, but we may not get as "far up" as possible to get which access is
  116. // clobbering the one queried.
  117. cl::opt<unsigned> llvm::SetLicmMssaOptCap(
  118. "licm-mssa-optimization-cap", cl::init(100), cl::Hidden,
  119. cl::desc("Enable imprecision in LICM in pathological cases, in exchange "
  120. "for faster compile. Caps the MemorySSA clobbering calls."));
  121. // Experimentally, memory promotion carries less importance than sinking and
  122. // hoisting. Limit when we do promotion when using MemorySSA, in order to save
  123. // compile time.
  124. cl::opt<unsigned> llvm::SetLicmMssaNoAccForPromotionCap(
  125. "licm-mssa-max-acc-promotion", cl::init(250), cl::Hidden,
  126. cl::desc("[LICM & MemorySSA] When MSSA in LICM is disabled, this has no "
  127. "effect. When MSSA in LICM is enabled, then this is the maximum "
  128. "number of accesses allowed to be present in a loop in order to "
  129. "enable memory promotion."));
  130. static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
  131. static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
  132. const LoopSafetyInfo *SafetyInfo,
  133. TargetTransformInfo *TTI, bool &FreeInLoop,
  134. bool LoopNestMode);
  135. static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
  136. BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo,
  137. MemorySSAUpdater *MSSAU, ScalarEvolution *SE,
  138. OptimizationRemarkEmitter *ORE);
  139. static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
  140. BlockFrequencyInfo *BFI, const Loop *CurLoop,
  141. ICFLoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU,
  142. OptimizationRemarkEmitter *ORE);
  143. static bool isSafeToExecuteUnconditionally(
  144. Instruction &Inst, const DominatorTree *DT, const TargetLibraryInfo *TLI,
  145. const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo,
  146. OptimizationRemarkEmitter *ORE, const Instruction *CtxI,
  147. bool AllowSpeculation);
  148. static bool pointerInvalidatedByLoop(MemoryLocation MemLoc,
  149. AliasSetTracker *CurAST, Loop *CurLoop,
  150. AAResults *AA);
  151. static bool pointerInvalidatedByLoopWithMSSA(MemorySSA *MSSA, MemoryUse *MU,
  152. Loop *CurLoop, Instruction &I,
  153. SinkAndHoistLICMFlags &Flags);
  154. static bool pointerInvalidatedByBlockWithMSSA(BasicBlock &BB, MemorySSA &MSSA,
  155. MemoryUse &MU);
  156. static Instruction *cloneInstructionInExitBlock(
  157. Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI,
  158. const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU);
  159. static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo,
  160. MemorySSAUpdater *MSSAU);
  161. static void moveInstructionBefore(Instruction &I, Instruction &Dest,
  162. ICFLoopSafetyInfo &SafetyInfo,
  163. MemorySSAUpdater *MSSAU, ScalarEvolution *SE);
  164. static void foreachMemoryAccess(MemorySSA *MSSA, Loop *L,
  165. function_ref<void(Instruction *)> Fn);
  166. static SmallVector<SmallSetVector<Value *, 8>, 0>
  167. collectPromotionCandidates(MemorySSA *MSSA, AliasAnalysis *AA, Loop *L);
  168. namespace {
  169. struct LoopInvariantCodeMotion {
  170. bool runOnLoop(Loop *L, AAResults *AA, LoopInfo *LI, DominatorTree *DT,
  171. BlockFrequencyInfo *BFI, TargetLibraryInfo *TLI,
  172. TargetTransformInfo *TTI, ScalarEvolution *SE, MemorySSA *MSSA,
  173. OptimizationRemarkEmitter *ORE, bool LoopNestMode = false);
  174. LoopInvariantCodeMotion(unsigned LicmMssaOptCap,
  175. unsigned LicmMssaNoAccForPromotionCap,
  176. bool LicmAllowSpeculation)
  177. : LicmMssaOptCap(LicmMssaOptCap),
  178. LicmMssaNoAccForPromotionCap(LicmMssaNoAccForPromotionCap),
  179. LicmAllowSpeculation(LicmAllowSpeculation) {}
  180. private:
  181. unsigned LicmMssaOptCap;
  182. unsigned LicmMssaNoAccForPromotionCap;
  183. bool LicmAllowSpeculation;
  184. };
  185. struct LegacyLICMPass : public LoopPass {
  186. static char ID; // Pass identification, replacement for typeid
  187. LegacyLICMPass(
  188. unsigned LicmMssaOptCap = SetLicmMssaOptCap,
  189. unsigned LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap,
  190. bool LicmAllowSpeculation = true)
  191. : LoopPass(ID), LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
  192. LicmAllowSpeculation) {
  193. initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry());
  194. }
  195. bool runOnLoop(Loop *L, LPPassManager &LPM) override {
  196. if (skipLoop(L))
  197. return false;
  198. LLVM_DEBUG(dbgs() << "Perform LICM on Loop with header at block "
  199. << L->getHeader()->getNameOrAsOperand() << "\n");
  200. auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
  201. MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
  202. bool hasProfileData = L->getHeader()->getParent()->hasProfileData();
  203. BlockFrequencyInfo *BFI =
  204. hasProfileData ? &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI()
  205. : nullptr;
  206. // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
  207. // pass. Function analyses need to be preserved across loop transformations
  208. // but ORE cannot be preserved (see comment before the pass definition).
  209. OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
  210. return LICM.runOnLoop(
  211. L, &getAnalysis<AAResultsWrapperPass>().getAAResults(),
  212. &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
  213. &getAnalysis<DominatorTreeWrapperPass>().getDomTree(), BFI,
  214. &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
  215. *L->getHeader()->getParent()),
  216. &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
  217. *L->getHeader()->getParent()),
  218. SE ? &SE->getSE() : nullptr, MSSA, &ORE);
  219. }
  220. /// This transformation requires natural loop information & requires that
  221. /// loop preheaders be inserted into the CFG...
  222. ///
  223. void getAnalysisUsage(AnalysisUsage &AU) const override {
  224. AU.addPreserved<DominatorTreeWrapperPass>();
  225. AU.addPreserved<LoopInfoWrapperPass>();
  226. AU.addRequired<TargetLibraryInfoWrapperPass>();
  227. AU.addRequired<MemorySSAWrapperPass>();
  228. AU.addPreserved<MemorySSAWrapperPass>();
  229. AU.addRequired<TargetTransformInfoWrapperPass>();
  230. getLoopAnalysisUsage(AU);
  231. LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
  232. AU.addPreserved<LazyBlockFrequencyInfoPass>();
  233. AU.addPreserved<LazyBranchProbabilityInfoPass>();
  234. }
  235. private:
  236. LoopInvariantCodeMotion LICM;
  237. };
  238. } // namespace
  239. PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM,
  240. LoopStandardAnalysisResults &AR, LPMUpdater &) {
  241. if (!AR.MSSA)
  242. report_fatal_error("LICM requires MemorySSA (loop-mssa)");
  243. // For the new PM, we also can't use OptimizationRemarkEmitter as an analysis
  244. // pass. Function analyses need to be preserved across loop transformations
  245. // but ORE cannot be preserved (see comment before the pass definition).
  246. OptimizationRemarkEmitter ORE(L.getHeader()->getParent());
  247. LoopInvariantCodeMotion LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
  248. LicmAllowSpeculation);
  249. if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, AR.BFI, &AR.TLI, &AR.TTI,
  250. &AR.SE, AR.MSSA, &ORE))
  251. return PreservedAnalyses::all();
  252. auto PA = getLoopPassPreservedAnalyses();
  253. PA.preserve<DominatorTreeAnalysis>();
  254. PA.preserve<LoopAnalysis>();
  255. PA.preserve<MemorySSAAnalysis>();
  256. return PA;
  257. }
  258. PreservedAnalyses LNICMPass::run(LoopNest &LN, LoopAnalysisManager &AM,
  259. LoopStandardAnalysisResults &AR,
  260. LPMUpdater &) {
  261. if (!AR.MSSA)
  262. report_fatal_error("LNICM requires MemorySSA (loop-mssa)");
  263. // For the new PM, we also can't use OptimizationRemarkEmitter as an analysis
  264. // pass. Function analyses need to be preserved across loop transformations
  265. // but ORE cannot be preserved (see comment before the pass definition).
  266. OptimizationRemarkEmitter ORE(LN.getParent());
  267. LoopInvariantCodeMotion LICM(LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
  268. LicmAllowSpeculation);
  269. Loop &OutermostLoop = LN.getOutermostLoop();
  270. bool Changed = LICM.runOnLoop(&OutermostLoop, &AR.AA, &AR.LI, &AR.DT, AR.BFI,
  271. &AR.TLI, &AR.TTI, &AR.SE, AR.MSSA, &ORE, true);
  272. if (!Changed)
  273. return PreservedAnalyses::all();
  274. auto PA = getLoopPassPreservedAnalyses();
  275. PA.preserve<DominatorTreeAnalysis>();
  276. PA.preserve<LoopAnalysis>();
  277. PA.preserve<MemorySSAAnalysis>();
  278. return PA;
  279. }
  280. char LegacyLICMPass::ID = 0;
  281. INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
  282. false, false)
  283. INITIALIZE_PASS_DEPENDENCY(LoopPass)
  284. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  285. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  286. INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
  287. INITIALIZE_PASS_DEPENDENCY(LazyBFIPass)
  288. INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
  289. false)
  290. Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
  291. Pass *llvm::createLICMPass(unsigned LicmMssaOptCap,
  292. unsigned LicmMssaNoAccForPromotionCap,
  293. bool LicmAllowSpeculation) {
  294. return new LegacyLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
  295. LicmAllowSpeculation);
  296. }
  297. llvm::SinkAndHoistLICMFlags::SinkAndHoistLICMFlags(bool IsSink, Loop *L,
  298. MemorySSA *MSSA)
  299. : SinkAndHoistLICMFlags(SetLicmMssaOptCap, SetLicmMssaNoAccForPromotionCap,
  300. IsSink, L, MSSA) {}
  301. llvm::SinkAndHoistLICMFlags::SinkAndHoistLICMFlags(
  302. unsigned LicmMssaOptCap, unsigned LicmMssaNoAccForPromotionCap, bool IsSink,
  303. Loop *L, MemorySSA *MSSA)
  304. : LicmMssaOptCap(LicmMssaOptCap),
  305. LicmMssaNoAccForPromotionCap(LicmMssaNoAccForPromotionCap),
  306. IsSink(IsSink) {
  307. assert(((L != nullptr) == (MSSA != nullptr)) &&
  308. "Unexpected values for SinkAndHoistLICMFlags");
  309. if (!MSSA)
  310. return;
  311. unsigned AccessCapCount = 0;
  312. for (auto *BB : L->getBlocks())
  313. if (const auto *Accesses = MSSA->getBlockAccesses(BB))
  314. for (const auto &MA : *Accesses) {
  315. (void)MA;
  316. ++AccessCapCount;
  317. if (AccessCapCount > LicmMssaNoAccForPromotionCap) {
  318. NoOfMemAccTooLarge = true;
  319. return;
  320. }
  321. }
  322. }
  323. /// Hoist expressions out of the specified loop. Note, alias info for inner
  324. /// loop is not preserved so it is not a good idea to run LICM multiple
  325. /// times on one loop.
  326. bool LoopInvariantCodeMotion::runOnLoop(
  327. Loop *L, AAResults *AA, LoopInfo *LI, DominatorTree *DT,
  328. BlockFrequencyInfo *BFI, TargetLibraryInfo *TLI, TargetTransformInfo *TTI,
  329. ScalarEvolution *SE, MemorySSA *MSSA, OptimizationRemarkEmitter *ORE,
  330. bool LoopNestMode) {
  331. bool Changed = false;
  332. assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
  333. // If this loop has metadata indicating that LICM is not to be performed then
  334. // just exit.
  335. if (hasDisableLICMTransformsHint(L)) {
  336. return false;
  337. }
  338. // Don't sink stores from loops with coroutine suspend instructions.
  339. // LICM would sink instructions into the default destination of
  340. // the coroutine switch. The default destination of the switch is to
  341. // handle the case where the coroutine is suspended, by which point the
  342. // coroutine frame may have been destroyed. No instruction can be sunk there.
  343. // FIXME: This would unfortunately hurt the performance of coroutines, however
  344. // there is currently no general solution for this. Similar issues could also
  345. // potentially happen in other passes where instructions are being moved
  346. // across that edge.
  347. bool HasCoroSuspendInst = llvm::any_of(L->getBlocks(), [](BasicBlock *BB) {
  348. return llvm::any_of(*BB, [](Instruction &I) {
  349. IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
  350. return II && II->getIntrinsicID() == Intrinsic::coro_suspend;
  351. });
  352. });
  353. MemorySSAUpdater MSSAU(MSSA);
  354. SinkAndHoistLICMFlags Flags(LicmMssaOptCap, LicmMssaNoAccForPromotionCap,
  355. /*IsSink=*/true, L, MSSA);
  356. // Get the preheader block to move instructions into...
  357. BasicBlock *Preheader = L->getLoopPreheader();
  358. // Compute loop safety information.
  359. ICFLoopSafetyInfo SafetyInfo;
  360. SafetyInfo.computeLoopSafetyInfo(L);
  361. // We want to visit all of the instructions in this loop... that are not parts
  362. // of our subloops (they have already had their invariants hoisted out of
  363. // their loop, into this loop, so there is no need to process the BODIES of
  364. // the subloops).
  365. //
  366. // Traverse the body of the loop in depth first order on the dominator tree so
  367. // that we are guaranteed to see definitions before we see uses. This allows
  368. // us to sink instructions in one pass, without iteration. After sinking
  369. // instructions, we perform another pass to hoist them out of the loop.
  370. if (L->hasDedicatedExits())
  371. Changed |= LoopNestMode
  372. ? sinkRegionForLoopNest(DT->getNode(L->getHeader()), AA, LI,
  373. DT, BFI, TLI, TTI, L, &MSSAU,
  374. &SafetyInfo, Flags, ORE)
  375. : sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, BFI,
  376. TLI, TTI, L, &MSSAU, &SafetyInfo, Flags, ORE);
  377. Flags.setIsSink(false);
  378. if (Preheader)
  379. Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, BFI, TLI, L,
  380. &MSSAU, SE, &SafetyInfo, Flags, ORE, LoopNestMode,
  381. LicmAllowSpeculation);
  382. // Now that all loop invariants have been removed from the loop, promote any
  383. // memory references to scalars that we can.
  384. // Don't sink stores from loops without dedicated block exits. Exits
  385. // containing indirect branches are not transformed by loop simplify,
  386. // make sure we catch that. An additional load may be generated in the
  387. // preheader for SSA updater, so also avoid sinking when no preheader
  388. // is available.
  389. if (!DisablePromotion && Preheader && L->hasDedicatedExits() &&
  390. !Flags.tooManyMemoryAccesses() && !HasCoroSuspendInst) {
  391. // Figure out the loop exits and their insertion points
  392. SmallVector<BasicBlock *, 8> ExitBlocks;
  393. L->getUniqueExitBlocks(ExitBlocks);
  394. // We can't insert into a catchswitch.
  395. bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
  396. return isa<CatchSwitchInst>(Exit->getTerminator());
  397. });
  398. if (!HasCatchSwitch) {
  399. SmallVector<Instruction *, 8> InsertPts;
  400. SmallVector<MemoryAccess *, 8> MSSAInsertPts;
  401. InsertPts.reserve(ExitBlocks.size());
  402. MSSAInsertPts.reserve(ExitBlocks.size());
  403. for (BasicBlock *ExitBlock : ExitBlocks) {
  404. InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
  405. MSSAInsertPts.push_back(nullptr);
  406. }
  407. PredIteratorCache PIC;
  408. // Promoting one set of accesses may make the pointers for another set
  409. // loop invariant, so run this in a loop (with the MaybePromotable set
  410. // decreasing in size over time).
  411. bool Promoted = false;
  412. bool LocalPromoted;
  413. do {
  414. LocalPromoted = false;
  415. for (const SmallSetVector<Value *, 8> &PointerMustAliases :
  416. collectPromotionCandidates(MSSA, AA, L)) {
  417. LocalPromoted |= promoteLoopAccessesToScalars(
  418. PointerMustAliases, ExitBlocks, InsertPts, MSSAInsertPts, PIC, LI,
  419. DT, TLI, L, &MSSAU, &SafetyInfo, ORE, LicmAllowSpeculation);
  420. }
  421. Promoted |= LocalPromoted;
  422. } while (LocalPromoted);
  423. // Once we have promoted values across the loop body we have to
  424. // recursively reform LCSSA as any nested loop may now have values defined
  425. // within the loop used in the outer loop.
  426. // FIXME: This is really heavy handed. It would be a bit better to use an
  427. // SSAUpdater strategy during promotion that was LCSSA aware and reformed
  428. // it as it went.
  429. if (Promoted)
  430. formLCSSARecursively(*L, *DT, LI, SE);
  431. Changed |= Promoted;
  432. }
  433. }
  434. // Check that neither this loop nor its parent have had LCSSA broken. LICM is
  435. // specifically moving instructions across the loop boundary and so it is
  436. // especially in need of basic functional correctness checking here.
  437. assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
  438. assert((L->isOutermost() || L->getParentLoop()->isLCSSAForm(*DT)) &&
  439. "Parent loop not left in LCSSA form after LICM!");
  440. if (VerifyMemorySSA)
  441. MSSA->verifyMemorySSA();
  442. if (Changed && SE)
  443. SE->forgetLoopDispositions(L);
  444. return Changed;
  445. }
  446. /// Walk the specified region of the CFG (defined by all blocks dominated by
  447. /// the specified block, and that are in the current loop) in reverse depth
  448. /// first order w.r.t the DominatorTree. This allows us to visit uses before
  449. /// definitions, allowing us to sink a loop body in one pass without iteration.
  450. ///
  451. bool llvm::sinkRegion(DomTreeNode *N, AAResults *AA, LoopInfo *LI,
  452. DominatorTree *DT, BlockFrequencyInfo *BFI,
  453. TargetLibraryInfo *TLI, TargetTransformInfo *TTI,
  454. Loop *CurLoop, MemorySSAUpdater *MSSAU,
  455. ICFLoopSafetyInfo *SafetyInfo,
  456. SinkAndHoistLICMFlags &Flags,
  457. OptimizationRemarkEmitter *ORE, Loop *OutermostLoop) {
  458. // Verify inputs.
  459. assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
  460. CurLoop != nullptr && MSSAU != nullptr && SafetyInfo != nullptr &&
  461. "Unexpected input to sinkRegion.");
  462. // We want to visit children before parents. We will enque all the parents
  463. // before their children in the worklist and process the worklist in reverse
  464. // order.
  465. SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
  466. bool Changed = false;
  467. for (DomTreeNode *DTN : reverse(Worklist)) {
  468. BasicBlock *BB = DTN->getBlock();
  469. // Only need to process the contents of this block if it is not part of a
  470. // subloop (which would already have been processed).
  471. if (inSubLoop(BB, CurLoop, LI))
  472. continue;
  473. for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
  474. Instruction &I = *--II;
  475. // The instruction is not used in the loop if it is dead. In this case,
  476. // we just delete it instead of sinking it.
  477. if (isInstructionTriviallyDead(&I, TLI)) {
  478. LLVM_DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
  479. salvageKnowledge(&I);
  480. salvageDebugInfo(I);
  481. ++II;
  482. eraseInstruction(I, *SafetyInfo, MSSAU);
  483. Changed = true;
  484. continue;
  485. }
  486. // Check to see if we can sink this instruction to the exit blocks
  487. // of the loop. We can do this if the all users of the instruction are
  488. // outside of the loop. In this case, it doesn't even matter if the
  489. // operands of the instruction are loop invariant.
  490. //
  491. bool FreeInLoop = false;
  492. bool LoopNestMode = OutermostLoop != nullptr;
  493. if (!I.mayHaveSideEffects() &&
  494. isNotUsedOrFreeInLoop(I, LoopNestMode ? OutermostLoop : CurLoop,
  495. SafetyInfo, TTI, FreeInLoop, LoopNestMode) &&
  496. canSinkOrHoistInst(I, AA, DT, CurLoop, /*CurAST*/nullptr, MSSAU, true,
  497. &Flags, ORE)) {
  498. if (sink(I, LI, DT, BFI, CurLoop, SafetyInfo, MSSAU, ORE)) {
  499. if (!FreeInLoop) {
  500. ++II;
  501. salvageDebugInfo(I);
  502. eraseInstruction(I, *SafetyInfo, MSSAU);
  503. }
  504. Changed = true;
  505. }
  506. }
  507. }
  508. }
  509. if (VerifyMemorySSA)
  510. MSSAU->getMemorySSA()->verifyMemorySSA();
  511. return Changed;
  512. }
  513. bool llvm::sinkRegionForLoopNest(
  514. DomTreeNode *N, AAResults *AA, LoopInfo *LI, DominatorTree *DT,
  515. BlockFrequencyInfo *BFI, TargetLibraryInfo *TLI, TargetTransformInfo *TTI,
  516. Loop *CurLoop, MemorySSAUpdater *MSSAU, ICFLoopSafetyInfo *SafetyInfo,
  517. SinkAndHoistLICMFlags &Flags, OptimizationRemarkEmitter *ORE) {
  518. bool Changed = false;
  519. SmallPriorityWorklist<Loop *, 4> Worklist;
  520. Worklist.insert(CurLoop);
  521. appendLoopsToWorklist(*CurLoop, Worklist);
  522. while (!Worklist.empty()) {
  523. Loop *L = Worklist.pop_back_val();
  524. Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, BFI, TLI,
  525. TTI, L, MSSAU, SafetyInfo, Flags, ORE, CurLoop);
  526. }
  527. return Changed;
  528. }
  529. namespace {
  530. // This is a helper class for hoistRegion to make it able to hoist control flow
  531. // in order to be able to hoist phis. The way this works is that we initially
  532. // start hoisting to the loop preheader, and when we see a loop invariant branch
  533. // we make note of this. When we then come to hoist an instruction that's
  534. // conditional on such a branch we duplicate the branch and the relevant control
  535. // flow, then hoist the instruction into the block corresponding to its original
  536. // block in the duplicated control flow.
  537. class ControlFlowHoister {
  538. private:
  539. // Information about the loop we are hoisting from
  540. LoopInfo *LI;
  541. DominatorTree *DT;
  542. Loop *CurLoop;
  543. MemorySSAUpdater *MSSAU;
  544. // A map of blocks in the loop to the block their instructions will be hoisted
  545. // to.
  546. DenseMap<BasicBlock *, BasicBlock *> HoistDestinationMap;
  547. // The branches that we can hoist, mapped to the block that marks a
  548. // convergence point of their control flow.
  549. DenseMap<BranchInst *, BasicBlock *> HoistableBranches;
  550. public:
  551. ControlFlowHoister(LoopInfo *LI, DominatorTree *DT, Loop *CurLoop,
  552. MemorySSAUpdater *MSSAU)
  553. : LI(LI), DT(DT), CurLoop(CurLoop), MSSAU(MSSAU) {}
  554. void registerPossiblyHoistableBranch(BranchInst *BI) {
  555. // We can only hoist conditional branches with loop invariant operands.
  556. if (!ControlFlowHoisting || !BI->isConditional() ||
  557. !CurLoop->hasLoopInvariantOperands(BI))
  558. return;
  559. // The branch destinations need to be in the loop, and we don't gain
  560. // anything by duplicating conditional branches with duplicate successors,
  561. // as it's essentially the same as an unconditional branch.
  562. BasicBlock *TrueDest = BI->getSuccessor(0);
  563. BasicBlock *FalseDest = BI->getSuccessor(1);
  564. if (!CurLoop->contains(TrueDest) || !CurLoop->contains(FalseDest) ||
  565. TrueDest == FalseDest)
  566. return;
  567. // We can hoist BI if one branch destination is the successor of the other,
  568. // or both have common successor which we check by seeing if the
  569. // intersection of their successors is non-empty.
  570. // TODO: This could be expanded to allowing branches where both ends
  571. // eventually converge to a single block.
  572. SmallPtrSet<BasicBlock *, 4> TrueDestSucc, FalseDestSucc;
  573. TrueDestSucc.insert(succ_begin(TrueDest), succ_end(TrueDest));
  574. FalseDestSucc.insert(succ_begin(FalseDest), succ_end(FalseDest));
  575. BasicBlock *CommonSucc = nullptr;
  576. if (TrueDestSucc.count(FalseDest)) {
  577. CommonSucc = FalseDest;
  578. } else if (FalseDestSucc.count(TrueDest)) {
  579. CommonSucc = TrueDest;
  580. } else {
  581. set_intersect(TrueDestSucc, FalseDestSucc);
  582. // If there's one common successor use that.
  583. if (TrueDestSucc.size() == 1)
  584. CommonSucc = *TrueDestSucc.begin();
  585. // If there's more than one pick whichever appears first in the block list
  586. // (we can't use the value returned by TrueDestSucc.begin() as it's
  587. // unpredicatable which element gets returned).
  588. else if (!TrueDestSucc.empty()) {
  589. Function *F = TrueDest->getParent();
  590. auto IsSucc = [&](BasicBlock &BB) { return TrueDestSucc.count(&BB); };
  591. auto It = llvm::find_if(*F, IsSucc);
  592. assert(It != F->end() && "Could not find successor in function");
  593. CommonSucc = &*It;
  594. }
  595. }
  596. // The common successor has to be dominated by the branch, as otherwise
  597. // there will be some other path to the successor that will not be
  598. // controlled by this branch so any phi we hoist would be controlled by the
  599. // wrong condition. This also takes care of avoiding hoisting of loop back
  600. // edges.
  601. // TODO: In some cases this could be relaxed if the successor is dominated
  602. // by another block that's been hoisted and we can guarantee that the
  603. // control flow has been replicated exactly.
  604. if (CommonSucc && DT->dominates(BI, CommonSucc))
  605. HoistableBranches[BI] = CommonSucc;
  606. }
  607. bool canHoistPHI(PHINode *PN) {
  608. // The phi must have loop invariant operands.
  609. if (!ControlFlowHoisting || !CurLoop->hasLoopInvariantOperands(PN))
  610. return false;
  611. // We can hoist phis if the block they are in is the target of hoistable
  612. // branches which cover all of the predecessors of the block.
  613. SmallPtrSet<BasicBlock *, 8> PredecessorBlocks;
  614. BasicBlock *BB = PN->getParent();
  615. for (BasicBlock *PredBB : predecessors(BB))
  616. PredecessorBlocks.insert(PredBB);
  617. // If we have less predecessor blocks than predecessors then the phi will
  618. // have more than one incoming value for the same block which we can't
  619. // handle.
  620. // TODO: This could be handled be erasing some of the duplicate incoming
  621. // values.
  622. if (PredecessorBlocks.size() != pred_size(BB))
  623. return false;
  624. for (auto &Pair : HoistableBranches) {
  625. if (Pair.second == BB) {
  626. // Which blocks are predecessors via this branch depends on if the
  627. // branch is triangle-like or diamond-like.
  628. if (Pair.first->getSuccessor(0) == BB) {
  629. PredecessorBlocks.erase(Pair.first->getParent());
  630. PredecessorBlocks.erase(Pair.first->getSuccessor(1));
  631. } else if (Pair.first->getSuccessor(1) == BB) {
  632. PredecessorBlocks.erase(Pair.first->getParent());
  633. PredecessorBlocks.erase(Pair.first->getSuccessor(0));
  634. } else {
  635. PredecessorBlocks.erase(Pair.first->getSuccessor(0));
  636. PredecessorBlocks.erase(Pair.first->getSuccessor(1));
  637. }
  638. }
  639. }
  640. // PredecessorBlocks will now be empty if for every predecessor of BB we
  641. // found a hoistable branch source.
  642. return PredecessorBlocks.empty();
  643. }
  644. BasicBlock *getOrCreateHoistedBlock(BasicBlock *BB) {
  645. if (!ControlFlowHoisting)
  646. return CurLoop->getLoopPreheader();
  647. // If BB has already been hoisted, return that
  648. if (HoistDestinationMap.count(BB))
  649. return HoistDestinationMap[BB];
  650. // Check if this block is conditional based on a pending branch
  651. auto HasBBAsSuccessor =
  652. [&](DenseMap<BranchInst *, BasicBlock *>::value_type &Pair) {
  653. return BB != Pair.second && (Pair.first->getSuccessor(0) == BB ||
  654. Pair.first->getSuccessor(1) == BB);
  655. };
  656. auto It = llvm::find_if(HoistableBranches, HasBBAsSuccessor);
  657. // If not involved in a pending branch, hoist to preheader
  658. BasicBlock *InitialPreheader = CurLoop->getLoopPreheader();
  659. if (It == HoistableBranches.end()) {
  660. LLVM_DEBUG(dbgs() << "LICM using "
  661. << InitialPreheader->getNameOrAsOperand()
  662. << " as hoist destination for "
  663. << BB->getNameOrAsOperand() << "\n");
  664. HoistDestinationMap[BB] = InitialPreheader;
  665. return InitialPreheader;
  666. }
  667. BranchInst *BI = It->first;
  668. assert(std::find_if(++It, HoistableBranches.end(), HasBBAsSuccessor) ==
  669. HoistableBranches.end() &&
  670. "BB is expected to be the target of at most one branch");
  671. LLVMContext &C = BB->getContext();
  672. BasicBlock *TrueDest = BI->getSuccessor(0);
  673. BasicBlock *FalseDest = BI->getSuccessor(1);
  674. BasicBlock *CommonSucc = HoistableBranches[BI];
  675. BasicBlock *HoistTarget = getOrCreateHoistedBlock(BI->getParent());
  676. // Create hoisted versions of blocks that currently don't have them
  677. auto CreateHoistedBlock = [&](BasicBlock *Orig) {
  678. if (HoistDestinationMap.count(Orig))
  679. return HoistDestinationMap[Orig];
  680. BasicBlock *New =
  681. BasicBlock::Create(C, Orig->getName() + ".licm", Orig->getParent());
  682. HoistDestinationMap[Orig] = New;
  683. DT->addNewBlock(New, HoistTarget);
  684. if (CurLoop->getParentLoop())
  685. CurLoop->getParentLoop()->addBasicBlockToLoop(New, *LI);
  686. ++NumCreatedBlocks;
  687. LLVM_DEBUG(dbgs() << "LICM created " << New->getName()
  688. << " as hoist destination for " << Orig->getName()
  689. << "\n");
  690. return New;
  691. };
  692. BasicBlock *HoistTrueDest = CreateHoistedBlock(TrueDest);
  693. BasicBlock *HoistFalseDest = CreateHoistedBlock(FalseDest);
  694. BasicBlock *HoistCommonSucc = CreateHoistedBlock(CommonSucc);
  695. // Link up these blocks with branches.
  696. if (!HoistCommonSucc->getTerminator()) {
  697. // The new common successor we've generated will branch to whatever that
  698. // hoist target branched to.
  699. BasicBlock *TargetSucc = HoistTarget->getSingleSuccessor();
  700. assert(TargetSucc && "Expected hoist target to have a single successor");
  701. HoistCommonSucc->moveBefore(TargetSucc);
  702. BranchInst::Create(TargetSucc, HoistCommonSucc);
  703. }
  704. if (!HoistTrueDest->getTerminator()) {
  705. HoistTrueDest->moveBefore(HoistCommonSucc);
  706. BranchInst::Create(HoistCommonSucc, HoistTrueDest);
  707. }
  708. if (!HoistFalseDest->getTerminator()) {
  709. HoistFalseDest->moveBefore(HoistCommonSucc);
  710. BranchInst::Create(HoistCommonSucc, HoistFalseDest);
  711. }
  712. // If BI is being cloned to what was originally the preheader then
  713. // HoistCommonSucc will now be the new preheader.
  714. if (HoistTarget == InitialPreheader) {
  715. // Phis in the loop header now need to use the new preheader.
  716. InitialPreheader->replaceSuccessorsPhiUsesWith(HoistCommonSucc);
  717. MSSAU->wireOldPredecessorsToNewImmediatePredecessor(
  718. HoistTarget->getSingleSuccessor(), HoistCommonSucc, {HoistTarget});
  719. // The new preheader dominates the loop header.
  720. DomTreeNode *PreheaderNode = DT->getNode(HoistCommonSucc);
  721. DomTreeNode *HeaderNode = DT->getNode(CurLoop->getHeader());
  722. DT->changeImmediateDominator(HeaderNode, PreheaderNode);
  723. // The preheader hoist destination is now the new preheader, with the
  724. // exception of the hoist destination of this branch.
  725. for (auto &Pair : HoistDestinationMap)
  726. if (Pair.second == InitialPreheader && Pair.first != BI->getParent())
  727. Pair.second = HoistCommonSucc;
  728. }
  729. // Now finally clone BI.
  730. ReplaceInstWithInst(
  731. HoistTarget->getTerminator(),
  732. BranchInst::Create(HoistTrueDest, HoistFalseDest, BI->getCondition()));
  733. ++NumClonedBranches;
  734. assert(CurLoop->getLoopPreheader() &&
  735. "Hoisting blocks should not have destroyed preheader");
  736. return HoistDestinationMap[BB];
  737. }
  738. };
  739. } // namespace
  740. /// Walk the specified region of the CFG (defined by all blocks dominated by
  741. /// the specified block, and that are in the current loop) in depth first
  742. /// order w.r.t the DominatorTree. This allows us to visit definitions before
  743. /// uses, allowing us to hoist a loop body in one pass without iteration.
  744. ///
  745. bool llvm::hoistRegion(DomTreeNode *N, AAResults *AA, LoopInfo *LI,
  746. DominatorTree *DT, BlockFrequencyInfo *BFI,
  747. TargetLibraryInfo *TLI, Loop *CurLoop,
  748. MemorySSAUpdater *MSSAU, ScalarEvolution *SE,
  749. ICFLoopSafetyInfo *SafetyInfo,
  750. SinkAndHoistLICMFlags &Flags,
  751. OptimizationRemarkEmitter *ORE, bool LoopNestMode,
  752. bool AllowSpeculation) {
  753. // Verify inputs.
  754. assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
  755. CurLoop != nullptr && MSSAU != nullptr && SafetyInfo != nullptr &&
  756. "Unexpected input to hoistRegion.");
  757. ControlFlowHoister CFH(LI, DT, CurLoop, MSSAU);
  758. // Keep track of instructions that have been hoisted, as they may need to be
  759. // re-hoisted if they end up not dominating all of their uses.
  760. SmallVector<Instruction *, 16> HoistedInstructions;
  761. // For PHI hoisting to work we need to hoist blocks before their successors.
  762. // We can do this by iterating through the blocks in the loop in reverse
  763. // post-order.
  764. LoopBlocksRPO Worklist(CurLoop);
  765. Worklist.perform(LI);
  766. bool Changed = false;
  767. for (BasicBlock *BB : Worklist) {
  768. // Only need to process the contents of this block if it is not part of a
  769. // subloop (which would already have been processed).
  770. if (!LoopNestMode && inSubLoop(BB, CurLoop, LI))
  771. continue;
  772. for (Instruction &I : llvm::make_early_inc_range(*BB)) {
  773. // Try constant folding this instruction. If all the operands are
  774. // constants, it is technically hoistable, but it would be better to
  775. // just fold it.
  776. if (Constant *C = ConstantFoldInstruction(
  777. &I, I.getModule()->getDataLayout(), TLI)) {
  778. LLVM_DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C
  779. << '\n');
  780. // FIXME MSSA: Such replacements may make accesses unoptimized (D51960).
  781. I.replaceAllUsesWith(C);
  782. if (isInstructionTriviallyDead(&I, TLI))
  783. eraseInstruction(I, *SafetyInfo, MSSAU);
  784. Changed = true;
  785. continue;
  786. }
  787. // Try hoisting the instruction out to the preheader. We can only do
  788. // this if all of the operands of the instruction are loop invariant and
  789. // if it is safe to hoist the instruction. We also check block frequency
  790. // to make sure instruction only gets hoisted into colder blocks.
  791. // TODO: It may be safe to hoist if we are hoisting to a conditional block
  792. // and we have accurately duplicated the control flow from the loop header
  793. // to that block.
  794. if (CurLoop->hasLoopInvariantOperands(&I) &&
  795. canSinkOrHoistInst(I, AA, DT, CurLoop, /*CurAST*/ nullptr, MSSAU,
  796. true, &Flags, ORE) &&
  797. isSafeToExecuteUnconditionally(
  798. I, DT, TLI, CurLoop, SafetyInfo, ORE,
  799. CurLoop->getLoopPreheader()->getTerminator(), AllowSpeculation)) {
  800. hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
  801. MSSAU, SE, ORE);
  802. HoistedInstructions.push_back(&I);
  803. Changed = true;
  804. continue;
  805. }
  806. // Attempt to remove floating point division out of the loop by
  807. // converting it to a reciprocal multiplication.
  808. if (I.getOpcode() == Instruction::FDiv && I.hasAllowReciprocal() &&
  809. CurLoop->isLoopInvariant(I.getOperand(1))) {
  810. auto Divisor = I.getOperand(1);
  811. auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0);
  812. auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);
  813. ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags());
  814. SafetyInfo->insertInstructionTo(ReciprocalDivisor, I.getParent());
  815. ReciprocalDivisor->insertBefore(&I);
  816. auto Product =
  817. BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor);
  818. Product->setFastMathFlags(I.getFastMathFlags());
  819. SafetyInfo->insertInstructionTo(Product, I.getParent());
  820. Product->insertAfter(&I);
  821. I.replaceAllUsesWith(Product);
  822. eraseInstruction(I, *SafetyInfo, MSSAU);
  823. hoist(*ReciprocalDivisor, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB),
  824. SafetyInfo, MSSAU, SE, ORE);
  825. HoistedInstructions.push_back(ReciprocalDivisor);
  826. Changed = true;
  827. continue;
  828. }
  829. auto IsInvariantStart = [&](Instruction &I) {
  830. using namespace PatternMatch;
  831. return I.use_empty() &&
  832. match(&I, m_Intrinsic<Intrinsic::invariant_start>());
  833. };
  834. auto MustExecuteWithoutWritesBefore = [&](Instruction &I) {
  835. return SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop) &&
  836. SafetyInfo->doesNotWriteMemoryBefore(I, CurLoop);
  837. };
  838. if ((IsInvariantStart(I) || isGuard(&I)) &&
  839. CurLoop->hasLoopInvariantOperands(&I) &&
  840. MustExecuteWithoutWritesBefore(I)) {
  841. hoist(I, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
  842. MSSAU, SE, ORE);
  843. HoistedInstructions.push_back(&I);
  844. Changed = true;
  845. continue;
  846. }
  847. if (PHINode *PN = dyn_cast<PHINode>(&I)) {
  848. if (CFH.canHoistPHI(PN)) {
  849. // Redirect incoming blocks first to ensure that we create hoisted
  850. // versions of those blocks before we hoist the phi.
  851. for (unsigned int i = 0; i < PN->getNumIncomingValues(); ++i)
  852. PN->setIncomingBlock(
  853. i, CFH.getOrCreateHoistedBlock(PN->getIncomingBlock(i)));
  854. hoist(*PN, DT, CurLoop, CFH.getOrCreateHoistedBlock(BB), SafetyInfo,
  855. MSSAU, SE, ORE);
  856. assert(DT->dominates(PN, BB) && "Conditional PHIs not expected");
  857. Changed = true;
  858. continue;
  859. }
  860. }
  861. // Remember possibly hoistable branches so we can actually hoist them
  862. // later if needed.
  863. if (BranchInst *BI = dyn_cast<BranchInst>(&I))
  864. CFH.registerPossiblyHoistableBranch(BI);
  865. }
  866. }
  867. // If we hoisted instructions to a conditional block they may not dominate
  868. // their uses that weren't hoisted (such as phis where some operands are not
  869. // loop invariant). If so make them unconditional by moving them to their
  870. // immediate dominator. We iterate through the instructions in reverse order
  871. // which ensures that when we rehoist an instruction we rehoist its operands,
  872. // and also keep track of where in the block we are rehoisting to to make sure
  873. // that we rehoist instructions before the instructions that use them.
  874. Instruction *HoistPoint = nullptr;
  875. if (ControlFlowHoisting) {
  876. for (Instruction *I : reverse(HoistedInstructions)) {
  877. if (!llvm::all_of(I->uses(),
  878. [&](Use &U) { return DT->dominates(I, U); })) {
  879. BasicBlock *Dominator =
  880. DT->getNode(I->getParent())->getIDom()->getBlock();
  881. if (!HoistPoint || !DT->dominates(HoistPoint->getParent(), Dominator)) {
  882. if (HoistPoint)
  883. assert(DT->dominates(Dominator, HoistPoint->getParent()) &&
  884. "New hoist point expected to dominate old hoist point");
  885. HoistPoint = Dominator->getTerminator();
  886. }
  887. LLVM_DEBUG(dbgs() << "LICM rehoisting to "
  888. << HoistPoint->getParent()->getNameOrAsOperand()
  889. << ": " << *I << "\n");
  890. moveInstructionBefore(*I, *HoistPoint, *SafetyInfo, MSSAU, SE);
  891. HoistPoint = I;
  892. Changed = true;
  893. }
  894. }
  895. }
  896. if (VerifyMemorySSA)
  897. MSSAU->getMemorySSA()->verifyMemorySSA();
  898. // Now that we've finished hoisting make sure that LI and DT are still
  899. // valid.
  900. #ifdef EXPENSIVE_CHECKS
  901. if (Changed) {
  902. assert(DT->verify(DominatorTree::VerificationLevel::Fast) &&
  903. "Dominator tree verification failed");
  904. LI->verify(*DT);
  905. }
  906. #endif
  907. return Changed;
  908. }
  909. // Return true if LI is invariant within scope of the loop. LI is invariant if
  910. // CurLoop is dominated by an invariant.start representing the same memory
  911. // location and size as the memory location LI loads from, and also the
  912. // invariant.start has no uses.
  913. static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT,
  914. Loop *CurLoop) {
  915. Value *Addr = LI->getOperand(0);
  916. const DataLayout &DL = LI->getModule()->getDataLayout();
  917. const TypeSize LocSizeInBits = DL.getTypeSizeInBits(LI->getType());
  918. // It is not currently possible for clang to generate an invariant.start
  919. // intrinsic with scalable vector types because we don't support thread local
  920. // sizeless types and we don't permit sizeless types in structs or classes.
  921. // Furthermore, even if support is added for this in future the intrinsic
  922. // itself is defined to have a size of -1 for variable sized objects. This
  923. // makes it impossible to verify if the intrinsic envelops our region of
  924. // interest. For example, both <vscale x 32 x i8> and <vscale x 16 x i8>
  925. // types would have a -1 parameter, but the former is clearly double the size
  926. // of the latter.
  927. if (LocSizeInBits.isScalable())
  928. return false;
  929. // if the type is i8 addrspace(x)*, we know this is the type of
  930. // llvm.invariant.start operand
  931. auto *PtrInt8Ty = PointerType::get(Type::getInt8Ty(LI->getContext()),
  932. LI->getPointerAddressSpace());
  933. unsigned BitcastsVisited = 0;
  934. // Look through bitcasts until we reach the i8* type (this is invariant.start
  935. // operand type).
  936. while (Addr->getType() != PtrInt8Ty) {
  937. auto *BC = dyn_cast<BitCastInst>(Addr);
  938. // Avoid traversing high number of bitcast uses.
  939. if (++BitcastsVisited > MaxNumUsesTraversed || !BC)
  940. return false;
  941. Addr = BC->getOperand(0);
  942. }
  943. // If we've ended up at a global/constant, bail. We shouldn't be looking at
  944. // uselists for non-local Values in a loop pass.
  945. if (isa<Constant>(Addr))
  946. return false;
  947. unsigned UsesVisited = 0;
  948. // Traverse all uses of the load operand value, to see if invariant.start is
  949. // one of the uses, and whether it dominates the load instruction.
  950. for (auto *U : Addr->users()) {
  951. // Avoid traversing for Load operand with high number of users.
  952. if (++UsesVisited > MaxNumUsesTraversed)
  953. return false;
  954. IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
  955. // If there are escaping uses of invariant.start instruction, the load maybe
  956. // non-invariant.
  957. if (!II || II->getIntrinsicID() != Intrinsic::invariant_start ||
  958. !II->use_empty())
  959. continue;
  960. ConstantInt *InvariantSize = cast<ConstantInt>(II->getArgOperand(0));
  961. // The intrinsic supports having a -1 argument for variable sized objects
  962. // so we should check for that here.
  963. if (InvariantSize->isNegative())
  964. continue;
  965. uint64_t InvariantSizeInBits = InvariantSize->getSExtValue() * 8;
  966. // Confirm the invariant.start location size contains the load operand size
  967. // in bits. Also, the invariant.start should dominate the load, and we
  968. // should not hoist the load out of a loop that contains this dominating
  969. // invariant.start.
  970. if (LocSizeInBits.getFixedSize() <= InvariantSizeInBits &&
  971. DT->properlyDominates(II->getParent(), CurLoop->getHeader()))
  972. return true;
  973. }
  974. return false;
  975. }
  976. namespace {
  977. /// Return true if-and-only-if we know how to (mechanically) both hoist and
  978. /// sink a given instruction out of a loop. Does not address legality
  979. /// concerns such as aliasing or speculation safety.
  980. bool isHoistableAndSinkableInst(Instruction &I) {
  981. // Only these instructions are hoistable/sinkable.
  982. return (isa<LoadInst>(I) || isa<StoreInst>(I) || isa<CallInst>(I) ||
  983. isa<FenceInst>(I) || isa<CastInst>(I) || isa<UnaryOperator>(I) ||
  984. isa<BinaryOperator>(I) || isa<SelectInst>(I) ||
  985. isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||
  986. isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
  987. isa<ShuffleVectorInst>(I) || isa<ExtractValueInst>(I) ||
  988. isa<InsertValueInst>(I) || isa<FreezeInst>(I));
  989. }
  990. /// Return true if all of the alias sets within this AST are known not to
  991. /// contain a Mod, or if MSSA knows there are no MemoryDefs in the loop.
  992. bool isReadOnly(AliasSetTracker *CurAST, const MemorySSAUpdater *MSSAU,
  993. const Loop *L) {
  994. if (CurAST) {
  995. for (AliasSet &AS : *CurAST) {
  996. if (!AS.isForwardingAliasSet() && AS.isMod()) {
  997. return false;
  998. }
  999. }
  1000. return true;
  1001. } else { /*MSSAU*/
  1002. for (auto *BB : L->getBlocks())
  1003. if (MSSAU->getMemorySSA()->getBlockDefs(BB))
  1004. return false;
  1005. return true;
  1006. }
  1007. }
  1008. /// Return true if I is the only Instruction with a MemoryAccess in L.
  1009. bool isOnlyMemoryAccess(const Instruction *I, const Loop *L,
  1010. const MemorySSAUpdater *MSSAU) {
  1011. for (auto *BB : L->getBlocks())
  1012. if (auto *Accs = MSSAU->getMemorySSA()->getBlockAccesses(BB)) {
  1013. int NotAPhi = 0;
  1014. for (const auto &Acc : *Accs) {
  1015. if (isa<MemoryPhi>(&Acc))
  1016. continue;
  1017. const auto *MUD = cast<MemoryUseOrDef>(&Acc);
  1018. if (MUD->getMemoryInst() != I || NotAPhi++ == 1)
  1019. return false;
  1020. }
  1021. }
  1022. return true;
  1023. }
  1024. }
  1025. bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,
  1026. Loop *CurLoop, AliasSetTracker *CurAST,
  1027. MemorySSAUpdater *MSSAU,
  1028. bool TargetExecutesOncePerLoop,
  1029. SinkAndHoistLICMFlags *Flags,
  1030. OptimizationRemarkEmitter *ORE) {
  1031. assert(((CurAST != nullptr) ^ (MSSAU != nullptr)) &&
  1032. "Either AliasSetTracker or MemorySSA should be initialized.");
  1033. // If we don't understand the instruction, bail early.
  1034. if (!isHoistableAndSinkableInst(I))
  1035. return false;
  1036. MemorySSA *MSSA = MSSAU ? MSSAU->getMemorySSA() : nullptr;
  1037. if (MSSA)
  1038. assert(Flags != nullptr && "Flags cannot be null.");
  1039. // Loads have extra constraints we have to verify before we can hoist them.
  1040. if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
  1041. if (!LI->isUnordered())
  1042. return false; // Don't sink/hoist volatile or ordered atomic loads!
  1043. // Loads from constant memory are always safe to move, even if they end up
  1044. // in the same alias set as something that ends up being modified.
  1045. if (AA->pointsToConstantMemory(LI->getOperand(0)))
  1046. return true;
  1047. if (LI->hasMetadata(LLVMContext::MD_invariant_load))
  1048. return true;
  1049. if (LI->isAtomic() && !TargetExecutesOncePerLoop)
  1050. return false; // Don't risk duplicating unordered loads
  1051. // This checks for an invariant.start dominating the load.
  1052. if (isLoadInvariantInLoop(LI, DT, CurLoop))
  1053. return true;
  1054. bool Invalidated;
  1055. if (CurAST)
  1056. Invalidated = pointerInvalidatedByLoop(MemoryLocation::get(LI), CurAST,
  1057. CurLoop, AA);
  1058. else
  1059. Invalidated = pointerInvalidatedByLoopWithMSSA(
  1060. MSSA, cast<MemoryUse>(MSSA->getMemoryAccess(LI)), CurLoop, I, *Flags);
  1061. // Check loop-invariant address because this may also be a sinkable load
  1062. // whose address is not necessarily loop-invariant.
  1063. if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand()))
  1064. ORE->emit([&]() {
  1065. return OptimizationRemarkMissed(
  1066. DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", LI)
  1067. << "failed to move load with loop-invariant address "
  1068. "because the loop may invalidate its value";
  1069. });
  1070. return !Invalidated;
  1071. } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
  1072. // Don't sink or hoist dbg info; it's legal, but not useful.
  1073. if (isa<DbgInfoIntrinsic>(I))
  1074. return false;
  1075. // Don't sink calls which can throw.
  1076. if (CI->mayThrow())
  1077. return false;
  1078. // Convergent attribute has been used on operations that involve
  1079. // inter-thread communication which results are implicitly affected by the
  1080. // enclosing control flows. It is not safe to hoist or sink such operations
  1081. // across control flow.
  1082. if (CI->isConvergent())
  1083. return false;
  1084. using namespace PatternMatch;
  1085. if (match(CI, m_Intrinsic<Intrinsic::assume>()))
  1086. // Assumes don't actually alias anything or throw
  1087. return true;
  1088. if (match(CI, m_Intrinsic<Intrinsic::experimental_widenable_condition>()))
  1089. // Widenable conditions don't actually alias anything or throw
  1090. return true;
  1091. // Handle simple cases by querying alias analysis.
  1092. FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
  1093. if (Behavior == FMRB_DoesNotAccessMemory)
  1094. return true;
  1095. if (AAResults::onlyReadsMemory(Behavior)) {
  1096. // A readonly argmemonly function only reads from memory pointed to by
  1097. // it's arguments with arbitrary offsets. If we can prove there are no
  1098. // writes to this memory in the loop, we can hoist or sink.
  1099. if (AAResults::onlyAccessesArgPointees(Behavior)) {
  1100. // TODO: expand to writeable arguments
  1101. for (Value *Op : CI->args())
  1102. if (Op->getType()->isPointerTy()) {
  1103. bool Invalidated;
  1104. if (CurAST)
  1105. Invalidated = pointerInvalidatedByLoop(
  1106. MemoryLocation::getBeforeOrAfter(Op), CurAST, CurLoop, AA);
  1107. else
  1108. Invalidated = pointerInvalidatedByLoopWithMSSA(
  1109. MSSA, cast<MemoryUse>(MSSA->getMemoryAccess(CI)), CurLoop, I,
  1110. *Flags);
  1111. if (Invalidated)
  1112. return false;
  1113. }
  1114. return true;
  1115. }
  1116. // If this call only reads from memory and there are no writes to memory
  1117. // in the loop, we can hoist or sink the call as appropriate.
  1118. if (isReadOnly(CurAST, MSSAU, CurLoop))
  1119. return true;
  1120. }
  1121. // FIXME: This should use mod/ref information to see if we can hoist or
  1122. // sink the call.
  1123. return false;
  1124. } else if (auto *FI = dyn_cast<FenceInst>(&I)) {
  1125. // Fences alias (most) everything to provide ordering. For the moment,
  1126. // just give up if there are any other memory operations in the loop.
  1127. if (CurAST) {
  1128. auto Begin = CurAST->begin();
  1129. assert(Begin != CurAST->end() && "must contain FI");
  1130. if (std::next(Begin) != CurAST->end())
  1131. // constant memory for instance, TODO: handle better
  1132. return false;
  1133. auto *UniqueI = Begin->getUniqueInstruction();
  1134. if (!UniqueI)
  1135. // other memory op, give up
  1136. return false;
  1137. (void)FI; // suppress unused variable warning
  1138. assert(UniqueI == FI && "AS must contain FI");
  1139. return true;
  1140. } else // MSSAU
  1141. return isOnlyMemoryAccess(FI, CurLoop, MSSAU);
  1142. } else if (auto *SI = dyn_cast<StoreInst>(&I)) {
  1143. if (!SI->isUnordered())
  1144. return false; // Don't sink/hoist volatile or ordered atomic store!
  1145. // We can only hoist a store that we can prove writes a value which is not
  1146. // read or overwritten within the loop. For those cases, we fallback to
  1147. // load store promotion instead. TODO: We can extend this to cases where
  1148. // there is exactly one write to the location and that write dominates an
  1149. // arbitrary number of reads in the loop.
  1150. if (CurAST) {
  1151. auto &AS = CurAST->getAliasSetFor(MemoryLocation::get(SI));
  1152. if (AS.isRef() || !AS.isMustAlias())
  1153. // Quick exit test, handled by the full path below as well.
  1154. return false;
  1155. auto *UniqueI = AS.getUniqueInstruction();
  1156. if (!UniqueI)
  1157. // other memory op, give up
  1158. return false;
  1159. assert(UniqueI == SI && "AS must contain SI");
  1160. return true;
  1161. } else { // MSSAU
  1162. if (isOnlyMemoryAccess(SI, CurLoop, MSSAU))
  1163. return true;
  1164. // If there are more accesses than the Promotion cap or no "quota" to
  1165. // check clobber, then give up as we're not walking a list that long.
  1166. if (Flags->tooManyMemoryAccesses() || Flags->tooManyClobberingCalls())
  1167. return false;
  1168. // If there are interfering Uses (i.e. their defining access is in the
  1169. // loop), or ordered loads (stored as Defs!), don't move this store.
  1170. // Could do better here, but this is conservatively correct.
  1171. // TODO: Cache set of Uses on the first walk in runOnLoop, update when
  1172. // moving accesses. Can also extend to dominating uses.
  1173. auto *SIMD = MSSA->getMemoryAccess(SI);
  1174. for (auto *BB : CurLoop->getBlocks())
  1175. if (auto *Accesses = MSSA->getBlockAccesses(BB)) {
  1176. for (const auto &MA : *Accesses)
  1177. if (const auto *MU = dyn_cast<MemoryUse>(&MA)) {
  1178. auto *MD = MU->getDefiningAccess();
  1179. if (!MSSA->isLiveOnEntryDef(MD) &&
  1180. CurLoop->contains(MD->getBlock()))
  1181. return false;
  1182. // Disable hoisting past potentially interfering loads. Optimized
  1183. // Uses may point to an access outside the loop, as getClobbering
  1184. // checks the previous iteration when walking the backedge.
  1185. // FIXME: More precise: no Uses that alias SI.
  1186. if (!Flags->getIsSink() && !MSSA->dominates(SIMD, MU))
  1187. return false;
  1188. } else if (const auto *MD = dyn_cast<MemoryDef>(&MA)) {
  1189. if (auto *LI = dyn_cast<LoadInst>(MD->getMemoryInst())) {
  1190. (void)LI; // Silence warning.
  1191. assert(!LI->isUnordered() && "Expected unordered load");
  1192. return false;
  1193. }
  1194. // Any call, while it may not be clobbering SI, it may be a use.
  1195. if (auto *CI = dyn_cast<CallInst>(MD->getMemoryInst())) {
  1196. // Check if the call may read from the memory location written
  1197. // to by SI. Check CI's attributes and arguments; the number of
  1198. // such checks performed is limited above by NoOfMemAccTooLarge.
  1199. ModRefInfo MRI = AA->getModRefInfo(CI, MemoryLocation::get(SI));
  1200. if (isModOrRefSet(MRI))
  1201. return false;
  1202. }
  1203. }
  1204. }
  1205. auto *Source = MSSA->getSkipSelfWalker()->getClobberingMemoryAccess(SI);
  1206. Flags->incrementClobberingCalls();
  1207. // If there are no clobbering Defs in the loop, store is safe to hoist.
  1208. return MSSA->isLiveOnEntryDef(Source) ||
  1209. !CurLoop->contains(Source->getBlock());
  1210. }
  1211. }
  1212. assert(!I.mayReadOrWriteMemory() && "unhandled aliasing");
  1213. // We've established mechanical ability and aliasing, it's up to the caller
  1214. // to check fault safety
  1215. return true;
  1216. }
  1217. /// Returns true if a PHINode is a trivially replaceable with an
  1218. /// Instruction.
  1219. /// This is true when all incoming values are that instruction.
  1220. /// This pattern occurs most often with LCSSA PHI nodes.
  1221. ///
  1222. static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I) {
  1223. for (const Value *IncValue : PN.incoming_values())
  1224. if (IncValue != &I)
  1225. return false;
  1226. return true;
  1227. }
  1228. /// Return true if the instruction is free in the loop.
  1229. static bool isFreeInLoop(const Instruction &I, const Loop *CurLoop,
  1230. const TargetTransformInfo *TTI) {
  1231. if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
  1232. if (TTI->getUserCost(GEP, TargetTransformInfo::TCK_SizeAndLatency) !=
  1233. TargetTransformInfo::TCC_Free)
  1234. return false;
  1235. // For a GEP, we cannot simply use getUserCost because currently it
  1236. // optimistically assumes that a GEP will fold into addressing mode
  1237. // regardless of its users.
  1238. const BasicBlock *BB = GEP->getParent();
  1239. for (const User *U : GEP->users()) {
  1240. const Instruction *UI = cast<Instruction>(U);
  1241. if (CurLoop->contains(UI) &&
  1242. (BB != UI->getParent() ||
  1243. (!isa<StoreInst>(UI) && !isa<LoadInst>(UI))))
  1244. return false;
  1245. }
  1246. return true;
  1247. } else
  1248. return TTI->getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency) ==
  1249. TargetTransformInfo::TCC_Free;
  1250. }
  1251. /// Return true if the only users of this instruction are outside of
  1252. /// the loop. If this is true, we can sink the instruction to the exit
  1253. /// blocks of the loop.
  1254. ///
  1255. /// We also return true if the instruction could be folded away in lowering.
  1256. /// (e.g., a GEP can be folded into a load as an addressing mode in the loop).
  1257. static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
  1258. const LoopSafetyInfo *SafetyInfo,
  1259. TargetTransformInfo *TTI, bool &FreeInLoop,
  1260. bool LoopNestMode) {
  1261. const auto &BlockColors = SafetyInfo->getBlockColors();
  1262. bool IsFree = isFreeInLoop(I, CurLoop, TTI);
  1263. for (const User *U : I.users()) {
  1264. const Instruction *UI = cast<Instruction>(U);
  1265. if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
  1266. const BasicBlock *BB = PN->getParent();
  1267. // We cannot sink uses in catchswitches.
  1268. if (isa<CatchSwitchInst>(BB->getTerminator()))
  1269. return false;
  1270. // We need to sink a callsite to a unique funclet. Avoid sinking if the
  1271. // phi use is too muddled.
  1272. if (isa<CallInst>(I))
  1273. if (!BlockColors.empty() &&
  1274. BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
  1275. return false;
  1276. if (LoopNestMode) {
  1277. while (isa<PHINode>(UI) && UI->hasOneUser() &&
  1278. UI->getNumOperands() == 1) {
  1279. if (!CurLoop->contains(UI))
  1280. break;
  1281. UI = cast<Instruction>(UI->user_back());
  1282. }
  1283. }
  1284. }
  1285. if (CurLoop->contains(UI)) {
  1286. if (IsFree) {
  1287. FreeInLoop = true;
  1288. continue;
  1289. }
  1290. return false;
  1291. }
  1292. }
  1293. return true;
  1294. }
  1295. static Instruction *cloneInstructionInExitBlock(
  1296. Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI,
  1297. const LoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU) {
  1298. Instruction *New;
  1299. if (auto *CI = dyn_cast<CallInst>(&I)) {
  1300. const auto &BlockColors = SafetyInfo->getBlockColors();
  1301. // Sinking call-sites need to be handled differently from other
  1302. // instructions. The cloned call-site needs a funclet bundle operand
  1303. // appropriate for its location in the CFG.
  1304. SmallVector<OperandBundleDef, 1> OpBundles;
  1305. for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
  1306. BundleIdx != BundleEnd; ++BundleIdx) {
  1307. OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
  1308. if (Bundle.getTagID() == LLVMContext::OB_funclet)
  1309. continue;
  1310. OpBundles.emplace_back(Bundle);
  1311. }
  1312. if (!BlockColors.empty()) {
  1313. const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
  1314. assert(CV.size() == 1 && "non-unique color for exit block!");
  1315. BasicBlock *BBColor = CV.front();
  1316. Instruction *EHPad = BBColor->getFirstNonPHI();
  1317. if (EHPad->isEHPad())
  1318. OpBundles.emplace_back("funclet", EHPad);
  1319. }
  1320. New = CallInst::Create(CI, OpBundles);
  1321. } else {
  1322. New = I.clone();
  1323. }
  1324. ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
  1325. if (!I.getName().empty())
  1326. New->setName(I.getName() + ".le");
  1327. if (MSSAU && MSSAU->getMemorySSA()->getMemoryAccess(&I)) {
  1328. // Create a new MemoryAccess and let MemorySSA set its defining access.
  1329. MemoryAccess *NewMemAcc = MSSAU->createMemoryAccessInBB(
  1330. New, nullptr, New->getParent(), MemorySSA::Beginning);
  1331. if (NewMemAcc) {
  1332. if (auto *MemDef = dyn_cast<MemoryDef>(NewMemAcc))
  1333. MSSAU->insertDef(MemDef, /*RenameUses=*/true);
  1334. else {
  1335. auto *MemUse = cast<MemoryUse>(NewMemAcc);
  1336. MSSAU->insertUse(MemUse, /*RenameUses=*/true);
  1337. }
  1338. }
  1339. }
  1340. // Build LCSSA PHI nodes for any in-loop operands (if legal). Note that
  1341. // this is particularly cheap because we can rip off the PHI node that we're
  1342. // replacing for the number and blocks of the predecessors.
  1343. // OPT: If this shows up in a profile, we can instead finish sinking all
  1344. // invariant instructions, and then walk their operands to re-establish
  1345. // LCSSA. That will eliminate creating PHI nodes just to nuke them when
  1346. // sinking bottom-up.
  1347. for (Use &Op : New->operands())
  1348. if (LI->wouldBeOutOfLoopUseRequiringLCSSA(Op.get(), PN.getParent())) {
  1349. auto *OInst = cast<Instruction>(Op.get());
  1350. PHINode *OpPN =
  1351. PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
  1352. OInst->getName() + ".lcssa", &ExitBlock.front());
  1353. for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
  1354. OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
  1355. Op = OpPN;
  1356. }
  1357. return New;
  1358. }
  1359. static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo,
  1360. MemorySSAUpdater *MSSAU) {
  1361. if (MSSAU)
  1362. MSSAU->removeMemoryAccess(&I);
  1363. SafetyInfo.removeInstruction(&I);
  1364. I.eraseFromParent();
  1365. }
  1366. static void moveInstructionBefore(Instruction &I, Instruction &Dest,
  1367. ICFLoopSafetyInfo &SafetyInfo,
  1368. MemorySSAUpdater *MSSAU,
  1369. ScalarEvolution *SE) {
  1370. SafetyInfo.removeInstruction(&I);
  1371. SafetyInfo.insertInstructionTo(&I, Dest.getParent());
  1372. I.moveBefore(&Dest);
  1373. if (MSSAU)
  1374. if (MemoryUseOrDef *OldMemAcc = cast_or_null<MemoryUseOrDef>(
  1375. MSSAU->getMemorySSA()->getMemoryAccess(&I)))
  1376. MSSAU->moveToPlace(OldMemAcc, Dest.getParent(),
  1377. MemorySSA::BeforeTerminator);
  1378. if (SE)
  1379. SE->forgetValue(&I);
  1380. }
  1381. static Instruction *sinkThroughTriviallyReplaceablePHI(
  1382. PHINode *TPN, Instruction *I, LoopInfo *LI,
  1383. SmallDenseMap<BasicBlock *, Instruction *, 32> &SunkCopies,
  1384. const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop,
  1385. MemorySSAUpdater *MSSAU) {
  1386. assert(isTriviallyReplaceablePHI(*TPN, *I) &&
  1387. "Expect only trivially replaceable PHI");
  1388. BasicBlock *ExitBlock = TPN->getParent();
  1389. Instruction *New;
  1390. auto It = SunkCopies.find(ExitBlock);
  1391. if (It != SunkCopies.end())
  1392. New = It->second;
  1393. else
  1394. New = SunkCopies[ExitBlock] = cloneInstructionInExitBlock(
  1395. *I, *ExitBlock, *TPN, LI, SafetyInfo, MSSAU);
  1396. return New;
  1397. }
  1398. static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo) {
  1399. BasicBlock *BB = PN->getParent();
  1400. if (!BB->canSplitPredecessors())
  1401. return false;
  1402. // It's not impossible to split EHPad blocks, but if BlockColors already exist
  1403. // it require updating BlockColors for all offspring blocks accordingly. By
  1404. // skipping such corner case, we can make updating BlockColors after splitting
  1405. // predecessor fairly simple.
  1406. if (!SafetyInfo->getBlockColors().empty() && BB->getFirstNonPHI()->isEHPad())
  1407. return false;
  1408. for (BasicBlock *BBPred : predecessors(BB)) {
  1409. if (isa<IndirectBrInst>(BBPred->getTerminator()) ||
  1410. isa<CallBrInst>(BBPred->getTerminator()))
  1411. return false;
  1412. }
  1413. return true;
  1414. }
  1415. static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT,
  1416. LoopInfo *LI, const Loop *CurLoop,
  1417. LoopSafetyInfo *SafetyInfo,
  1418. MemorySSAUpdater *MSSAU) {
  1419. #ifndef NDEBUG
  1420. SmallVector<BasicBlock *, 32> ExitBlocks;
  1421. CurLoop->getUniqueExitBlocks(ExitBlocks);
  1422. SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
  1423. ExitBlocks.end());
  1424. #endif
  1425. BasicBlock *ExitBB = PN->getParent();
  1426. assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block.");
  1427. // Split predecessors of the loop exit to make instructions in the loop are
  1428. // exposed to exit blocks through trivially replaceable PHIs while keeping the
  1429. // loop in the canonical form where each predecessor of each exit block should
  1430. // be contained within the loop. For example, this will convert the loop below
  1431. // from
  1432. //
  1433. // LB1:
  1434. // %v1 =
  1435. // br %LE, %LB2
  1436. // LB2:
  1437. // %v2 =
  1438. // br %LE, %LB1
  1439. // LE:
  1440. // %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replaceable
  1441. //
  1442. // to
  1443. //
  1444. // LB1:
  1445. // %v1 =
  1446. // br %LE.split, %LB2
  1447. // LB2:
  1448. // %v2 =
  1449. // br %LE.split2, %LB1
  1450. // LE.split:
  1451. // %p1 = phi [%v1, %LB1] <-- trivially replaceable
  1452. // br %LE
  1453. // LE.split2:
  1454. // %p2 = phi [%v2, %LB2] <-- trivially replaceable
  1455. // br %LE
  1456. // LE:
  1457. // %p = phi [%p1, %LE.split], [%p2, %LE.split2]
  1458. //
  1459. const auto &BlockColors = SafetyInfo->getBlockColors();
  1460. SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB));
  1461. while (!PredBBs.empty()) {
  1462. BasicBlock *PredBB = *PredBBs.begin();
  1463. assert(CurLoop->contains(PredBB) &&
  1464. "Expect all predecessors are in the loop");
  1465. if (PN->getBasicBlockIndex(PredBB) >= 0) {
  1466. BasicBlock *NewPred = SplitBlockPredecessors(
  1467. ExitBB, PredBB, ".split.loop.exit", DT, LI, MSSAU, true);
  1468. // Since we do not allow splitting EH-block with BlockColors in
  1469. // canSplitPredecessors(), we can simply assign predecessor's color to
  1470. // the new block.
  1471. if (!BlockColors.empty())
  1472. // Grab a reference to the ColorVector to be inserted before getting the
  1473. // reference to the vector we are copying because inserting the new
  1474. // element in BlockColors might cause the map to be reallocated.
  1475. SafetyInfo->copyColors(NewPred, PredBB);
  1476. }
  1477. PredBBs.remove(PredBB);
  1478. }
  1479. }
  1480. /// When an instruction is found to only be used outside of the loop, this
  1481. /// function moves it to the exit blocks and patches up SSA form as needed.
  1482. /// This method is guaranteed to remove the original instruction from its
  1483. /// position, and may either delete it or move it to outside of the loop.
  1484. ///
  1485. static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
  1486. BlockFrequencyInfo *BFI, const Loop *CurLoop,
  1487. ICFLoopSafetyInfo *SafetyInfo, MemorySSAUpdater *MSSAU,
  1488. OptimizationRemarkEmitter *ORE) {
  1489. bool Changed = false;
  1490. LLVM_DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
  1491. // Iterate over users to be ready for actual sinking. Replace users via
  1492. // unreachable blocks with undef and make all user PHIs trivially replaceable.
  1493. SmallPtrSet<Instruction *, 8> VisitedUsers;
  1494. for (Value::user_iterator UI = I.user_begin(), UE = I.user_end(); UI != UE;) {
  1495. auto *User = cast<Instruction>(*UI);
  1496. Use &U = UI.getUse();
  1497. ++UI;
  1498. if (VisitedUsers.count(User) || CurLoop->contains(User))
  1499. continue;
  1500. if (!DT->isReachableFromEntry(User->getParent())) {
  1501. U = UndefValue::get(I.getType());
  1502. Changed = true;
  1503. continue;
  1504. }
  1505. // The user must be a PHI node.
  1506. PHINode *PN = cast<PHINode>(User);
  1507. // Surprisingly, instructions can be used outside of loops without any
  1508. // exits. This can only happen in PHI nodes if the incoming block is
  1509. // unreachable.
  1510. BasicBlock *BB = PN->getIncomingBlock(U);
  1511. if (!DT->isReachableFromEntry(BB)) {
  1512. U = UndefValue::get(I.getType());
  1513. Changed = true;
  1514. continue;
  1515. }
  1516. VisitedUsers.insert(PN);
  1517. if (isTriviallyReplaceablePHI(*PN, I))
  1518. continue;
  1519. if (!canSplitPredecessors(PN, SafetyInfo))
  1520. return Changed;
  1521. // Split predecessors of the PHI so that we can make users trivially
  1522. // replaceable.
  1523. splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop, SafetyInfo, MSSAU);
  1524. // Should rebuild the iterators, as they may be invalidated by
  1525. // splitPredecessorsOfLoopExit().
  1526. UI = I.user_begin();
  1527. UE = I.user_end();
  1528. }
  1529. if (VisitedUsers.empty())
  1530. return Changed;
  1531. ORE->emit([&]() {
  1532. return OptimizationRemark(DEBUG_TYPE, "InstSunk", &I)
  1533. << "sinking " << ore::NV("Inst", &I);
  1534. });
  1535. if (isa<LoadInst>(I))
  1536. ++NumMovedLoads;
  1537. else if (isa<CallInst>(I))
  1538. ++NumMovedCalls;
  1539. ++NumSunk;
  1540. #ifndef NDEBUG
  1541. SmallVector<BasicBlock *, 32> ExitBlocks;
  1542. CurLoop->getUniqueExitBlocks(ExitBlocks);
  1543. SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
  1544. ExitBlocks.end());
  1545. #endif
  1546. // Clones of this instruction. Don't create more than one per exit block!
  1547. SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
  1548. // If this instruction is only used outside of the loop, then all users are
  1549. // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
  1550. // the instruction.
  1551. // First check if I is worth sinking for all uses. Sink only when it is worth
  1552. // across all uses.
  1553. SmallSetVector<User*, 8> Users(I.user_begin(), I.user_end());
  1554. for (auto *UI : Users) {
  1555. auto *User = cast<Instruction>(UI);
  1556. if (CurLoop->contains(User))
  1557. continue;
  1558. PHINode *PN = cast<PHINode>(User);
  1559. assert(ExitBlockSet.count(PN->getParent()) &&
  1560. "The LCSSA PHI is not in an exit block!");
  1561. // The PHI must be trivially replaceable.
  1562. Instruction *New = sinkThroughTriviallyReplaceablePHI(
  1563. PN, &I, LI, SunkCopies, SafetyInfo, CurLoop, MSSAU);
  1564. PN->replaceAllUsesWith(New);
  1565. eraseInstruction(*PN, *SafetyInfo, nullptr);
  1566. Changed = true;
  1567. }
  1568. return Changed;
  1569. }
  1570. /// When an instruction is found to only use loop invariant operands that
  1571. /// is safe to hoist, this instruction is called to do the dirty work.
  1572. ///
  1573. static void hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
  1574. BasicBlock *Dest, ICFLoopSafetyInfo *SafetyInfo,
  1575. MemorySSAUpdater *MSSAU, ScalarEvolution *SE,
  1576. OptimizationRemarkEmitter *ORE) {
  1577. LLVM_DEBUG(dbgs() << "LICM hoisting to " << Dest->getNameOrAsOperand() << ": "
  1578. << I << "\n");
  1579. ORE->emit([&]() {
  1580. return OptimizationRemark(DEBUG_TYPE, "Hoisted", &I) << "hoisting "
  1581. << ore::NV("Inst", &I);
  1582. });
  1583. // Metadata can be dependent on conditions we are hoisting above.
  1584. // Conservatively strip all metadata on the instruction unless we were
  1585. // guaranteed to execute I if we entered the loop, in which case the metadata
  1586. // is valid in the loop preheader.
  1587. // Similarly, If I is a call and it is not guaranteed to execute in the loop,
  1588. // then moving to the preheader means we should strip attributes on the call
  1589. // that can cause UB since we may be hoisting above conditions that allowed
  1590. // inferring those attributes. They may not be valid at the preheader.
  1591. if ((I.hasMetadataOtherThanDebugLoc() || isa<CallInst>(I)) &&
  1592. // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
  1593. // time in isGuaranteedToExecute if we don't actually have anything to
  1594. // drop. It is a compile time optimization, not required for correctness.
  1595. !SafetyInfo->isGuaranteedToExecute(I, DT, CurLoop))
  1596. I.dropUndefImplyingAttrsAndUnknownMetadata();
  1597. if (isa<PHINode>(I))
  1598. // Move the new node to the end of the phi list in the destination block.
  1599. moveInstructionBefore(I, *Dest->getFirstNonPHI(), *SafetyInfo, MSSAU, SE);
  1600. else
  1601. // Move the new node to the destination block, before its terminator.
  1602. moveInstructionBefore(I, *Dest->getTerminator(), *SafetyInfo, MSSAU, SE);
  1603. I.updateLocationAfterHoist();
  1604. if (isa<LoadInst>(I))
  1605. ++NumMovedLoads;
  1606. else if (isa<CallInst>(I))
  1607. ++NumMovedCalls;
  1608. ++NumHoisted;
  1609. }
  1610. /// Only sink or hoist an instruction if it is not a trapping instruction,
  1611. /// or if the instruction is known not to trap when moved to the preheader.
  1612. /// or if it is a trapping instruction and is guaranteed to execute.
  1613. static bool isSafeToExecuteUnconditionally(
  1614. Instruction &Inst, const DominatorTree *DT, const TargetLibraryInfo *TLI,
  1615. const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo,
  1616. OptimizationRemarkEmitter *ORE, const Instruction *CtxI,
  1617. bool AllowSpeculation) {
  1618. if (AllowSpeculation && isSafeToSpeculativelyExecute(&Inst, CtxI, DT, TLI))
  1619. return true;
  1620. bool GuaranteedToExecute =
  1621. SafetyInfo->isGuaranteedToExecute(Inst, DT, CurLoop);
  1622. if (!GuaranteedToExecute) {
  1623. auto *LI = dyn_cast<LoadInst>(&Inst);
  1624. if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand()))
  1625. ORE->emit([&]() {
  1626. return OptimizationRemarkMissed(
  1627. DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI)
  1628. << "failed to hoist load with loop-invariant address "
  1629. "because load is conditionally executed";
  1630. });
  1631. }
  1632. return GuaranteedToExecute;
  1633. }
  1634. namespace {
  1635. class LoopPromoter : public LoadAndStorePromoter {
  1636. Value *SomePtr; // Designated pointer to store to.
  1637. const SmallSetVector<Value *, 8> &PointerMustAliases;
  1638. SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
  1639. SmallVectorImpl<Instruction *> &LoopInsertPts;
  1640. SmallVectorImpl<MemoryAccess *> &MSSAInsertPts;
  1641. PredIteratorCache &PredCache;
  1642. MemorySSAUpdater *MSSAU;
  1643. LoopInfo &LI;
  1644. DebugLoc DL;
  1645. Align Alignment;
  1646. bool UnorderedAtomic;
  1647. AAMDNodes AATags;
  1648. ICFLoopSafetyInfo &SafetyInfo;
  1649. bool CanInsertStoresInExitBlocks;
  1650. // We're about to add a use of V in a loop exit block. Insert an LCSSA phi
  1651. // (if legal) if doing so would add an out-of-loop use to an instruction
  1652. // defined in-loop.
  1653. Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
  1654. if (!LI.wouldBeOutOfLoopUseRequiringLCSSA(V, BB))
  1655. return V;
  1656. Instruction *I = cast<Instruction>(V);
  1657. // We need to create an LCSSA PHI node for the incoming value and
  1658. // store that.
  1659. PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
  1660. I->getName() + ".lcssa", &BB->front());
  1661. for (BasicBlock *Pred : PredCache.get(BB))
  1662. PN->addIncoming(I, Pred);
  1663. return PN;
  1664. }
  1665. public:
  1666. LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
  1667. const SmallSetVector<Value *, 8> &PMA,
  1668. SmallVectorImpl<BasicBlock *> &LEB,
  1669. SmallVectorImpl<Instruction *> &LIP,
  1670. SmallVectorImpl<MemoryAccess *> &MSSAIP, PredIteratorCache &PIC,
  1671. MemorySSAUpdater *MSSAU, LoopInfo &li, DebugLoc dl,
  1672. Align Alignment, bool UnorderedAtomic, const AAMDNodes &AATags,
  1673. ICFLoopSafetyInfo &SafetyInfo, bool CanInsertStoresInExitBlocks)
  1674. : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
  1675. LoopExitBlocks(LEB), LoopInsertPts(LIP), MSSAInsertPts(MSSAIP),
  1676. PredCache(PIC), MSSAU(MSSAU), LI(li), DL(std::move(dl)),
  1677. Alignment(Alignment), UnorderedAtomic(UnorderedAtomic), AATags(AATags),
  1678. SafetyInfo(SafetyInfo),
  1679. CanInsertStoresInExitBlocks(CanInsertStoresInExitBlocks) {}
  1680. bool isInstInList(Instruction *I,
  1681. const SmallVectorImpl<Instruction *> &) const override {
  1682. Value *Ptr;
  1683. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  1684. Ptr = LI->getOperand(0);
  1685. else
  1686. Ptr = cast<StoreInst>(I)->getPointerOperand();
  1687. return PointerMustAliases.count(Ptr);
  1688. }
  1689. void insertStoresInLoopExitBlocks() {
  1690. // Insert stores after in the loop exit blocks. Each exit block gets a
  1691. // store of the live-out values that feed them. Since we've already told
  1692. // the SSA updater about the defs in the loop and the preheader
  1693. // definition, it is all set and we can start using it.
  1694. for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
  1695. BasicBlock *ExitBlock = LoopExitBlocks[i];
  1696. Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
  1697. LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
  1698. Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
  1699. Instruction *InsertPos = LoopInsertPts[i];
  1700. StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
  1701. if (UnorderedAtomic)
  1702. NewSI->setOrdering(AtomicOrdering::Unordered);
  1703. NewSI->setAlignment(Alignment);
  1704. NewSI->setDebugLoc(DL);
  1705. if (AATags)
  1706. NewSI->setAAMetadata(AATags);
  1707. MemoryAccess *MSSAInsertPoint = MSSAInsertPts[i];
  1708. MemoryAccess *NewMemAcc;
  1709. if (!MSSAInsertPoint) {
  1710. NewMemAcc = MSSAU->createMemoryAccessInBB(
  1711. NewSI, nullptr, NewSI->getParent(), MemorySSA::Beginning);
  1712. } else {
  1713. NewMemAcc =
  1714. MSSAU->createMemoryAccessAfter(NewSI, nullptr, MSSAInsertPoint);
  1715. }
  1716. MSSAInsertPts[i] = NewMemAcc;
  1717. MSSAU->insertDef(cast<MemoryDef>(NewMemAcc), true);
  1718. // FIXME: true for safety, false may still be correct.
  1719. }
  1720. }
  1721. void doExtraRewritesBeforeFinalDeletion() override {
  1722. if (CanInsertStoresInExitBlocks)
  1723. insertStoresInLoopExitBlocks();
  1724. }
  1725. void instructionDeleted(Instruction *I) const override {
  1726. SafetyInfo.removeInstruction(I);
  1727. MSSAU->removeMemoryAccess(I);
  1728. }
  1729. bool shouldDelete(Instruction *I) const override {
  1730. if (isa<StoreInst>(I))
  1731. return CanInsertStoresInExitBlocks;
  1732. return true;
  1733. }
  1734. };
  1735. bool isNotCapturedBeforeOrInLoop(const Value *V, const Loop *L,
  1736. DominatorTree *DT) {
  1737. // We can perform the captured-before check against any instruction in the
  1738. // loop header, as the loop header is reachable from any instruction inside
  1739. // the loop.
  1740. // TODO: ReturnCaptures=true shouldn't be necessary here.
  1741. return !PointerMayBeCapturedBefore(V, /* ReturnCaptures */ true,
  1742. /* StoreCaptures */ true,
  1743. L->getHeader()->getTerminator(), DT);
  1744. }
  1745. /// Return true if we can prove that a caller cannot inspect the object if an
  1746. /// unwind occurs inside the loop.
  1747. bool isNotVisibleOnUnwindInLoop(const Value *Object, const Loop *L,
  1748. DominatorTree *DT) {
  1749. bool RequiresNoCaptureBeforeUnwind;
  1750. if (!isNotVisibleOnUnwind(Object, RequiresNoCaptureBeforeUnwind))
  1751. return false;
  1752. return !RequiresNoCaptureBeforeUnwind ||
  1753. isNotCapturedBeforeOrInLoop(Object, L, DT);
  1754. }
  1755. } // namespace
  1756. /// Try to promote memory values to scalars by sinking stores out of the
  1757. /// loop and moving loads to before the loop. We do this by looping over
  1758. /// the stores in the loop, looking for stores to Must pointers which are
  1759. /// loop invariant.
  1760. ///
  1761. bool llvm::promoteLoopAccessesToScalars(
  1762. const SmallSetVector<Value *, 8> &PointerMustAliases,
  1763. SmallVectorImpl<BasicBlock *> &ExitBlocks,
  1764. SmallVectorImpl<Instruction *> &InsertPts,
  1765. SmallVectorImpl<MemoryAccess *> &MSSAInsertPts, PredIteratorCache &PIC,
  1766. LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
  1767. Loop *CurLoop, MemorySSAUpdater *MSSAU, ICFLoopSafetyInfo *SafetyInfo,
  1768. OptimizationRemarkEmitter *ORE, bool AllowSpeculation) {
  1769. // Verify inputs.
  1770. assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
  1771. SafetyInfo != nullptr &&
  1772. "Unexpected Input to promoteLoopAccessesToScalars");
  1773. Value *SomePtr = *PointerMustAliases.begin();
  1774. BasicBlock *Preheader = CurLoop->getLoopPreheader();
  1775. // It is not safe to promote a load/store from the loop if the load/store is
  1776. // conditional. For example, turning:
  1777. //
  1778. // for () { if (c) *P += 1; }
  1779. //
  1780. // into:
  1781. //
  1782. // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
  1783. //
  1784. // is not safe, because *P may only be valid to access if 'c' is true.
  1785. //
  1786. // The safety property divides into two parts:
  1787. // p1) The memory may not be dereferenceable on entry to the loop. In this
  1788. // case, we can't insert the required load in the preheader.
  1789. // p2) The memory model does not allow us to insert a store along any dynamic
  1790. // path which did not originally have one.
  1791. //
  1792. // If at least one store is guaranteed to execute, both properties are
  1793. // satisfied, and promotion is legal.
  1794. //
  1795. // This, however, is not a necessary condition. Even if no store/load is
  1796. // guaranteed to execute, we can still establish these properties.
  1797. // We can establish (p1) by proving that hoisting the load into the preheader
  1798. // is safe (i.e. proving dereferenceability on all paths through the loop). We
  1799. // can use any access within the alias set to prove dereferenceability,
  1800. // since they're all must alias.
  1801. //
  1802. // There are two ways establish (p2):
  1803. // a) Prove the location is thread-local. In this case the memory model
  1804. // requirement does not apply, and stores are safe to insert.
  1805. // b) Prove a store dominates every exit block. In this case, if an exit
  1806. // blocks is reached, the original dynamic path would have taken us through
  1807. // the store, so inserting a store into the exit block is safe. Note that this
  1808. // is different from the store being guaranteed to execute. For instance,
  1809. // if an exception is thrown on the first iteration of the loop, the original
  1810. // store is never executed, but the exit blocks are not executed either.
  1811. bool DereferenceableInPH = false;
  1812. bool SafeToInsertStore = false;
  1813. bool FoundLoadToPromote = false;
  1814. SmallVector<Instruction *, 64> LoopUses;
  1815. // We start with an alignment of one and try to find instructions that allow
  1816. // us to prove better alignment.
  1817. Align Alignment;
  1818. // Keep track of which types of access we see
  1819. bool SawUnorderedAtomic = false;
  1820. bool SawNotAtomic = false;
  1821. AAMDNodes AATags;
  1822. const DataLayout &MDL = Preheader->getModule()->getDataLayout();
  1823. bool IsKnownThreadLocalObject = false;
  1824. if (SafetyInfo->anyBlockMayThrow()) {
  1825. // If a loop can throw, we have to insert a store along each unwind edge.
  1826. // That said, we can't actually make the unwind edge explicit. Therefore,
  1827. // we have to prove that the store is dead along the unwind edge. We do
  1828. // this by proving that the caller can't have a reference to the object
  1829. // after return and thus can't possibly load from the object.
  1830. Value *Object = getUnderlyingObject(SomePtr);
  1831. if (!isNotVisibleOnUnwindInLoop(Object, CurLoop, DT))
  1832. return false;
  1833. // Subtlety: Alloca's aren't visible to callers, but *are* potentially
  1834. // visible to other threads if captured and used during their lifetimes.
  1835. IsKnownThreadLocalObject = !isa<AllocaInst>(Object);
  1836. }
  1837. // Check that all accesses to pointers in the aliass set use the same type.
  1838. // We cannot (yet) promote a memory location that is loaded and stored in
  1839. // different sizes. While we are at it, collect alignment and AA info.
  1840. Type *AccessTy = nullptr;
  1841. for (Value *ASIV : PointerMustAliases) {
  1842. for (User *U : ASIV->users()) {
  1843. // Ignore instructions that are outside the loop.
  1844. Instruction *UI = dyn_cast<Instruction>(U);
  1845. if (!UI || !CurLoop->contains(UI))
  1846. continue;
  1847. // If there is an non-load/store instruction in the loop, we can't promote
  1848. // it.
  1849. if (LoadInst *Load = dyn_cast<LoadInst>(UI)) {
  1850. if (!Load->isUnordered())
  1851. return false;
  1852. SawUnorderedAtomic |= Load->isAtomic();
  1853. SawNotAtomic |= !Load->isAtomic();
  1854. FoundLoadToPromote = true;
  1855. Align InstAlignment = Load->getAlign();
  1856. // Note that proving a load safe to speculate requires proving
  1857. // sufficient alignment at the target location. Proving it guaranteed
  1858. // to execute does as well. Thus we can increase our guaranteed
  1859. // alignment as well.
  1860. if (!DereferenceableInPH || (InstAlignment > Alignment))
  1861. if (isSafeToExecuteUnconditionally(
  1862. *Load, DT, TLI, CurLoop, SafetyInfo, ORE,
  1863. Preheader->getTerminator(), AllowSpeculation)) {
  1864. DereferenceableInPH = true;
  1865. Alignment = std::max(Alignment, InstAlignment);
  1866. }
  1867. } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
  1868. // Stores *of* the pointer are not interesting, only stores *to* the
  1869. // pointer.
  1870. if (UI->getOperand(1) != ASIV)
  1871. continue;
  1872. if (!Store->isUnordered())
  1873. return false;
  1874. SawUnorderedAtomic |= Store->isAtomic();
  1875. SawNotAtomic |= !Store->isAtomic();
  1876. // If the store is guaranteed to execute, both properties are satisfied.
  1877. // We may want to check if a store is guaranteed to execute even if we
  1878. // already know that promotion is safe, since it may have higher
  1879. // alignment than any other guaranteed stores, in which case we can
  1880. // raise the alignment on the promoted store.
  1881. Align InstAlignment = Store->getAlign();
  1882. if (!DereferenceableInPH || !SafeToInsertStore ||
  1883. (InstAlignment > Alignment)) {
  1884. if (SafetyInfo->isGuaranteedToExecute(*UI, DT, CurLoop)) {
  1885. DereferenceableInPH = true;
  1886. SafeToInsertStore = true;
  1887. Alignment = std::max(Alignment, InstAlignment);
  1888. }
  1889. }
  1890. // If a store dominates all exit blocks, it is safe to sink.
  1891. // As explained above, if an exit block was executed, a dominating
  1892. // store must have been executed at least once, so we are not
  1893. // introducing stores on paths that did not have them.
  1894. // Note that this only looks at explicit exit blocks. If we ever
  1895. // start sinking stores into unwind edges (see above), this will break.
  1896. if (!SafeToInsertStore)
  1897. SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) {
  1898. return DT->dominates(Store->getParent(), Exit);
  1899. });
  1900. // If the store is not guaranteed to execute, we may still get
  1901. // deref info through it.
  1902. if (!DereferenceableInPH) {
  1903. DereferenceableInPH = isDereferenceableAndAlignedPointer(
  1904. Store->getPointerOperand(), Store->getValueOperand()->getType(),
  1905. Store->getAlign(), MDL, Preheader->getTerminator(), DT, TLI);
  1906. }
  1907. } else
  1908. return false; // Not a load or store.
  1909. if (!AccessTy)
  1910. AccessTy = getLoadStoreType(UI);
  1911. else if (AccessTy != getLoadStoreType(UI))
  1912. return false;
  1913. // Merge the AA tags.
  1914. if (LoopUses.empty()) {
  1915. // On the first load/store, just take its AA tags.
  1916. AATags = UI->getAAMetadata();
  1917. } else if (AATags) {
  1918. AATags = AATags.merge(UI->getAAMetadata());
  1919. }
  1920. LoopUses.push_back(UI);
  1921. }
  1922. }
  1923. // If we found both an unordered atomic instruction and a non-atomic memory
  1924. // access, bail. We can't blindly promote non-atomic to atomic since we
  1925. // might not be able to lower the result. We can't downgrade since that
  1926. // would violate memory model. Also, align 0 is an error for atomics.
  1927. if (SawUnorderedAtomic && SawNotAtomic)
  1928. return false;
  1929. // If we're inserting an atomic load in the preheader, we must be able to
  1930. // lower it. We're only guaranteed to be able to lower naturally aligned
  1931. // atomics.
  1932. if (SawUnorderedAtomic && Alignment < MDL.getTypeStoreSize(AccessTy))
  1933. return false;
  1934. // If we couldn't prove we can hoist the load, bail.
  1935. if (!DereferenceableInPH)
  1936. return false;
  1937. // We know we can hoist the load, but don't have a guaranteed store.
  1938. // Check whether the location is thread-local. If it is, then we can insert
  1939. // stores along paths which originally didn't have them without violating the
  1940. // memory model.
  1941. if (!SafeToInsertStore) {
  1942. if (IsKnownThreadLocalObject)
  1943. SafeToInsertStore = true;
  1944. else {
  1945. Value *Object = getUnderlyingObject(SomePtr);
  1946. SafeToInsertStore =
  1947. (isNoAliasCall(Object) || isa<AllocaInst>(Object)) &&
  1948. isNotCapturedBeforeOrInLoop(Object, CurLoop, DT);
  1949. }
  1950. }
  1951. // If we've still failed to prove we can sink the store, hoist the load
  1952. // only, if possible.
  1953. if (!SafeToInsertStore && !FoundLoadToPromote)
  1954. // If we cannot hoist the load either, give up.
  1955. return false;
  1956. // Lets do the promotion!
  1957. if (SafeToInsertStore)
  1958. LLVM_DEBUG(dbgs() << "LICM: Promoting load/store of the value: " << *SomePtr
  1959. << '\n');
  1960. else
  1961. LLVM_DEBUG(dbgs() << "LICM: Promoting load of the value: " << *SomePtr
  1962. << '\n');
  1963. ORE->emit([&]() {
  1964. return OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar",
  1965. LoopUses[0])
  1966. << "Moving accesses to memory location out of the loop";
  1967. });
  1968. ++NumPromoted;
  1969. // Look at all the loop uses, and try to merge their locations.
  1970. std::vector<const DILocation *> LoopUsesLocs;
  1971. for (auto U : LoopUses)
  1972. LoopUsesLocs.push_back(U->getDebugLoc().get());
  1973. auto DL = DebugLoc(DILocation::getMergedLocations(LoopUsesLocs));
  1974. // We use the SSAUpdater interface to insert phi nodes as required.
  1975. SmallVector<PHINode *, 16> NewPHIs;
  1976. SSAUpdater SSA(&NewPHIs);
  1977. LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
  1978. InsertPts, MSSAInsertPts, PIC, MSSAU, *LI, DL,
  1979. Alignment, SawUnorderedAtomic, AATags, *SafetyInfo,
  1980. SafeToInsertStore);
  1981. // Set up the preheader to have a definition of the value. It is the live-out
  1982. // value from the preheader that uses in the loop will use.
  1983. LoadInst *PreheaderLoad = new LoadInst(
  1984. AccessTy, SomePtr, SomePtr->getName() + ".promoted",
  1985. Preheader->getTerminator());
  1986. if (SawUnorderedAtomic)
  1987. PreheaderLoad->setOrdering(AtomicOrdering::Unordered);
  1988. PreheaderLoad->setAlignment(Alignment);
  1989. PreheaderLoad->setDebugLoc(DebugLoc());
  1990. if (AATags)
  1991. PreheaderLoad->setAAMetadata(AATags);
  1992. SSA.AddAvailableValue(Preheader, PreheaderLoad);
  1993. MemoryAccess *PreheaderLoadMemoryAccess = MSSAU->createMemoryAccessInBB(
  1994. PreheaderLoad, nullptr, PreheaderLoad->getParent(), MemorySSA::End);
  1995. MemoryUse *NewMemUse = cast<MemoryUse>(PreheaderLoadMemoryAccess);
  1996. MSSAU->insertUse(NewMemUse, /*RenameUses=*/true);
  1997. if (VerifyMemorySSA)
  1998. MSSAU->getMemorySSA()->verifyMemorySSA();
  1999. // Rewrite all the loads in the loop and remember all the definitions from
  2000. // stores in the loop.
  2001. Promoter.run(LoopUses);
  2002. if (VerifyMemorySSA)
  2003. MSSAU->getMemorySSA()->verifyMemorySSA();
  2004. // If the SSAUpdater didn't use the load in the preheader, just zap it now.
  2005. if (PreheaderLoad->use_empty())
  2006. eraseInstruction(*PreheaderLoad, *SafetyInfo, MSSAU);
  2007. return true;
  2008. }
  2009. static void foreachMemoryAccess(MemorySSA *MSSA, Loop *L,
  2010. function_ref<void(Instruction *)> Fn) {
  2011. for (const BasicBlock *BB : L->blocks())
  2012. if (const auto *Accesses = MSSA->getBlockAccesses(BB))
  2013. for (const auto &Access : *Accesses)
  2014. if (const auto *MUD = dyn_cast<MemoryUseOrDef>(&Access))
  2015. Fn(MUD->getMemoryInst());
  2016. }
  2017. static SmallVector<SmallSetVector<Value *, 8>, 0>
  2018. collectPromotionCandidates(MemorySSA *MSSA, AliasAnalysis *AA, Loop *L) {
  2019. AliasSetTracker AST(*AA);
  2020. auto IsPotentiallyPromotable = [L](const Instruction *I) {
  2021. if (const auto *SI = dyn_cast<StoreInst>(I))
  2022. return L->isLoopInvariant(SI->getPointerOperand());
  2023. if (const auto *LI = dyn_cast<LoadInst>(I))
  2024. return L->isLoopInvariant(LI->getPointerOperand());
  2025. return false;
  2026. };
  2027. // Populate AST with potentially promotable accesses and remove them from
  2028. // MaybePromotable, so they will not be checked again on the next iteration.
  2029. SmallPtrSet<Value *, 16> AttemptingPromotion;
  2030. foreachMemoryAccess(MSSA, L, [&](Instruction *I) {
  2031. if (IsPotentiallyPromotable(I)) {
  2032. AttemptingPromotion.insert(I);
  2033. AST.add(I);
  2034. }
  2035. });
  2036. // We're only interested in must-alias sets that contain a mod.
  2037. SmallVector<const AliasSet *, 8> Sets;
  2038. for (AliasSet &AS : AST)
  2039. if (!AS.isForwardingAliasSet() && AS.isMod() && AS.isMustAlias())
  2040. Sets.push_back(&AS);
  2041. if (Sets.empty())
  2042. return {}; // Nothing to promote...
  2043. // Discard any sets for which there is an aliasing non-promotable access.
  2044. foreachMemoryAccess(MSSA, L, [&](Instruction *I) {
  2045. if (AttemptingPromotion.contains(I))
  2046. return;
  2047. llvm::erase_if(Sets, [&](const AliasSet *AS) {
  2048. return AS->aliasesUnknownInst(I, *AA);
  2049. });
  2050. });
  2051. SmallVector<SmallSetVector<Value *, 8>, 0> Result;
  2052. for (const AliasSet *Set : Sets) {
  2053. SmallSetVector<Value *, 8> PointerMustAliases;
  2054. for (const auto &ASI : *Set)
  2055. PointerMustAliases.insert(ASI.getValue());
  2056. Result.push_back(std::move(PointerMustAliases));
  2057. }
  2058. return Result;
  2059. }
  2060. static bool pointerInvalidatedByLoop(MemoryLocation MemLoc,
  2061. AliasSetTracker *CurAST, Loop *CurLoop,
  2062. AAResults *AA) {
  2063. return CurAST->getAliasSetFor(MemLoc).isMod();
  2064. }
  2065. bool pointerInvalidatedByLoopWithMSSA(MemorySSA *MSSA, MemoryUse *MU,
  2066. Loop *CurLoop, Instruction &I,
  2067. SinkAndHoistLICMFlags &Flags) {
  2068. // For hoisting, use the walker to determine safety
  2069. if (!Flags.getIsSink()) {
  2070. MemoryAccess *Source;
  2071. // See declaration of SetLicmMssaOptCap for usage details.
  2072. if (Flags.tooManyClobberingCalls())
  2073. Source = MU->getDefiningAccess();
  2074. else {
  2075. Source = MSSA->getSkipSelfWalker()->getClobberingMemoryAccess(MU);
  2076. Flags.incrementClobberingCalls();
  2077. }
  2078. return !MSSA->isLiveOnEntryDef(Source) &&
  2079. CurLoop->contains(Source->getBlock());
  2080. }
  2081. // For sinking, we'd need to check all Defs below this use. The getClobbering
  2082. // call will look on the backedge of the loop, but will check aliasing with
  2083. // the instructions on the previous iteration.
  2084. // For example:
  2085. // for (i ... )
  2086. // load a[i] ( Use (LoE)
  2087. // store a[i] ( 1 = Def (2), with 2 = Phi for the loop.
  2088. // i++;
  2089. // The load sees no clobbering inside the loop, as the backedge alias check
  2090. // does phi translation, and will check aliasing against store a[i-1].
  2091. // However sinking the load outside the loop, below the store is incorrect.
  2092. // For now, only sink if there are no Defs in the loop, and the existing ones
  2093. // precede the use and are in the same block.
  2094. // FIXME: Increase precision: Safe to sink if Use post dominates the Def;
  2095. // needs PostDominatorTreeAnalysis.
  2096. // FIXME: More precise: no Defs that alias this Use.
  2097. if (Flags.tooManyMemoryAccesses())
  2098. return true;
  2099. for (auto *BB : CurLoop->getBlocks())
  2100. if (pointerInvalidatedByBlockWithMSSA(*BB, *MSSA, *MU))
  2101. return true;
  2102. // When sinking, the source block may not be part of the loop so check it.
  2103. if (!CurLoop->contains(&I))
  2104. return pointerInvalidatedByBlockWithMSSA(*I.getParent(), *MSSA, *MU);
  2105. return false;
  2106. }
  2107. bool pointerInvalidatedByBlockWithMSSA(BasicBlock &BB, MemorySSA &MSSA,
  2108. MemoryUse &MU) {
  2109. if (const auto *Accesses = MSSA.getBlockDefs(&BB))
  2110. for (const auto &MA : *Accesses)
  2111. if (const auto *MD = dyn_cast<MemoryDef>(&MA))
  2112. if (MU.getBlock() != MD->getBlock() || !MSSA.locallyDominates(MD, &MU))
  2113. return true;
  2114. return false;
  2115. }
  2116. /// Little predicate that returns true if the specified basic block is in
  2117. /// a subloop of the current one, not the current one itself.
  2118. ///
  2119. static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
  2120. assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
  2121. return LI->getLoopFor(BB) != CurLoop;
  2122. }