LoopPassManagerTest.cpp 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584
  1. //===- llvm/unittest/Analysis/LoopPassManagerTest.cpp - LPM tests ---------===//
  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. #include "llvm/Transforms/Scalar/LoopPassManager.h"
  9. #include "llvm/Analysis/AliasAnalysis.h"
  10. #include "llvm/Analysis/AssumptionCache.h"
  11. #include "llvm/Analysis/ScalarEvolution.h"
  12. #include "llvm/Analysis/TargetLibraryInfo.h"
  13. #include "llvm/Analysis/TargetTransformInfo.h"
  14. #include "llvm/AsmParser/Parser.h"
  15. #include "llvm/IR/Dominators.h"
  16. #include "llvm/IR/Function.h"
  17. #include "llvm/IR/LLVMContext.h"
  18. #include "llvm/IR/Module.h"
  19. #include "llvm/IR/PassManager.h"
  20. #include "llvm/Support/SourceMgr.h"
  21. #include "gmock/gmock.h"
  22. #include "gtest/gtest.h"
  23. using namespace llvm;
  24. namespace {
  25. using testing::DoDefault;
  26. using testing::Return;
  27. using testing::Expectation;
  28. using testing::Invoke;
  29. using testing::InvokeWithoutArgs;
  30. using testing::_;
  31. template <typename DerivedT, typename IRUnitT,
  32. typename AnalysisManagerT = AnalysisManager<IRUnitT>,
  33. typename... ExtraArgTs>
  34. class MockAnalysisHandleBase {
  35. public:
  36. class Analysis : public AnalysisInfoMixin<Analysis> {
  37. friend AnalysisInfoMixin<Analysis>;
  38. friend MockAnalysisHandleBase;
  39. static AnalysisKey Key;
  40. DerivedT *Handle;
  41. Analysis(DerivedT &Handle) : Handle(&Handle) {
  42. static_assert(std::is_base_of<MockAnalysisHandleBase, DerivedT>::value,
  43. "Must pass the derived type to this template!");
  44. }
  45. public:
  46. class Result {
  47. friend MockAnalysisHandleBase;
  48. DerivedT *Handle;
  49. Result(DerivedT &Handle) : Handle(&Handle) {}
  50. public:
  51. // Forward invalidation events to the mock handle.
  52. bool invalidate(IRUnitT &IR, const PreservedAnalyses &PA,
  53. typename AnalysisManagerT::Invalidator &Inv) {
  54. return Handle->invalidate(IR, PA, Inv);
  55. }
  56. };
  57. Result run(IRUnitT &IR, AnalysisManagerT &AM, ExtraArgTs... ExtraArgs) {
  58. return Handle->run(IR, AM, ExtraArgs...);
  59. }
  60. };
  61. Analysis getAnalysis() { return Analysis(static_cast<DerivedT &>(*this)); }
  62. typename Analysis::Result getResult() {
  63. return typename Analysis::Result(static_cast<DerivedT &>(*this));
  64. }
  65. protected:
  66. // FIXME: MSVC seems unable to handle a lambda argument to Invoke from within
  67. // the template, so we use a boring static function.
  68. static bool invalidateCallback(IRUnitT &IR, const PreservedAnalyses &PA,
  69. typename AnalysisManagerT::Invalidator &Inv) {
  70. auto PAC = PA.template getChecker<Analysis>();
  71. return !PAC.preserved() &&
  72. !PAC.template preservedSet<AllAnalysesOn<IRUnitT>>();
  73. }
  74. /// Derived classes should call this in their constructor to set up default
  75. /// mock actions. (We can't do this in our constructor because this has to
  76. /// run after the DerivedT is constructed.)
  77. void setDefaults() {
  78. ON_CALL(static_cast<DerivedT &>(*this),
  79. run(_, _, testing::Matcher<ExtraArgTs>(_)...))
  80. .WillByDefault(Return(this->getResult()));
  81. ON_CALL(static_cast<DerivedT &>(*this), invalidate(_, _, _))
  82. .WillByDefault(Invoke(&invalidateCallback));
  83. }
  84. };
  85. template <typename DerivedT, typename IRUnitT, typename AnalysisManagerT,
  86. typename... ExtraArgTs>
  87. AnalysisKey MockAnalysisHandleBase<DerivedT, IRUnitT, AnalysisManagerT,
  88. ExtraArgTs...>::Analysis::Key;
  89. /// Mock handle for loop analyses.
  90. ///
  91. /// This is provided as a template accepting an (optional) integer. Because
  92. /// analyses are identified and queried by type, this allows constructing
  93. /// multiple handles with distinctly typed nested 'Analysis' types that can be
  94. /// registered and queried. If you want to register multiple loop analysis
  95. /// passes, you'll need to instantiate this type with different values for I.
  96. /// For example:
  97. ///
  98. /// MockLoopAnalysisHandleTemplate<0> h0;
  99. /// MockLoopAnalysisHandleTemplate<1> h1;
  100. /// typedef decltype(h0)::Analysis Analysis0;
  101. /// typedef decltype(h1)::Analysis Analysis1;
  102. template <size_t I = static_cast<size_t>(-1)>
  103. struct MockLoopAnalysisHandleTemplate
  104. : MockAnalysisHandleBase<MockLoopAnalysisHandleTemplate<I>, Loop,
  105. LoopAnalysisManager,
  106. LoopStandardAnalysisResults &> {
  107. typedef typename MockLoopAnalysisHandleTemplate::Analysis Analysis;
  108. MOCK_METHOD3_T(run, typename Analysis::Result(Loop &, LoopAnalysisManager &,
  109. LoopStandardAnalysisResults &));
  110. MOCK_METHOD3_T(invalidate, bool(Loop &, const PreservedAnalyses &,
  111. LoopAnalysisManager::Invalidator &));
  112. MockLoopAnalysisHandleTemplate() { this->setDefaults(); }
  113. };
  114. typedef MockLoopAnalysisHandleTemplate<> MockLoopAnalysisHandle;
  115. struct MockFunctionAnalysisHandle
  116. : MockAnalysisHandleBase<MockFunctionAnalysisHandle, Function> {
  117. MOCK_METHOD2(run, Analysis::Result(Function &, FunctionAnalysisManager &));
  118. MOCK_METHOD3(invalidate, bool(Function &, const PreservedAnalyses &,
  119. FunctionAnalysisManager::Invalidator &));
  120. MockFunctionAnalysisHandle() { setDefaults(); }
  121. };
  122. template <typename DerivedT, typename IRUnitT,
  123. typename AnalysisManagerT = AnalysisManager<IRUnitT>,
  124. typename... ExtraArgTs>
  125. class MockPassHandleBase {
  126. public:
  127. class Pass : public PassInfoMixin<Pass> {
  128. friend MockPassHandleBase;
  129. DerivedT *Handle;
  130. Pass(DerivedT &Handle) : Handle(&Handle) {
  131. static_assert(std::is_base_of<MockPassHandleBase, DerivedT>::value,
  132. "Must pass the derived type to this template!");
  133. }
  134. public:
  135. PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM,
  136. ExtraArgTs... ExtraArgs) {
  137. return Handle->run(IR, AM, ExtraArgs...);
  138. }
  139. };
  140. Pass getPass() { return Pass(static_cast<DerivedT &>(*this)); }
  141. protected:
  142. /// Derived classes should call this in their constructor to set up default
  143. /// mock actions. (We can't do this in our constructor because this has to
  144. /// run after the DerivedT is constructed.)
  145. void setDefaults() {
  146. ON_CALL(static_cast<DerivedT &>(*this),
  147. run(_, _, testing::Matcher<ExtraArgTs>(_)...))
  148. .WillByDefault(Return(PreservedAnalyses::all()));
  149. }
  150. };
  151. struct MockLoopPassHandle
  152. : MockPassHandleBase<MockLoopPassHandle, Loop, LoopAnalysisManager,
  153. LoopStandardAnalysisResults &, LPMUpdater &> {
  154. MOCK_METHOD4(run,
  155. PreservedAnalyses(Loop &, LoopAnalysisManager &,
  156. LoopStandardAnalysisResults &, LPMUpdater &));
  157. MockLoopPassHandle() { setDefaults(); }
  158. };
  159. struct MockFunctionPassHandle
  160. : MockPassHandleBase<MockFunctionPassHandle, Function> {
  161. MOCK_METHOD2(run, PreservedAnalyses(Function &, FunctionAnalysisManager &));
  162. MockFunctionPassHandle() { setDefaults(); }
  163. };
  164. struct MockModulePassHandle : MockPassHandleBase<MockModulePassHandle, Module> {
  165. MOCK_METHOD2(run, PreservedAnalyses(Module &, ModuleAnalysisManager &));
  166. MockModulePassHandle() { setDefaults(); }
  167. };
  168. /// Define a custom matcher for objects which support a 'getName' method
  169. /// returning a StringRef.
  170. ///
  171. /// LLVM often has IR objects or analysis objects which expose a StringRef name
  172. /// and in tests it is convenient to match these by name for readability. This
  173. /// matcher supports any type exposing a getName() method of this form.
  174. ///
  175. /// It should be used as:
  176. ///
  177. /// HasName("my_function")
  178. ///
  179. /// No namespace or other qualification is required.
  180. MATCHER_P(HasName, Name, "") {
  181. // The matcher's name and argument are printed in the case of failure, but we
  182. // also want to print out the name of the argument. This uses an implicitly
  183. // avaiable std::ostream, so we have to construct a std::string.
  184. *result_listener << "has name '" << arg.getName().str() << "'";
  185. return Name == arg.getName();
  186. }
  187. std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) {
  188. SMDiagnostic Err;
  189. return parseAssemblyString(IR, Err, C);
  190. }
  191. class LoopPassManagerTest : public ::testing::Test {
  192. protected:
  193. LLVMContext Context;
  194. std::unique_ptr<Module> M;
  195. LoopAnalysisManager LAM;
  196. FunctionAnalysisManager FAM;
  197. ModuleAnalysisManager MAM;
  198. MockLoopAnalysisHandle MLAHandle;
  199. MockLoopPassHandle MLPHandle;
  200. MockFunctionPassHandle MFPHandle;
  201. MockModulePassHandle MMPHandle;
  202. static PreservedAnalyses
  203. getLoopAnalysisResult(Loop &L, LoopAnalysisManager &AM,
  204. LoopStandardAnalysisResults &AR, LPMUpdater &) {
  205. (void)AM.getResult<MockLoopAnalysisHandle::Analysis>(L, AR);
  206. return PreservedAnalyses::all();
  207. };
  208. public:
  209. LoopPassManagerTest()
  210. : M(parseIR(Context,
  211. "define void @f(i1* %ptr) {\n"
  212. "entry:\n"
  213. " br label %loop.0\n"
  214. "loop.0:\n"
  215. " %cond.0 = load volatile i1, i1* %ptr\n"
  216. " br i1 %cond.0, label %loop.0.0.ph, label %end\n"
  217. "loop.0.0.ph:\n"
  218. " br label %loop.0.0\n"
  219. "loop.0.0:\n"
  220. " %cond.0.0 = load volatile i1, i1* %ptr\n"
  221. " br i1 %cond.0.0, label %loop.0.0, label %loop.0.1.ph\n"
  222. "loop.0.1.ph:\n"
  223. " br label %loop.0.1\n"
  224. "loop.0.1:\n"
  225. " %cond.0.1 = load volatile i1, i1* %ptr\n"
  226. " br i1 %cond.0.1, label %loop.0.1, label %loop.0.latch\n"
  227. "loop.0.latch:\n"
  228. " br label %loop.0\n"
  229. "end:\n"
  230. " ret void\n"
  231. "}\n"
  232. "\n"
  233. "define void @g(i1* %ptr) {\n"
  234. "entry:\n"
  235. " br label %loop.g.0\n"
  236. "loop.g.0:\n"
  237. " %cond.0 = load volatile i1, i1* %ptr\n"
  238. " br i1 %cond.0, label %loop.g.0, label %end\n"
  239. "end:\n"
  240. " ret void\n"
  241. "}\n")),
  242. LAM(true), FAM(true), MAM(true) {
  243. // Register our mock analysis.
  244. LAM.registerPass([&] { return MLAHandle.getAnalysis(); });
  245. // We need DominatorTreeAnalysis for LoopAnalysis.
  246. FAM.registerPass([&] { return DominatorTreeAnalysis(); });
  247. FAM.registerPass([&] { return LoopAnalysis(); });
  248. // We also allow loop passes to assume a set of other analyses and so need
  249. // those.
  250. FAM.registerPass([&] { return AAManager(); });
  251. FAM.registerPass([&] { return AssumptionAnalysis(); });
  252. FAM.registerPass([&] { return MemorySSAAnalysis(); });
  253. FAM.registerPass([&] { return ScalarEvolutionAnalysis(); });
  254. FAM.registerPass([&] { return TargetLibraryAnalysis(); });
  255. FAM.registerPass([&] { return TargetIRAnalysis(); });
  256. // Register required pass instrumentation analysis.
  257. LAM.registerPass([&] { return PassInstrumentationAnalysis(); });
  258. FAM.registerPass([&] { return PassInstrumentationAnalysis(); });
  259. MAM.registerPass([&] { return PassInstrumentationAnalysis(); });
  260. // Cross-register proxies.
  261. LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
  262. FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
  263. FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
  264. MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
  265. }
  266. };
  267. TEST_F(LoopPassManagerTest, Basic) {
  268. ModulePassManager MPM(true);
  269. ::testing::InSequence MakeExpectationsSequenced;
  270. // First we just visit all the loops in all the functions and get their
  271. // analysis results. This will run the analysis a total of four times,
  272. // once for each loop.
  273. EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
  274. .WillOnce(Invoke(getLoopAnalysisResult));
  275. EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
  276. EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
  277. .WillOnce(Invoke(getLoopAnalysisResult));
  278. EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
  279. EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
  280. .WillOnce(Invoke(getLoopAnalysisResult));
  281. EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
  282. EXPECT_CALL(MLPHandle, run(HasName("loop.g.0"), _, _, _))
  283. .WillOnce(Invoke(getLoopAnalysisResult));
  284. EXPECT_CALL(MLAHandle, run(HasName("loop.g.0"), _, _));
  285. // Wire the loop pass through pass managers into the module pipeline.
  286. {
  287. LoopPassManager LPM(true);
  288. LPM.addPass(MLPHandle.getPass());
  289. FunctionPassManager FPM(true);
  290. FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM)));
  291. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
  292. }
  293. // Next we run two passes over the loops. The first one invalidates the
  294. // analyses for one loop, the second ones try to get the analysis results.
  295. // This should force only one analysis to re-run within the loop PM, but will
  296. // also invalidate everything after the loop pass manager finishes.
  297. EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
  298. .WillOnce(DoDefault())
  299. .WillOnce(Invoke(getLoopAnalysisResult));
  300. EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
  301. .WillOnce(InvokeWithoutArgs([] { return PreservedAnalyses::none(); }))
  302. .WillOnce(Invoke(getLoopAnalysisResult));
  303. EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
  304. EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
  305. .WillOnce(DoDefault())
  306. .WillOnce(Invoke(getLoopAnalysisResult));
  307. EXPECT_CALL(MLPHandle, run(HasName("loop.g.0"), _, _, _))
  308. .WillOnce(DoDefault())
  309. .WillOnce(Invoke(getLoopAnalysisResult));
  310. // Wire two loop pass runs into the module pipeline.
  311. {
  312. LoopPassManager LPM(true);
  313. LPM.addPass(MLPHandle.getPass());
  314. LPM.addPass(MLPHandle.getPass());
  315. FunctionPassManager FPM(true);
  316. FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM)));
  317. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
  318. }
  319. // And now run the pipeline across the module.
  320. MPM.run(*M, MAM);
  321. }
  322. TEST_F(LoopPassManagerTest, FunctionPassInvalidationOfLoopAnalyses) {
  323. ModulePassManager MPM(true);
  324. FunctionPassManager FPM(true);
  325. // We process each function completely in sequence.
  326. ::testing::Sequence FSequence, GSequence;
  327. // First, force the analysis result to be computed for each loop.
  328. EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _))
  329. .InSequence(FSequence)
  330. .WillOnce(DoDefault());
  331. EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _))
  332. .InSequence(FSequence)
  333. .WillOnce(DoDefault());
  334. EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _))
  335. .InSequence(FSequence)
  336. .WillOnce(DoDefault());
  337. EXPECT_CALL(MLAHandle, run(HasName("loop.g.0"), _, _))
  338. .InSequence(GSequence)
  339. .WillOnce(DoDefault());
  340. FPM.addPass(createFunctionToLoopPassAdaptor(
  341. RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
  342. // No need to re-run if we require again from a fresh loop pass manager.
  343. FPM.addPass(createFunctionToLoopPassAdaptor(
  344. RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
  345. // For 'f', preserve most things but not the specific loop analyses.
  346. auto PA = getLoopPassPreservedAnalyses();
  347. if (EnableMSSALoopDependency)
  348. PA.preserve<MemorySSAAnalysis>();
  349. EXPECT_CALL(MFPHandle, run(HasName("f"), _))
  350. .InSequence(FSequence)
  351. .WillOnce(Return(PA));
  352. EXPECT_CALL(MLAHandle, invalidate(HasName("loop.0.0"), _, _))
  353. .InSequence(FSequence)
  354. .WillOnce(DoDefault());
  355. // On one loop, skip the invalidation (as though we did an internal update).
  356. EXPECT_CALL(MLAHandle, invalidate(HasName("loop.0.1"), _, _))
  357. .InSequence(FSequence)
  358. .WillOnce(Return(false));
  359. EXPECT_CALL(MLAHandle, invalidate(HasName("loop.0"), _, _))
  360. .InSequence(FSequence)
  361. .WillOnce(DoDefault());
  362. // Now two loops still have to be recomputed.
  363. EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _))
  364. .InSequence(FSequence)
  365. .WillOnce(DoDefault());
  366. EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _))
  367. .InSequence(FSequence)
  368. .WillOnce(DoDefault());
  369. // Preserve things in the second function to ensure invalidation remains
  370. // isolated to one function.
  371. EXPECT_CALL(MFPHandle, run(HasName("g"), _))
  372. .InSequence(GSequence)
  373. .WillOnce(DoDefault());
  374. FPM.addPass(MFPHandle.getPass());
  375. FPM.addPass(createFunctionToLoopPassAdaptor(
  376. RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
  377. EXPECT_CALL(MFPHandle, run(HasName("f"), _))
  378. .InSequence(FSequence)
  379. .WillOnce(DoDefault());
  380. // For 'g', fail to preserve anything, causing the loops themselves to be
  381. // cleared. We don't get an invalidation event here as the loop is gone, but
  382. // we should still have to recompute the analysis.
  383. EXPECT_CALL(MFPHandle, run(HasName("g"), _))
  384. .InSequence(GSequence)
  385. .WillOnce(Return(PreservedAnalyses::none()));
  386. EXPECT_CALL(MLAHandle, run(HasName("loop.g.0"), _, _))
  387. .InSequence(GSequence)
  388. .WillOnce(DoDefault());
  389. FPM.addPass(MFPHandle.getPass());
  390. FPM.addPass(createFunctionToLoopPassAdaptor(
  391. RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
  392. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
  393. // Verify with a separate function pass run that we didn't mess up 'f's
  394. // cache. No analysis runs should be necessary here.
  395. MPM.addPass(createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(
  396. RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>())));
  397. MPM.run(*M, MAM);
  398. }
  399. TEST_F(LoopPassManagerTest, ModulePassInvalidationOfLoopAnalyses) {
  400. ModulePassManager MPM(true);
  401. ::testing::InSequence MakeExpectationsSequenced;
  402. // First, force the analysis result to be computed for each loop.
  403. EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
  404. EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
  405. EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
  406. EXPECT_CALL(MLAHandle, run(HasName("loop.g.0"), _, _));
  407. MPM.addPass(createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(
  408. RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>())));
  409. // Walking all the way out and all the way back in doesn't re-run the
  410. // analysis.
  411. MPM.addPass(createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(
  412. RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>())));
  413. // But a module pass that doesn't preserve the actual mock loop analysis
  414. // invalidates all the way down and forces recomputing.
  415. EXPECT_CALL(MMPHandle, run(_, _)).WillOnce(InvokeWithoutArgs([] {
  416. auto PA = getLoopPassPreservedAnalyses();
  417. PA.preserve<FunctionAnalysisManagerModuleProxy>();
  418. if (EnableMSSALoopDependency)
  419. PA.preserve<MemorySSAAnalysis>();
  420. return PA;
  421. }));
  422. // All the loop analyses from both functions get invalidated before we
  423. // recompute anything.
  424. EXPECT_CALL(MLAHandle, invalidate(HasName("loop.0.0"), _, _));
  425. // On one loop, again skip the invalidation (as though we did an internal
  426. // update).
  427. EXPECT_CALL(MLAHandle, invalidate(HasName("loop.0.1"), _, _))
  428. .WillOnce(Return(false));
  429. EXPECT_CALL(MLAHandle, invalidate(HasName("loop.0"), _, _));
  430. EXPECT_CALL(MLAHandle, invalidate(HasName("loop.g.0"), _, _));
  431. // Now all but one of the loops gets re-analyzed.
  432. EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
  433. EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
  434. EXPECT_CALL(MLAHandle, run(HasName("loop.g.0"), _, _));
  435. MPM.addPass(MMPHandle.getPass());
  436. MPM.addPass(createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(
  437. RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>())));
  438. // Verify that the cached values persist.
  439. MPM.addPass(createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(
  440. RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>())));
  441. // Now we fail to preserve the loop analysis and observe that the loop
  442. // analyses are cleared (so no invalidation event) as the loops themselves
  443. // are no longer valid.
  444. EXPECT_CALL(MMPHandle, run(_, _)).WillOnce(InvokeWithoutArgs([] {
  445. auto PA = PreservedAnalyses::none();
  446. PA.preserve<FunctionAnalysisManagerModuleProxy>();
  447. return PA;
  448. }));
  449. EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
  450. EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
  451. EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
  452. EXPECT_CALL(MLAHandle, run(HasName("loop.g.0"), _, _));
  453. MPM.addPass(MMPHandle.getPass());
  454. MPM.addPass(createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(
  455. RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>())));
  456. // Verify that the cached values persist.
  457. MPM.addPass(createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(
  458. RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>())));
  459. // Next, check that even if we preserve everything within the function itelf,
  460. // if the function's module pass proxy isn't preserved and the potential set
  461. // of functions changes, the clear reaches the loop analyses as well. This
  462. // will again trigger re-runs but not invalidation events.
  463. EXPECT_CALL(MMPHandle, run(_, _)).WillOnce(InvokeWithoutArgs([] {
  464. auto PA = PreservedAnalyses::none();
  465. PA.preserveSet<AllAnalysesOn<Function>>();
  466. PA.preserveSet<AllAnalysesOn<Loop>>();
  467. return PA;
  468. }));
  469. EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
  470. EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
  471. EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
  472. EXPECT_CALL(MLAHandle, run(HasName("loop.g.0"), _, _));
  473. MPM.addPass(MMPHandle.getPass());
  474. MPM.addPass(createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor(
  475. RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>())));
  476. MPM.run(*M, MAM);
  477. }
  478. // Test that if any of the bundled analyses provided in the LPM's signature
  479. // become invalid, the analysis proxy itself becomes invalid and we clear all
  480. // loop analysis results.
  481. TEST_F(LoopPassManagerTest, InvalidationOfBundledAnalyses) {
  482. ModulePassManager MPM(true);
  483. FunctionPassManager FPM(true);
  484. ::testing::InSequence MakeExpectationsSequenced;
  485. // First, force the analysis result to be computed for each loop.
  486. EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
  487. EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
  488. EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
  489. FPM.addPass(createFunctionToLoopPassAdaptor(
  490. RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
  491. // No need to re-run if we require again from a fresh loop pass manager.
  492. FPM.addPass(createFunctionToLoopPassAdaptor(
  493. RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
  494. // Preserving everything but the loop analyses themselves results in
  495. // invalidation and running.
  496. EXPECT_CALL(MFPHandle, run(HasName("f"), _))
  497. .WillOnce(Return(getLoopPassPreservedAnalyses()));
  498. EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
  499. EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
  500. EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
  501. FPM.addPass(MFPHandle.getPass());
  502. FPM.addPass(createFunctionToLoopPassAdaptor(
  503. RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
  504. // The rest don't invalidate analyses, they only trigger re-runs because we
  505. // clear the cache completely.
  506. EXPECT_CALL(MFPHandle, run(HasName("f"), _)).WillOnce(InvokeWithoutArgs([] {
  507. auto PA = PreservedAnalyses::none();
  508. // Not preserving `AAManager`.
  509. PA.preserve<DominatorTreeAnalysis>();
  510. PA.preserve<LoopAnalysis>();
  511. PA.preserve<LoopAnalysisManagerFunctionProxy>();
  512. PA.preserve<ScalarEvolutionAnalysis>();
  513. return PA;
  514. }));
  515. EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
  516. EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
  517. EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
  518. FPM.addPass(MFPHandle.getPass());
  519. FPM.addPass(createFunctionToLoopPassAdaptor(
  520. RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
  521. EXPECT_CALL(MFPHandle, run(HasName("f"), _)).WillOnce(InvokeWithoutArgs([] {
  522. auto PA = PreservedAnalyses::none();
  523. PA.preserve<AAManager>();
  524. // Not preserving `DominatorTreeAnalysis`.
  525. PA.preserve<LoopAnalysis>();
  526. PA.preserve<LoopAnalysisManagerFunctionProxy>();
  527. PA.preserve<ScalarEvolutionAnalysis>();
  528. return PA;
  529. }));
  530. EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
  531. EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
  532. EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
  533. FPM.addPass(MFPHandle.getPass());
  534. FPM.addPass(createFunctionToLoopPassAdaptor(
  535. RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
  536. EXPECT_CALL(MFPHandle, run(HasName("f"), _)).WillOnce(InvokeWithoutArgs([] {
  537. auto PA = PreservedAnalyses::none();
  538. PA.preserve<AAManager>();
  539. PA.preserve<DominatorTreeAnalysis>();
  540. // Not preserving the `LoopAnalysis`.
  541. PA.preserve<LoopAnalysisManagerFunctionProxy>();
  542. PA.preserve<ScalarEvolutionAnalysis>();
  543. return PA;
  544. }));
  545. EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
  546. EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
  547. EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
  548. FPM.addPass(MFPHandle.getPass());
  549. FPM.addPass(createFunctionToLoopPassAdaptor(
  550. RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
  551. EXPECT_CALL(MFPHandle, run(HasName("f"), _)).WillOnce(InvokeWithoutArgs([] {
  552. auto PA = PreservedAnalyses::none();
  553. PA.preserve<AAManager>();
  554. PA.preserve<DominatorTreeAnalysis>();
  555. PA.preserve<LoopAnalysis>();
  556. // Not preserving the `LoopAnalysisManagerFunctionProxy`.
  557. PA.preserve<ScalarEvolutionAnalysis>();
  558. return PA;
  559. }));
  560. EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
  561. EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
  562. EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
  563. FPM.addPass(MFPHandle.getPass());
  564. FPM.addPass(createFunctionToLoopPassAdaptor(
  565. RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
  566. EXPECT_CALL(MFPHandle, run(HasName("f"), _)).WillOnce(InvokeWithoutArgs([] {
  567. auto PA = PreservedAnalyses::none();
  568. PA.preserve<AAManager>();
  569. PA.preserve<DominatorTreeAnalysis>();
  570. PA.preserve<LoopAnalysis>();
  571. PA.preserve<LoopAnalysisManagerFunctionProxy>();
  572. // Not preserving `ScalarEvolutionAnalysis`.
  573. return PA;
  574. }));
  575. EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
  576. EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
  577. EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
  578. FPM.addPass(MFPHandle.getPass());
  579. FPM.addPass(createFunctionToLoopPassAdaptor(
  580. RequireAnalysisLoopPass<MockLoopAnalysisHandle::Analysis>()));
  581. // After all the churn on 'f', we'll compute the loop analysis results for
  582. // 'g' once with a requires pass and then run our mock pass over g a bunch
  583. // but just get cached results each time.
  584. EXPECT_CALL(MLAHandle, run(HasName("loop.g.0"), _, _));
  585. EXPECT_CALL(MFPHandle, run(HasName("g"), _)).Times(6);
  586. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
  587. MPM.run(*M, MAM);
  588. }
  589. TEST_F(LoopPassManagerTest, IndirectInvalidation) {
  590. // We need two distinct analysis types and handles.
  591. enum { A, B };
  592. MockLoopAnalysisHandleTemplate<A> MLAHandleA;
  593. MockLoopAnalysisHandleTemplate<B> MLAHandleB;
  594. LAM.registerPass([&] { return MLAHandleA.getAnalysis(); });
  595. LAM.registerPass([&] { return MLAHandleB.getAnalysis(); });
  596. typedef decltype(MLAHandleA)::Analysis AnalysisA;
  597. typedef decltype(MLAHandleB)::Analysis AnalysisB;
  598. // Set up AnalysisA to depend on our AnalysisB. For testing purposes we just
  599. // need to get the AnalysisB results in AnalysisA's run method and check if
  600. // AnalysisB gets invalidated in AnalysisA's invalidate method.
  601. ON_CALL(MLAHandleA, run(_, _, _))
  602. .WillByDefault(Invoke([&](Loop &L, LoopAnalysisManager &AM,
  603. LoopStandardAnalysisResults &AR) {
  604. (void)AM.getResult<AnalysisB>(L, AR);
  605. return MLAHandleA.getResult();
  606. }));
  607. ON_CALL(MLAHandleA, invalidate(_, _, _))
  608. .WillByDefault(Invoke([](Loop &L, const PreservedAnalyses &PA,
  609. LoopAnalysisManager::Invalidator &Inv) {
  610. auto PAC = PA.getChecker<AnalysisA>();
  611. return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Loop>>()) ||
  612. Inv.invalidate<AnalysisB>(L, PA);
  613. }));
  614. ::testing::InSequence MakeExpectationsSequenced;
  615. // Compute the analyses across all of 'f' first.
  616. EXPECT_CALL(MLAHandleA, run(HasName("loop.0.0"), _, _));
  617. EXPECT_CALL(MLAHandleB, run(HasName("loop.0.0"), _, _));
  618. EXPECT_CALL(MLAHandleA, run(HasName("loop.0.1"), _, _));
  619. EXPECT_CALL(MLAHandleB, run(HasName("loop.0.1"), _, _));
  620. EXPECT_CALL(MLAHandleA, run(HasName("loop.0"), _, _));
  621. EXPECT_CALL(MLAHandleB, run(HasName("loop.0"), _, _));
  622. // Now we invalidate AnalysisB (but not AnalysisA) for one of the loops and
  623. // preserve everything for the rest. This in turn triggers that one loop to
  624. // recompute both AnalysisB *and* AnalysisA if indirect invalidation is
  625. // working.
  626. EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
  627. .WillOnce(InvokeWithoutArgs([] {
  628. auto PA = getLoopPassPreservedAnalyses();
  629. // Specifically preserve AnalysisA so that it would survive if it
  630. // didn't depend on AnalysisB.
  631. PA.preserve<AnalysisA>();
  632. return PA;
  633. }));
  634. // It happens that AnalysisB is invalidated first. That shouldn't matter
  635. // though, and we should still call AnalysisA's invalidation.
  636. EXPECT_CALL(MLAHandleB, invalidate(HasName("loop.0.0"), _, _));
  637. EXPECT_CALL(MLAHandleA, invalidate(HasName("loop.0.0"), _, _));
  638. EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
  639. .WillOnce(Invoke([](Loop &L, LoopAnalysisManager &AM,
  640. LoopStandardAnalysisResults &AR, LPMUpdater &) {
  641. (void)AM.getResult<AnalysisA>(L, AR);
  642. return PreservedAnalyses::all();
  643. }));
  644. EXPECT_CALL(MLAHandleA, run(HasName("loop.0.0"), _, _));
  645. EXPECT_CALL(MLAHandleB, run(HasName("loop.0.0"), _, _));
  646. // The rest of the loops should run and get cached results.
  647. EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
  648. .Times(2)
  649. .WillRepeatedly(Invoke([](Loop &L, LoopAnalysisManager &AM,
  650. LoopStandardAnalysisResults &AR, LPMUpdater &) {
  651. (void)AM.getResult<AnalysisA>(L, AR);
  652. return PreservedAnalyses::all();
  653. }));
  654. EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
  655. .Times(2)
  656. .WillRepeatedly(Invoke([](Loop &L, LoopAnalysisManager &AM,
  657. LoopStandardAnalysisResults &AR, LPMUpdater &) {
  658. (void)AM.getResult<AnalysisA>(L, AR);
  659. return PreservedAnalyses::all();
  660. }));
  661. // The run over 'g' should be boring, with us just computing the analyses once
  662. // up front and then running loop passes and getting cached results.
  663. EXPECT_CALL(MLAHandleA, run(HasName("loop.g.0"), _, _));
  664. EXPECT_CALL(MLAHandleB, run(HasName("loop.g.0"), _, _));
  665. EXPECT_CALL(MLPHandle, run(HasName("loop.g.0"), _, _, _))
  666. .Times(2)
  667. .WillRepeatedly(Invoke([](Loop &L, LoopAnalysisManager &AM,
  668. LoopStandardAnalysisResults &AR, LPMUpdater &) {
  669. (void)AM.getResult<AnalysisA>(L, AR);
  670. return PreservedAnalyses::all();
  671. }));
  672. // Build the pipeline and run it.
  673. ModulePassManager MPM(true);
  674. FunctionPassManager FPM(true);
  675. FPM.addPass(
  676. createFunctionToLoopPassAdaptor(RequireAnalysisLoopPass<AnalysisA>()));
  677. LoopPassManager LPM(true);
  678. LPM.addPass(MLPHandle.getPass());
  679. LPM.addPass(MLPHandle.getPass());
  680. FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM)));
  681. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
  682. MPM.run(*M, MAM);
  683. }
  684. TEST_F(LoopPassManagerTest, IndirectOuterPassInvalidation) {
  685. typedef decltype(MLAHandle)::Analysis LoopAnalysis;
  686. MockFunctionAnalysisHandle MFAHandle;
  687. FAM.registerPass([&] { return MFAHandle.getAnalysis(); });
  688. typedef decltype(MFAHandle)::Analysis FunctionAnalysis;
  689. // Set up the loop analysis to depend on both the function and module
  690. // analysis.
  691. ON_CALL(MLAHandle, run(_, _, _))
  692. .WillByDefault(Invoke([&](Loop &L, LoopAnalysisManager &AM,
  693. LoopStandardAnalysisResults &AR) {
  694. auto &FAMP = AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR);
  695. auto &FAM = FAMP.getManager();
  696. Function &F = *L.getHeader()->getParent();
  697. if (FAM.getCachedResult<FunctionAnalysis>(F))
  698. FAMP.registerOuterAnalysisInvalidation<FunctionAnalysis,
  699. LoopAnalysis>();
  700. return MLAHandle.getResult();
  701. }));
  702. ::testing::InSequence MakeExpectationsSequenced;
  703. // Compute the analyses across all of 'f' first.
  704. EXPECT_CALL(MFPHandle, run(HasName("f"), _))
  705. .WillOnce(Invoke([](Function &F, FunctionAnalysisManager &AM) {
  706. // Force the computing of the function analysis so it is available in
  707. // this function.
  708. (void)AM.getResult<FunctionAnalysis>(F);
  709. return PreservedAnalyses::all();
  710. }));
  711. EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
  712. EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
  713. EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
  714. // Now invalidate the function analysis but preserve the loop analyses.
  715. // This should trigger immediate invalidation of the loop analyses, despite
  716. // the fact that they were preserved.
  717. EXPECT_CALL(MFPHandle, run(HasName("f"), _)).WillOnce(InvokeWithoutArgs([] {
  718. auto PA = getLoopPassPreservedAnalyses();
  719. if (EnableMSSALoopDependency)
  720. PA.preserve<MemorySSAAnalysis>();
  721. PA.preserveSet<AllAnalysesOn<Loop>>();
  722. return PA;
  723. }));
  724. EXPECT_CALL(MLAHandle, invalidate(HasName("loop.0.0"), _, _));
  725. EXPECT_CALL(MLAHandle, invalidate(HasName("loop.0.1"), _, _));
  726. EXPECT_CALL(MLAHandle, invalidate(HasName("loop.0"), _, _));
  727. // And re-running a requires pass recomputes them.
  728. EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
  729. EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
  730. EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
  731. // When we run over 'g' we don't populate the cache with the function
  732. // analysis.
  733. EXPECT_CALL(MFPHandle, run(HasName("g"), _))
  734. .WillOnce(Return(PreservedAnalyses::all()));
  735. EXPECT_CALL(MLAHandle, run(HasName("loop.g.0"), _, _));
  736. // Which means that no extra invalidation occurs and cached values are used.
  737. EXPECT_CALL(MFPHandle, run(HasName("g"), _)).WillOnce(InvokeWithoutArgs([] {
  738. auto PA = getLoopPassPreservedAnalyses();
  739. if (EnableMSSALoopDependency)
  740. PA.preserve<MemorySSAAnalysis>();
  741. PA.preserveSet<AllAnalysesOn<Loop>>();
  742. return PA;
  743. }));
  744. // Build the pipeline and run it.
  745. ModulePassManager MPM(true);
  746. FunctionPassManager FPM(true);
  747. FPM.addPass(MFPHandle.getPass());
  748. FPM.addPass(
  749. createFunctionToLoopPassAdaptor(RequireAnalysisLoopPass<LoopAnalysis>()));
  750. FPM.addPass(MFPHandle.getPass());
  751. FPM.addPass(
  752. createFunctionToLoopPassAdaptor(RequireAnalysisLoopPass<LoopAnalysis>()));
  753. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
  754. MPM.run(*M, MAM);
  755. }
  756. TEST_F(LoopPassManagerTest, LoopChildInsertion) {
  757. // Super boring module with three loops in a single loop nest.
  758. M = parseIR(Context, "define void @f(i1* %ptr) {\n"
  759. "entry:\n"
  760. " br label %loop.0\n"
  761. "loop.0:\n"
  762. " %cond.0 = load volatile i1, i1* %ptr\n"
  763. " br i1 %cond.0, label %loop.0.0.ph, label %end\n"
  764. "loop.0.0.ph:\n"
  765. " br label %loop.0.0\n"
  766. "loop.0.0:\n"
  767. " %cond.0.0 = load volatile i1, i1* %ptr\n"
  768. " br i1 %cond.0.0, label %loop.0.0, label %loop.0.1.ph\n"
  769. "loop.0.1.ph:\n"
  770. " br label %loop.0.1\n"
  771. "loop.0.1:\n"
  772. " %cond.0.1 = load volatile i1, i1* %ptr\n"
  773. " br i1 %cond.0.1, label %loop.0.1, label %loop.0.2.ph\n"
  774. "loop.0.2.ph:\n"
  775. " br label %loop.0.2\n"
  776. "loop.0.2:\n"
  777. " %cond.0.2 = load volatile i1, i1* %ptr\n"
  778. " br i1 %cond.0.2, label %loop.0.2, label %loop.0.latch\n"
  779. "loop.0.latch:\n"
  780. " br label %loop.0\n"
  781. "end:\n"
  782. " ret void\n"
  783. "}\n");
  784. // Build up variables referring into the IR so we can rewrite it below
  785. // easily.
  786. Function &F = *M->begin();
  787. ASSERT_THAT(F, HasName("f"));
  788. Argument &Ptr = *F.arg_begin();
  789. auto BBI = F.begin();
  790. BasicBlock &EntryBB = *BBI++;
  791. ASSERT_THAT(EntryBB, HasName("entry"));
  792. BasicBlock &Loop0BB = *BBI++;
  793. ASSERT_THAT(Loop0BB, HasName("loop.0"));
  794. BasicBlock &Loop00PHBB = *BBI++;
  795. ASSERT_THAT(Loop00PHBB, HasName("loop.0.0.ph"));
  796. BasicBlock &Loop00BB = *BBI++;
  797. ASSERT_THAT(Loop00BB, HasName("loop.0.0"));
  798. BasicBlock &Loop01PHBB = *BBI++;
  799. ASSERT_THAT(Loop01PHBB, HasName("loop.0.1.ph"));
  800. BasicBlock &Loop01BB = *BBI++;
  801. ASSERT_THAT(Loop01BB, HasName("loop.0.1"));
  802. BasicBlock &Loop02PHBB = *BBI++;
  803. ASSERT_THAT(Loop02PHBB, HasName("loop.0.2.ph"));
  804. BasicBlock &Loop02BB = *BBI++;
  805. ASSERT_THAT(Loop02BB, HasName("loop.0.2"));
  806. BasicBlock &Loop0LatchBB = *BBI++;
  807. ASSERT_THAT(Loop0LatchBB, HasName("loop.0.latch"));
  808. BasicBlock &EndBB = *BBI++;
  809. ASSERT_THAT(EndBB, HasName("end"));
  810. ASSERT_THAT(BBI, F.end());
  811. auto CreateCondBr = [&](BasicBlock *TrueBB, BasicBlock *FalseBB,
  812. const char *Name, BasicBlock *BB) {
  813. auto *Cond = new LoadInst(Type::getInt1Ty(Context), &Ptr, Name,
  814. /*isVolatile*/ true, BB);
  815. BranchInst::Create(TrueBB, FalseBB, Cond, BB);
  816. };
  817. // Build the pass managers and register our pipeline. We build a single loop
  818. // pass pipeline consisting of three mock pass runs over each loop. After
  819. // this we run both domtree and loop verification passes to make sure that
  820. // the IR remained valid during our mutations.
  821. ModulePassManager MPM(true);
  822. FunctionPassManager FPM(true);
  823. LoopPassManager LPM(true);
  824. LPM.addPass(MLPHandle.getPass());
  825. LPM.addPass(MLPHandle.getPass());
  826. LPM.addPass(MLPHandle.getPass());
  827. FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM)));
  828. FPM.addPass(DominatorTreeVerifierPass());
  829. FPM.addPass(LoopVerifierPass());
  830. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
  831. // All the visit orders are deterministic, so we use simple fully order
  832. // expectations.
  833. ::testing::InSequence MakeExpectationsSequenced;
  834. // We run loop passes three times over each of the loops.
  835. EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
  836. .WillOnce(Invoke(getLoopAnalysisResult));
  837. EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
  838. EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
  839. .Times(2)
  840. .WillRepeatedly(Invoke(getLoopAnalysisResult));
  841. EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
  842. .WillOnce(Invoke(getLoopAnalysisResult));
  843. EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
  844. // When running over the middle loop, the second run inserts two new child
  845. // loops, inserting them and itself into the worklist.
  846. BasicBlock *NewLoop010BB, *NewLoop01LatchBB;
  847. EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
  848. .WillOnce(Invoke([&](Loop &L, LoopAnalysisManager &AM,
  849. LoopStandardAnalysisResults &AR,
  850. LPMUpdater &Updater) {
  851. auto *NewLoop = AR.LI.AllocateLoop();
  852. L.addChildLoop(NewLoop);
  853. auto *NewLoop010PHBB =
  854. BasicBlock::Create(Context, "loop.0.1.0.ph", &F, &Loop02PHBB);
  855. NewLoop010BB =
  856. BasicBlock::Create(Context, "loop.0.1.0", &F, &Loop02PHBB);
  857. NewLoop01LatchBB =
  858. BasicBlock::Create(Context, "loop.0.1.latch", &F, &Loop02PHBB);
  859. Loop01BB.getTerminator()->replaceUsesOfWith(&Loop01BB, NewLoop010PHBB);
  860. BranchInst::Create(NewLoop010BB, NewLoop010PHBB);
  861. CreateCondBr(NewLoop01LatchBB, NewLoop010BB, "cond.0.1.0",
  862. NewLoop010BB);
  863. BranchInst::Create(&Loop01BB, NewLoop01LatchBB);
  864. AR.DT.addNewBlock(NewLoop010PHBB, &Loop01BB);
  865. AR.DT.addNewBlock(NewLoop010BB, NewLoop010PHBB);
  866. AR.DT.addNewBlock(NewLoop01LatchBB, NewLoop010BB);
  867. EXPECT_TRUE(AR.DT.verify());
  868. L.addBasicBlockToLoop(NewLoop010PHBB, AR.LI);
  869. NewLoop->addBasicBlockToLoop(NewLoop010BB, AR.LI);
  870. L.addBasicBlockToLoop(NewLoop01LatchBB, AR.LI);
  871. NewLoop->verifyLoop();
  872. L.verifyLoop();
  873. Updater.addChildLoops({NewLoop});
  874. return PreservedAnalyses::all();
  875. }));
  876. // We should immediately drop down to fully visit the new inner loop.
  877. EXPECT_CALL(MLPHandle, run(HasName("loop.0.1.0"), _, _, _))
  878. .WillOnce(Invoke(getLoopAnalysisResult));
  879. EXPECT_CALL(MLAHandle, run(HasName("loop.0.1.0"), _, _));
  880. EXPECT_CALL(MLPHandle, run(HasName("loop.0.1.0"), _, _, _))
  881. .Times(2)
  882. .WillRepeatedly(Invoke(getLoopAnalysisResult));
  883. // After visiting the inner loop, we should re-visit the second loop
  884. // reflecting its new loop nest structure.
  885. EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
  886. .WillOnce(Invoke(getLoopAnalysisResult));
  887. // In the second run over the middle loop after we've visited the new child,
  888. // we add another child to check that we can repeatedly add children, and add
  889. // children to a loop that already has children.
  890. EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
  891. .WillOnce(Invoke([&](Loop &L, LoopAnalysisManager &AM,
  892. LoopStandardAnalysisResults &AR,
  893. LPMUpdater &Updater) {
  894. auto *NewLoop = AR.LI.AllocateLoop();
  895. L.addChildLoop(NewLoop);
  896. auto *NewLoop011PHBB = BasicBlock::Create(Context, "loop.0.1.1.ph", &F, NewLoop01LatchBB);
  897. auto *NewLoop011BB = BasicBlock::Create(Context, "loop.0.1.1", &F, NewLoop01LatchBB);
  898. NewLoop010BB->getTerminator()->replaceUsesOfWith(NewLoop01LatchBB,
  899. NewLoop011PHBB);
  900. BranchInst::Create(NewLoop011BB, NewLoop011PHBB);
  901. CreateCondBr(NewLoop01LatchBB, NewLoop011BB, "cond.0.1.1",
  902. NewLoop011BB);
  903. AR.DT.addNewBlock(NewLoop011PHBB, NewLoop010BB);
  904. auto *NewDTNode = AR.DT.addNewBlock(NewLoop011BB, NewLoop011PHBB);
  905. AR.DT.changeImmediateDominator(AR.DT[NewLoop01LatchBB], NewDTNode);
  906. EXPECT_TRUE(AR.DT.verify());
  907. L.addBasicBlockToLoop(NewLoop011PHBB, AR.LI);
  908. NewLoop->addBasicBlockToLoop(NewLoop011BB, AR.LI);
  909. NewLoop->verifyLoop();
  910. L.verifyLoop();
  911. Updater.addChildLoops({NewLoop});
  912. return PreservedAnalyses::all();
  913. }));
  914. // Again, we should immediately drop down to visit the new, unvisited child
  915. // loop. We don't need to revisit the other child though.
  916. EXPECT_CALL(MLPHandle, run(HasName("loop.0.1.1"), _, _, _))
  917. .WillOnce(Invoke(getLoopAnalysisResult));
  918. EXPECT_CALL(MLAHandle, run(HasName("loop.0.1.1"), _, _));
  919. EXPECT_CALL(MLPHandle, run(HasName("loop.0.1.1"), _, _, _))
  920. .Times(2)
  921. .WillRepeatedly(Invoke(getLoopAnalysisResult));
  922. // And now we should pop back up to the second loop and do a full pipeline of
  923. // three passes on its current form.
  924. EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
  925. .Times(3)
  926. .WillRepeatedly(Invoke(getLoopAnalysisResult));
  927. EXPECT_CALL(MLPHandle, run(HasName("loop.0.2"), _, _, _))
  928. .WillOnce(Invoke(getLoopAnalysisResult));
  929. EXPECT_CALL(MLAHandle, run(HasName("loop.0.2"), _, _));
  930. EXPECT_CALL(MLPHandle, run(HasName("loop.0.2"), _, _, _))
  931. .Times(2)
  932. .WillRepeatedly(Invoke(getLoopAnalysisResult));
  933. EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
  934. .WillOnce(Invoke(getLoopAnalysisResult));
  935. EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
  936. EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
  937. .Times(2)
  938. .WillRepeatedly(Invoke(getLoopAnalysisResult));
  939. // Now that all the expected actions are registered, run the pipeline over
  940. // our module. All of our expectations are verified when the test finishes.
  941. MPM.run(*M, MAM);
  942. }
  943. TEST_F(LoopPassManagerTest, LoopPeerInsertion) {
  944. // Super boring module with two loop nests and loop nest with two child
  945. // loops.
  946. M = parseIR(Context, "define void @f(i1* %ptr) {\n"
  947. "entry:\n"
  948. " br label %loop.0\n"
  949. "loop.0:\n"
  950. " %cond.0 = load volatile i1, i1* %ptr\n"
  951. " br i1 %cond.0, label %loop.0.0.ph, label %loop.2.ph\n"
  952. "loop.0.0.ph:\n"
  953. " br label %loop.0.0\n"
  954. "loop.0.0:\n"
  955. " %cond.0.0 = load volatile i1, i1* %ptr\n"
  956. " br i1 %cond.0.0, label %loop.0.0, label %loop.0.2.ph\n"
  957. "loop.0.2.ph:\n"
  958. " br label %loop.0.2\n"
  959. "loop.0.2:\n"
  960. " %cond.0.2 = load volatile i1, i1* %ptr\n"
  961. " br i1 %cond.0.2, label %loop.0.2, label %loop.0.latch\n"
  962. "loop.0.latch:\n"
  963. " br label %loop.0\n"
  964. "loop.2.ph:\n"
  965. " br label %loop.2\n"
  966. "loop.2:\n"
  967. " %cond.2 = load volatile i1, i1* %ptr\n"
  968. " br i1 %cond.2, label %loop.2, label %end\n"
  969. "end:\n"
  970. " ret void\n"
  971. "}\n");
  972. // Build up variables referring into the IR so we can rewrite it below
  973. // easily.
  974. Function &F = *M->begin();
  975. ASSERT_THAT(F, HasName("f"));
  976. Argument &Ptr = *F.arg_begin();
  977. auto BBI = F.begin();
  978. BasicBlock &EntryBB = *BBI++;
  979. ASSERT_THAT(EntryBB, HasName("entry"));
  980. BasicBlock &Loop0BB = *BBI++;
  981. ASSERT_THAT(Loop0BB, HasName("loop.0"));
  982. BasicBlock &Loop00PHBB = *BBI++;
  983. ASSERT_THAT(Loop00PHBB, HasName("loop.0.0.ph"));
  984. BasicBlock &Loop00BB = *BBI++;
  985. ASSERT_THAT(Loop00BB, HasName("loop.0.0"));
  986. BasicBlock &Loop02PHBB = *BBI++;
  987. ASSERT_THAT(Loop02PHBB, HasName("loop.0.2.ph"));
  988. BasicBlock &Loop02BB = *BBI++;
  989. ASSERT_THAT(Loop02BB, HasName("loop.0.2"));
  990. BasicBlock &Loop0LatchBB = *BBI++;
  991. ASSERT_THAT(Loop0LatchBB, HasName("loop.0.latch"));
  992. BasicBlock &Loop2PHBB = *BBI++;
  993. ASSERT_THAT(Loop2PHBB, HasName("loop.2.ph"));
  994. BasicBlock &Loop2BB = *BBI++;
  995. ASSERT_THAT(Loop2BB, HasName("loop.2"));
  996. BasicBlock &EndBB = *BBI++;
  997. ASSERT_THAT(EndBB, HasName("end"));
  998. ASSERT_THAT(BBI, F.end());
  999. auto CreateCondBr = [&](BasicBlock *TrueBB, BasicBlock *FalseBB,
  1000. const char *Name, BasicBlock *BB) {
  1001. auto *Cond = new LoadInst(Type::getInt1Ty(Context), &Ptr, Name,
  1002. /*isVolatile*/ true, BB);
  1003. BranchInst::Create(TrueBB, FalseBB, Cond, BB);
  1004. };
  1005. // Build the pass managers and register our pipeline. We build a single loop
  1006. // pass pipeline consisting of three mock pass runs over each loop. After
  1007. // this we run both domtree and loop verification passes to make sure that
  1008. // the IR remained valid during our mutations.
  1009. ModulePassManager MPM(true);
  1010. FunctionPassManager FPM(true);
  1011. LoopPassManager LPM(true);
  1012. LPM.addPass(MLPHandle.getPass());
  1013. LPM.addPass(MLPHandle.getPass());
  1014. LPM.addPass(MLPHandle.getPass());
  1015. FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM)));
  1016. FPM.addPass(DominatorTreeVerifierPass());
  1017. FPM.addPass(LoopVerifierPass());
  1018. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
  1019. // All the visit orders are deterministic, so we use simple fully order
  1020. // expectations.
  1021. ::testing::InSequence MakeExpectationsSequenced;
  1022. // We run loop passes three times over each of the loops.
  1023. EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
  1024. .WillOnce(Invoke(getLoopAnalysisResult));
  1025. EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
  1026. // On the second run, we insert a sibling loop.
  1027. EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
  1028. .WillOnce(Invoke([&](Loop &L, LoopAnalysisManager &AM,
  1029. LoopStandardAnalysisResults &AR,
  1030. LPMUpdater &Updater) {
  1031. auto *NewLoop = AR.LI.AllocateLoop();
  1032. L.getParentLoop()->addChildLoop(NewLoop);
  1033. auto *NewLoop01PHBB = BasicBlock::Create(Context, "loop.0.1.ph", &F, &Loop02PHBB);
  1034. auto *NewLoop01BB = BasicBlock::Create(Context, "loop.0.1", &F, &Loop02PHBB);
  1035. BranchInst::Create(NewLoop01BB, NewLoop01PHBB);
  1036. CreateCondBr(&Loop02PHBB, NewLoop01BB, "cond.0.1", NewLoop01BB);
  1037. Loop00BB.getTerminator()->replaceUsesOfWith(&Loop02PHBB, NewLoop01PHBB);
  1038. AR.DT.addNewBlock(NewLoop01PHBB, &Loop00BB);
  1039. auto *NewDTNode = AR.DT.addNewBlock(NewLoop01BB, NewLoop01PHBB);
  1040. AR.DT.changeImmediateDominator(AR.DT[&Loop02PHBB], NewDTNode);
  1041. EXPECT_TRUE(AR.DT.verify());
  1042. L.getParentLoop()->addBasicBlockToLoop(NewLoop01PHBB, AR.LI);
  1043. NewLoop->addBasicBlockToLoop(NewLoop01BB, AR.LI);
  1044. L.getParentLoop()->verifyLoop();
  1045. Updater.addSiblingLoops({NewLoop});
  1046. return PreservedAnalyses::all();
  1047. }));
  1048. // We finish processing this loop as sibling loops don't perturb the
  1049. // postorder walk.
  1050. EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
  1051. .WillOnce(Invoke(getLoopAnalysisResult));
  1052. // We visit the inserted sibling next.
  1053. EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
  1054. .WillOnce(Invoke(getLoopAnalysisResult));
  1055. EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
  1056. EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
  1057. .Times(2)
  1058. .WillRepeatedly(Invoke(getLoopAnalysisResult));
  1059. EXPECT_CALL(MLPHandle, run(HasName("loop.0.2"), _, _, _))
  1060. .WillOnce(Invoke(getLoopAnalysisResult));
  1061. EXPECT_CALL(MLAHandle, run(HasName("loop.0.2"), _, _));
  1062. EXPECT_CALL(MLPHandle, run(HasName("loop.0.2"), _, _, _))
  1063. .WillOnce(Invoke(getLoopAnalysisResult));
  1064. // Next, on the third pass run on the last inner loop we add more new
  1065. // siblings, more than one, and one with nested child loops. By doing this at
  1066. // the end we make sure that edge case works well.
  1067. EXPECT_CALL(MLPHandle, run(HasName("loop.0.2"), _, _, _))
  1068. .WillOnce(Invoke([&](Loop &L, LoopAnalysisManager &AM,
  1069. LoopStandardAnalysisResults &AR,
  1070. LPMUpdater &Updater) {
  1071. Loop *NewLoops[] = {AR.LI.AllocateLoop(), AR.LI.AllocateLoop(),
  1072. AR.LI.AllocateLoop()};
  1073. L.getParentLoop()->addChildLoop(NewLoops[0]);
  1074. L.getParentLoop()->addChildLoop(NewLoops[1]);
  1075. NewLoops[1]->addChildLoop(NewLoops[2]);
  1076. auto *NewLoop03PHBB =
  1077. BasicBlock::Create(Context, "loop.0.3.ph", &F, &Loop0LatchBB);
  1078. auto *NewLoop03BB =
  1079. BasicBlock::Create(Context, "loop.0.3", &F, &Loop0LatchBB);
  1080. auto *NewLoop04PHBB =
  1081. BasicBlock::Create(Context, "loop.0.4.ph", &F, &Loop0LatchBB);
  1082. auto *NewLoop04BB =
  1083. BasicBlock::Create(Context, "loop.0.4", &F, &Loop0LatchBB);
  1084. auto *NewLoop040PHBB =
  1085. BasicBlock::Create(Context, "loop.0.4.0.ph", &F, &Loop0LatchBB);
  1086. auto *NewLoop040BB =
  1087. BasicBlock::Create(Context, "loop.0.4.0", &F, &Loop0LatchBB);
  1088. auto *NewLoop04LatchBB =
  1089. BasicBlock::Create(Context, "loop.0.4.latch", &F, &Loop0LatchBB);
  1090. Loop02BB.getTerminator()->replaceUsesOfWith(&Loop0LatchBB, NewLoop03PHBB);
  1091. BranchInst::Create(NewLoop03BB, NewLoop03PHBB);
  1092. CreateCondBr(NewLoop04PHBB, NewLoop03BB, "cond.0.3", NewLoop03BB);
  1093. BranchInst::Create(NewLoop04BB, NewLoop04PHBB);
  1094. CreateCondBr(&Loop0LatchBB, NewLoop040PHBB, "cond.0.4", NewLoop04BB);
  1095. BranchInst::Create(NewLoop040BB, NewLoop040PHBB);
  1096. CreateCondBr(NewLoop04LatchBB, NewLoop040BB, "cond.0.4.0", NewLoop040BB);
  1097. BranchInst::Create(NewLoop04BB, NewLoop04LatchBB);
  1098. AR.DT.addNewBlock(NewLoop03PHBB, &Loop02BB);
  1099. AR.DT.addNewBlock(NewLoop03BB, NewLoop03PHBB);
  1100. AR.DT.addNewBlock(NewLoop04PHBB, NewLoop03BB);
  1101. auto *NewDTNode = AR.DT.addNewBlock(NewLoop04BB, NewLoop04PHBB);
  1102. AR.DT.changeImmediateDominator(AR.DT[&Loop0LatchBB], NewDTNode);
  1103. AR.DT.addNewBlock(NewLoop040PHBB, NewLoop04BB);
  1104. AR.DT.addNewBlock(NewLoop040BB, NewLoop040PHBB);
  1105. AR.DT.addNewBlock(NewLoop04LatchBB, NewLoop040BB);
  1106. EXPECT_TRUE(AR.DT.verify());
  1107. L.getParentLoop()->addBasicBlockToLoop(NewLoop03PHBB, AR.LI);
  1108. NewLoops[0]->addBasicBlockToLoop(NewLoop03BB, AR.LI);
  1109. L.getParentLoop()->addBasicBlockToLoop(NewLoop04PHBB, AR.LI);
  1110. NewLoops[1]->addBasicBlockToLoop(NewLoop04BB, AR.LI);
  1111. NewLoops[1]->addBasicBlockToLoop(NewLoop040PHBB, AR.LI);
  1112. NewLoops[2]->addBasicBlockToLoop(NewLoop040BB, AR.LI);
  1113. NewLoops[1]->addBasicBlockToLoop(NewLoop04LatchBB, AR.LI);
  1114. L.getParentLoop()->verifyLoop();
  1115. Updater.addSiblingLoops({NewLoops[0], NewLoops[1]});
  1116. return PreservedAnalyses::all();
  1117. }));
  1118. EXPECT_CALL(MLPHandle, run(HasName("loop.0.3"), _, _, _))
  1119. .WillOnce(Invoke(getLoopAnalysisResult));
  1120. EXPECT_CALL(MLAHandle, run(HasName("loop.0.3"), _, _));
  1121. EXPECT_CALL(MLPHandle, run(HasName("loop.0.3"), _, _, _))
  1122. .Times(2)
  1123. .WillRepeatedly(Invoke(getLoopAnalysisResult));
  1124. // Note that we need to visit the inner loop of this added sibling before the
  1125. // sibling itself!
  1126. EXPECT_CALL(MLPHandle, run(HasName("loop.0.4.0"), _, _, _))
  1127. .WillOnce(Invoke(getLoopAnalysisResult));
  1128. EXPECT_CALL(MLAHandle, run(HasName("loop.0.4.0"), _, _));
  1129. EXPECT_CALL(MLPHandle, run(HasName("loop.0.4.0"), _, _, _))
  1130. .Times(2)
  1131. .WillRepeatedly(Invoke(getLoopAnalysisResult));
  1132. EXPECT_CALL(MLPHandle, run(HasName("loop.0.4"), _, _, _))
  1133. .WillOnce(Invoke(getLoopAnalysisResult));
  1134. EXPECT_CALL(MLAHandle, run(HasName("loop.0.4"), _, _));
  1135. EXPECT_CALL(MLPHandle, run(HasName("loop.0.4"), _, _, _))
  1136. .Times(2)
  1137. .WillRepeatedly(Invoke(getLoopAnalysisResult));
  1138. // And only now do we visit the outermost loop of the nest.
  1139. EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
  1140. .WillOnce(Invoke(getLoopAnalysisResult));
  1141. EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
  1142. // On the second pass, we add sibling loops which become new top-level loops.
  1143. EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
  1144. .WillOnce(Invoke([&](Loop &L, LoopAnalysisManager &AM,
  1145. LoopStandardAnalysisResults &AR,
  1146. LPMUpdater &Updater) {
  1147. auto *NewLoop = AR.LI.AllocateLoop();
  1148. AR.LI.addTopLevelLoop(NewLoop);
  1149. auto *NewLoop1PHBB = BasicBlock::Create(Context, "loop.1.ph", &F, &Loop2BB);
  1150. auto *NewLoop1BB = BasicBlock::Create(Context, "loop.1", &F, &Loop2BB);
  1151. BranchInst::Create(NewLoop1BB, NewLoop1PHBB);
  1152. CreateCondBr(&Loop2PHBB, NewLoop1BB, "cond.1", NewLoop1BB);
  1153. Loop0BB.getTerminator()->replaceUsesOfWith(&Loop2PHBB, NewLoop1PHBB);
  1154. AR.DT.addNewBlock(NewLoop1PHBB, &Loop0BB);
  1155. auto *NewDTNode = AR.DT.addNewBlock(NewLoop1BB, NewLoop1PHBB);
  1156. AR.DT.changeImmediateDominator(AR.DT[&Loop2PHBB], NewDTNode);
  1157. EXPECT_TRUE(AR.DT.verify());
  1158. NewLoop->addBasicBlockToLoop(NewLoop1BB, AR.LI);
  1159. NewLoop->verifyLoop();
  1160. Updater.addSiblingLoops({NewLoop});
  1161. return PreservedAnalyses::all();
  1162. }));
  1163. EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
  1164. .WillOnce(Invoke(getLoopAnalysisResult));
  1165. EXPECT_CALL(MLPHandle, run(HasName("loop.1"), _, _, _))
  1166. .WillOnce(Invoke(getLoopAnalysisResult));
  1167. EXPECT_CALL(MLAHandle, run(HasName("loop.1"), _, _));
  1168. EXPECT_CALL(MLPHandle, run(HasName("loop.1"), _, _, _))
  1169. .Times(2)
  1170. .WillRepeatedly(Invoke(getLoopAnalysisResult));
  1171. EXPECT_CALL(MLPHandle, run(HasName("loop.2"), _, _, _))
  1172. .WillOnce(Invoke(getLoopAnalysisResult));
  1173. EXPECT_CALL(MLAHandle, run(HasName("loop.2"), _, _));
  1174. EXPECT_CALL(MLPHandle, run(HasName("loop.2"), _, _, _))
  1175. .Times(2)
  1176. .WillRepeatedly(Invoke(getLoopAnalysisResult));
  1177. // Now that all the expected actions are registered, run the pipeline over
  1178. // our module. All of our expectations are verified when the test finishes.
  1179. MPM.run(*M, MAM);
  1180. }
  1181. TEST_F(LoopPassManagerTest, LoopDeletion) {
  1182. // Build a module with a single loop nest that contains one outer loop with
  1183. // three subloops, and one of those with its own subloop. We will
  1184. // incrementally delete all of these to test different deletion scenarios.
  1185. M = parseIR(Context, "define void @f(i1* %ptr) {\n"
  1186. "entry:\n"
  1187. " br label %loop.0\n"
  1188. "loop.0:\n"
  1189. " %cond.0 = load volatile i1, i1* %ptr\n"
  1190. " br i1 %cond.0, label %loop.0.0.ph, label %end\n"
  1191. "loop.0.0.ph:\n"
  1192. " br label %loop.0.0\n"
  1193. "loop.0.0:\n"
  1194. " %cond.0.0 = load volatile i1, i1* %ptr\n"
  1195. " br i1 %cond.0.0, label %loop.0.0, label %loop.0.1.ph\n"
  1196. "loop.0.1.ph:\n"
  1197. " br label %loop.0.1\n"
  1198. "loop.0.1:\n"
  1199. " %cond.0.1 = load volatile i1, i1* %ptr\n"
  1200. " br i1 %cond.0.1, label %loop.0.1, label %loop.0.2.ph\n"
  1201. "loop.0.2.ph:\n"
  1202. " br label %loop.0.2\n"
  1203. "loop.0.2:\n"
  1204. " %cond.0.2 = load volatile i1, i1* %ptr\n"
  1205. " br i1 %cond.0.2, label %loop.0.2.0.ph, label %loop.0.latch\n"
  1206. "loop.0.2.0.ph:\n"
  1207. " br label %loop.0.2.0\n"
  1208. "loop.0.2.0:\n"
  1209. " %cond.0.2.0 = load volatile i1, i1* %ptr\n"
  1210. " br i1 %cond.0.2.0, label %loop.0.2.0, label %loop.0.2.latch\n"
  1211. "loop.0.2.latch:\n"
  1212. " br label %loop.0.2\n"
  1213. "loop.0.latch:\n"
  1214. " br label %loop.0\n"
  1215. "end:\n"
  1216. " ret void\n"
  1217. "}\n");
  1218. // Build up variables referring into the IR so we can rewrite it below
  1219. // easily.
  1220. Function &F = *M->begin();
  1221. ASSERT_THAT(F, HasName("f"));
  1222. Argument &Ptr = *F.arg_begin();
  1223. auto BBI = F.begin();
  1224. BasicBlock &EntryBB = *BBI++;
  1225. ASSERT_THAT(EntryBB, HasName("entry"));
  1226. BasicBlock &Loop0BB = *BBI++;
  1227. ASSERT_THAT(Loop0BB, HasName("loop.0"));
  1228. BasicBlock &Loop00PHBB = *BBI++;
  1229. ASSERT_THAT(Loop00PHBB, HasName("loop.0.0.ph"));
  1230. BasicBlock &Loop00BB = *BBI++;
  1231. ASSERT_THAT(Loop00BB, HasName("loop.0.0"));
  1232. BasicBlock &Loop01PHBB = *BBI++;
  1233. ASSERT_THAT(Loop01PHBB, HasName("loop.0.1.ph"));
  1234. BasicBlock &Loop01BB = *BBI++;
  1235. ASSERT_THAT(Loop01BB, HasName("loop.0.1"));
  1236. BasicBlock &Loop02PHBB = *BBI++;
  1237. ASSERT_THAT(Loop02PHBB, HasName("loop.0.2.ph"));
  1238. BasicBlock &Loop02BB = *BBI++;
  1239. ASSERT_THAT(Loop02BB, HasName("loop.0.2"));
  1240. BasicBlock &Loop020PHBB = *BBI++;
  1241. ASSERT_THAT(Loop020PHBB, HasName("loop.0.2.0.ph"));
  1242. BasicBlock &Loop020BB = *BBI++;
  1243. ASSERT_THAT(Loop020BB, HasName("loop.0.2.0"));
  1244. BasicBlock &Loop02LatchBB = *BBI++;
  1245. ASSERT_THAT(Loop02LatchBB, HasName("loop.0.2.latch"));
  1246. BasicBlock &Loop0LatchBB = *BBI++;
  1247. ASSERT_THAT(Loop0LatchBB, HasName("loop.0.latch"));
  1248. BasicBlock &EndBB = *BBI++;
  1249. ASSERT_THAT(EndBB, HasName("end"));
  1250. ASSERT_THAT(BBI, F.end());
  1251. // Helper to do the actual deletion of a loop. We directly encode this here
  1252. // to isolate ourselves from the rest of LLVM and for simplicity. Here we can
  1253. // egregiously cheat based on knowledge of the test case. For example, we
  1254. // have no PHI nodes and there is always a single i-dom.
  1255. auto EraseLoop = [](Loop &L, BasicBlock &IDomBB,
  1256. LoopStandardAnalysisResults &AR, LPMUpdater &Updater) {
  1257. assert(L.empty() && "Can only delete leaf loops with this routine!");
  1258. SmallVector<BasicBlock *, 4> LoopBBs(L.block_begin(), L.block_end());
  1259. Updater.markLoopAsDeleted(L, L.getName());
  1260. IDomBB.getTerminator()->replaceUsesOfWith(L.getHeader(),
  1261. L.getUniqueExitBlock());
  1262. for (BasicBlock *LoopBB : LoopBBs) {
  1263. SmallVector<DomTreeNode *, 4> ChildNodes(AR.DT[LoopBB]->begin(),
  1264. AR.DT[LoopBB]->end());
  1265. for (DomTreeNode *ChildNode : ChildNodes)
  1266. AR.DT.changeImmediateDominator(ChildNode, AR.DT[&IDomBB]);
  1267. AR.DT.eraseNode(LoopBB);
  1268. AR.LI.removeBlock(LoopBB);
  1269. LoopBB->dropAllReferences();
  1270. }
  1271. for (BasicBlock *LoopBB : LoopBBs)
  1272. LoopBB->eraseFromParent();
  1273. AR.LI.erase(&L);
  1274. };
  1275. // Build up the pass managers.
  1276. ModulePassManager MPM(true);
  1277. FunctionPassManager FPM(true);
  1278. // We run several loop pass pipelines across the loop nest, but they all take
  1279. // the same form of three mock pass runs in a loop pipeline followed by
  1280. // domtree and loop verification. We use a lambda to stamp this out each
  1281. // time.
  1282. auto AddLoopPipelineAndVerificationPasses = [&] {
  1283. LoopPassManager LPM(true);
  1284. LPM.addPass(MLPHandle.getPass());
  1285. LPM.addPass(MLPHandle.getPass());
  1286. LPM.addPass(MLPHandle.getPass());
  1287. FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM)));
  1288. FPM.addPass(DominatorTreeVerifierPass());
  1289. FPM.addPass(LoopVerifierPass());
  1290. };
  1291. // All the visit orders are deterministic so we use simple fully order
  1292. // expectations.
  1293. ::testing::InSequence MakeExpectationsSequenced;
  1294. // We run the loop pipeline with three passes over each of the loops. When
  1295. // running over the middle loop, the second pass in the pipeline deletes it.
  1296. // This should prevent the third pass from visiting it but otherwise leave
  1297. // the process unimpacted.
  1298. AddLoopPipelineAndVerificationPasses();
  1299. EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
  1300. .WillOnce(Invoke(getLoopAnalysisResult));
  1301. EXPECT_CALL(MLAHandle, run(HasName("loop.0.0"), _, _));
  1302. EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
  1303. .Times(2)
  1304. .WillRepeatedly(Invoke(getLoopAnalysisResult));
  1305. EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
  1306. .WillOnce(Invoke(getLoopAnalysisResult));
  1307. EXPECT_CALL(MLAHandle, run(HasName("loop.0.1"), _, _));
  1308. EXPECT_CALL(MLPHandle, run(HasName("loop.0.1"), _, _, _))
  1309. .WillOnce(
  1310. Invoke([&](Loop &L, LoopAnalysisManager &AM,
  1311. LoopStandardAnalysisResults &AR, LPMUpdater &Updater) {
  1312. Loop *ParentL = L.getParentLoop();
  1313. AR.SE.forgetLoop(&L);
  1314. EraseLoop(L, Loop01PHBB, AR, Updater);
  1315. ParentL->verifyLoop();
  1316. return PreservedAnalyses::all();
  1317. }));
  1318. EXPECT_CALL(MLPHandle, run(HasName("loop.0.2.0"), _, _, _))
  1319. .WillOnce(Invoke(getLoopAnalysisResult));
  1320. EXPECT_CALL(MLAHandle, run(HasName("loop.0.2.0"), _, _));
  1321. EXPECT_CALL(MLPHandle, run(HasName("loop.0.2.0"), _, _, _))
  1322. .Times(2)
  1323. .WillRepeatedly(Invoke(getLoopAnalysisResult));
  1324. EXPECT_CALL(MLPHandle, run(HasName("loop.0.2"), _, _, _))
  1325. .WillOnce(Invoke(getLoopAnalysisResult));
  1326. EXPECT_CALL(MLAHandle, run(HasName("loop.0.2"), _, _));
  1327. EXPECT_CALL(MLPHandle, run(HasName("loop.0.2"), _, _, _))
  1328. .Times(2)
  1329. .WillRepeatedly(Invoke(getLoopAnalysisResult));
  1330. EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
  1331. .WillOnce(Invoke(getLoopAnalysisResult));
  1332. EXPECT_CALL(MLAHandle, run(HasName("loop.0"), _, _));
  1333. EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
  1334. .Times(2)
  1335. .WillRepeatedly(Invoke(getLoopAnalysisResult));
  1336. // Run the loop pipeline again. This time we delete the last loop, which
  1337. // contains a nested loop within it and insert a new loop into the nest. This
  1338. // makes sure we can handle nested loop deletion.
  1339. AddLoopPipelineAndVerificationPasses();
  1340. EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
  1341. .Times(3)
  1342. .WillRepeatedly(Invoke(getLoopAnalysisResult));
  1343. EXPECT_CALL(MLPHandle, run(HasName("loop.0.2.0"), _, _, _))
  1344. .Times(3)
  1345. .WillRepeatedly(Invoke(getLoopAnalysisResult));
  1346. EXPECT_CALL(MLPHandle, run(HasName("loop.0.2"), _, _, _))
  1347. .WillOnce(Invoke(getLoopAnalysisResult));
  1348. BasicBlock *NewLoop03PHBB;
  1349. EXPECT_CALL(MLPHandle, run(HasName("loop.0.2"), _, _, _))
  1350. .WillOnce(
  1351. Invoke([&](Loop &L, LoopAnalysisManager &AM,
  1352. LoopStandardAnalysisResults &AR, LPMUpdater &Updater) {
  1353. AR.SE.forgetLoop(*L.begin());
  1354. EraseLoop(**L.begin(), Loop020PHBB, AR, Updater);
  1355. auto *ParentL = L.getParentLoop();
  1356. AR.SE.forgetLoop(&L);
  1357. EraseLoop(L, Loop02PHBB, AR, Updater);
  1358. // Now insert a new sibling loop.
  1359. auto *NewSibling = AR.LI.AllocateLoop();
  1360. ParentL->addChildLoop(NewSibling);
  1361. NewLoop03PHBB =
  1362. BasicBlock::Create(Context, "loop.0.3.ph", &F, &Loop0LatchBB);
  1363. auto *NewLoop03BB =
  1364. BasicBlock::Create(Context, "loop.0.3", &F, &Loop0LatchBB);
  1365. BranchInst::Create(NewLoop03BB, NewLoop03PHBB);
  1366. auto *Cond =
  1367. new LoadInst(Type::getInt1Ty(Context), &Ptr, "cond.0.3",
  1368. /*isVolatile*/ true, NewLoop03BB);
  1369. BranchInst::Create(&Loop0LatchBB, NewLoop03BB, Cond, NewLoop03BB);
  1370. Loop02PHBB.getTerminator()->replaceUsesOfWith(&Loop0LatchBB,
  1371. NewLoop03PHBB);
  1372. AR.DT.addNewBlock(NewLoop03PHBB, &Loop02PHBB);
  1373. AR.DT.addNewBlock(NewLoop03BB, NewLoop03PHBB);
  1374. AR.DT.changeImmediateDominator(AR.DT[&Loop0LatchBB],
  1375. AR.DT[NewLoop03BB]);
  1376. EXPECT_TRUE(AR.DT.verify());
  1377. ParentL->addBasicBlockToLoop(NewLoop03PHBB, AR.LI);
  1378. NewSibling->addBasicBlockToLoop(NewLoop03BB, AR.LI);
  1379. NewSibling->verifyLoop();
  1380. ParentL->verifyLoop();
  1381. Updater.addSiblingLoops({NewSibling});
  1382. return PreservedAnalyses::all();
  1383. }));
  1384. // To respect our inner-to-outer traversal order, we must visit the
  1385. // newly-inserted sibling of the loop we just deleted before we visit the
  1386. // outer loop. When we do so, this must compute a fresh analysis result, even
  1387. // though our new loop has the same pointer value as the loop we deleted.
  1388. EXPECT_CALL(MLPHandle, run(HasName("loop.0.3"), _, _, _))
  1389. .WillOnce(Invoke(getLoopAnalysisResult));
  1390. EXPECT_CALL(MLAHandle, run(HasName("loop.0.3"), _, _));
  1391. EXPECT_CALL(MLPHandle, run(HasName("loop.0.3"), _, _, _))
  1392. .Times(2)
  1393. .WillRepeatedly(Invoke(getLoopAnalysisResult));
  1394. EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
  1395. .Times(3)
  1396. .WillRepeatedly(Invoke(getLoopAnalysisResult));
  1397. // In the final loop pipeline run we delete every loop, including the last
  1398. // loop of the nest. We do this again in the second pass in the pipeline, and
  1399. // as a consequence we never make it to three runs on any loop. We also cover
  1400. // deleting multiple loops in a single pipeline, deleting the first loop and
  1401. // deleting the (last) top level loop.
  1402. AddLoopPipelineAndVerificationPasses();
  1403. EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
  1404. .WillOnce(Invoke(getLoopAnalysisResult));
  1405. EXPECT_CALL(MLPHandle, run(HasName("loop.0.0"), _, _, _))
  1406. .WillOnce(
  1407. Invoke([&](Loop &L, LoopAnalysisManager &AM,
  1408. LoopStandardAnalysisResults &AR, LPMUpdater &Updater) {
  1409. AR.SE.forgetLoop(&L);
  1410. EraseLoop(L, Loop00PHBB, AR, Updater);
  1411. return PreservedAnalyses::all();
  1412. }));
  1413. EXPECT_CALL(MLPHandle, run(HasName("loop.0.3"), _, _, _))
  1414. .WillOnce(Invoke(getLoopAnalysisResult));
  1415. EXPECT_CALL(MLPHandle, run(HasName("loop.0.3"), _, _, _))
  1416. .WillOnce(
  1417. Invoke([&](Loop &L, LoopAnalysisManager &AM,
  1418. LoopStandardAnalysisResults &AR, LPMUpdater &Updater) {
  1419. AR.SE.forgetLoop(&L);
  1420. EraseLoop(L, *NewLoop03PHBB, AR, Updater);
  1421. return PreservedAnalyses::all();
  1422. }));
  1423. EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
  1424. .WillOnce(Invoke(getLoopAnalysisResult));
  1425. EXPECT_CALL(MLPHandle, run(HasName("loop.0"), _, _, _))
  1426. .WillOnce(
  1427. Invoke([&](Loop &L, LoopAnalysisManager &AM,
  1428. LoopStandardAnalysisResults &AR, LPMUpdater &Updater) {
  1429. AR.SE.forgetLoop(&L);
  1430. EraseLoop(L, EntryBB, AR, Updater);
  1431. return PreservedAnalyses::all();
  1432. }));
  1433. // Add the function pass pipeline now that it is fully built up and run it
  1434. // over the module's one function.
  1435. MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
  1436. MPM.run(*M, MAM);
  1437. }
  1438. }