LICM.cpp 99 KB

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