LoopFuse.cpp 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897
  1. //===- LoopFuse.cpp - Loop Fusion 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. /// \file
  10. /// This file implements the loop fusion pass.
  11. /// The implementation is largely based on the following document:
  12. ///
  13. /// Code Transformations to Augment the Scope of Loop Fusion in a
  14. /// Production Compiler
  15. /// Christopher Mark Barton
  16. /// MSc Thesis
  17. /// https://webdocs.cs.ualberta.ca/~amaral/thesis/ChristopherBartonMSc.pdf
  18. ///
  19. /// The general approach taken is to collect sets of control flow equivalent
  20. /// loops and test whether they can be fused. The necessary conditions for
  21. /// fusion are:
  22. /// 1. The loops must be adjacent (there cannot be any statements between
  23. /// the two loops).
  24. /// 2. The loops must be conforming (they must execute the same number of
  25. /// iterations).
  26. /// 3. The loops must be control flow equivalent (if one loop executes, the
  27. /// other is guaranteed to execute).
  28. /// 4. There cannot be any negative distance dependencies between the loops.
  29. /// If all of these conditions are satisfied, it is safe to fuse the loops.
  30. ///
  31. /// This implementation creates FusionCandidates that represent the loop and the
  32. /// necessary information needed by fusion. It then operates on the fusion
  33. /// candidates, first confirming that the candidate is eligible for fusion. The
  34. /// candidates are then collected into control flow equivalent sets, sorted in
  35. /// dominance order. Each set of control flow equivalent candidates is then
  36. /// traversed, attempting to fuse pairs of candidates in the set. If all
  37. /// requirements for fusion are met, the two candidates are fused, creating a
  38. /// new (fused) candidate which is then added back into the set to consider for
  39. /// additional fusion.
  40. ///
  41. /// This implementation currently does not make any modifications to remove
  42. /// conditions for fusion. Code transformations to make loops conform to each of
  43. /// the conditions for fusion are discussed in more detail in the document
  44. /// above. These can be added to the current implementation in the future.
  45. //===----------------------------------------------------------------------===//
  46. #include "llvm/Transforms/Scalar/LoopFuse.h"
  47. #include "llvm/ADT/Statistic.h"
  48. #include "llvm/Analysis/AssumptionCache.h"
  49. #include "llvm/Analysis/DependenceAnalysis.h"
  50. #include "llvm/Analysis/DomTreeUpdater.h"
  51. #include "llvm/Analysis/LoopInfo.h"
  52. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  53. #include "llvm/Analysis/PostDominators.h"
  54. #include "llvm/Analysis/ScalarEvolution.h"
  55. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  56. #include "llvm/Analysis/TargetTransformInfo.h"
  57. #include "llvm/IR/Function.h"
  58. #include "llvm/IR/Verifier.h"
  59. #include "llvm/InitializePasses.h"
  60. #include "llvm/Pass.h"
  61. #include "llvm/Support/CommandLine.h"
  62. #include "llvm/Support/Debug.h"
  63. #include "llvm/Support/raw_ostream.h"
  64. #include "llvm/Transforms/Scalar.h"
  65. #include "llvm/Transforms/Utils.h"
  66. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  67. #include "llvm/Transforms/Utils/CodeMoverUtils.h"
  68. #include "llvm/Transforms/Utils/LoopPeel.h"
  69. using namespace llvm;
  70. #define DEBUG_TYPE "loop-fusion"
  71. STATISTIC(FuseCounter, "Loops fused");
  72. STATISTIC(NumFusionCandidates, "Number of candidates for loop fusion");
  73. STATISTIC(InvalidPreheader, "Loop has invalid preheader");
  74. STATISTIC(InvalidHeader, "Loop has invalid header");
  75. STATISTIC(InvalidExitingBlock, "Loop has invalid exiting blocks");
  76. STATISTIC(InvalidExitBlock, "Loop has invalid exit block");
  77. STATISTIC(InvalidLatch, "Loop has invalid latch");
  78. STATISTIC(InvalidLoop, "Loop is invalid");
  79. STATISTIC(AddressTakenBB, "Basic block has address taken");
  80. STATISTIC(MayThrowException, "Loop may throw an exception");
  81. STATISTIC(ContainsVolatileAccess, "Loop contains a volatile access");
  82. STATISTIC(NotSimplifiedForm, "Loop is not in simplified form");
  83. STATISTIC(InvalidDependencies, "Dependencies prevent fusion");
  84. STATISTIC(UnknownTripCount, "Loop has unknown trip count");
  85. STATISTIC(UncomputableTripCount, "SCEV cannot compute trip count of loop");
  86. STATISTIC(NonEqualTripCount, "Loop trip counts are not the same");
  87. STATISTIC(NonAdjacent, "Loops are not adjacent");
  88. STATISTIC(
  89. NonEmptyPreheader,
  90. "Loop has a non-empty preheader with instructions that cannot be moved");
  91. STATISTIC(FusionNotBeneficial, "Fusion is not beneficial");
  92. STATISTIC(NonIdenticalGuards, "Candidates have different guards");
  93. STATISTIC(NonEmptyExitBlock, "Candidate has a non-empty exit block with "
  94. "instructions that cannot be moved");
  95. STATISTIC(NonEmptyGuardBlock, "Candidate has a non-empty guard block with "
  96. "instructions that cannot be moved");
  97. STATISTIC(NotRotated, "Candidate is not rotated");
  98. STATISTIC(OnlySecondCandidateIsGuarded,
  99. "The second candidate is guarded while the first one is not");
  100. enum FusionDependenceAnalysisChoice {
  101. FUSION_DEPENDENCE_ANALYSIS_SCEV,
  102. FUSION_DEPENDENCE_ANALYSIS_DA,
  103. FUSION_DEPENDENCE_ANALYSIS_ALL,
  104. };
  105. static cl::opt<FusionDependenceAnalysisChoice> FusionDependenceAnalysis(
  106. "loop-fusion-dependence-analysis",
  107. cl::desc("Which dependence analysis should loop fusion use?"),
  108. cl::values(clEnumValN(FUSION_DEPENDENCE_ANALYSIS_SCEV, "scev",
  109. "Use the scalar evolution interface"),
  110. clEnumValN(FUSION_DEPENDENCE_ANALYSIS_DA, "da",
  111. "Use the dependence analysis interface"),
  112. clEnumValN(FUSION_DEPENDENCE_ANALYSIS_ALL, "all",
  113. "Use all available analyses")),
  114. cl::Hidden, cl::init(FUSION_DEPENDENCE_ANALYSIS_ALL), cl::ZeroOrMore);
  115. static cl::opt<unsigned> FusionPeelMaxCount(
  116. "loop-fusion-peel-max-count", cl::init(0), cl::Hidden,
  117. cl::desc("Max number of iterations to be peeled from a loop, such that "
  118. "fusion can take place"));
  119. #ifndef NDEBUG
  120. static cl::opt<bool>
  121. VerboseFusionDebugging("loop-fusion-verbose-debug",
  122. cl::desc("Enable verbose debugging for Loop Fusion"),
  123. cl::Hidden, cl::init(false), cl::ZeroOrMore);
  124. #endif
  125. namespace {
  126. /// This class is used to represent a candidate for loop fusion. When it is
  127. /// constructed, it checks the conditions for loop fusion to ensure that it
  128. /// represents a valid candidate. It caches several parts of a loop that are
  129. /// used throughout loop fusion (e.g., loop preheader, loop header, etc) instead
  130. /// of continually querying the underlying Loop to retrieve these values. It is
  131. /// assumed these will not change throughout loop fusion.
  132. ///
  133. /// The invalidate method should be used to indicate that the FusionCandidate is
  134. /// no longer a valid candidate for fusion. Similarly, the isValid() method can
  135. /// be used to ensure that the FusionCandidate is still valid for fusion.
  136. struct FusionCandidate {
  137. /// Cache of parts of the loop used throughout loop fusion. These should not
  138. /// need to change throughout the analysis and transformation.
  139. /// These parts are cached to avoid repeatedly looking up in the Loop class.
  140. /// Preheader of the loop this candidate represents
  141. BasicBlock *Preheader;
  142. /// Header of the loop this candidate represents
  143. BasicBlock *Header;
  144. /// Blocks in the loop that exit the loop
  145. BasicBlock *ExitingBlock;
  146. /// The successor block of this loop (where the exiting blocks go to)
  147. BasicBlock *ExitBlock;
  148. /// Latch of the loop
  149. BasicBlock *Latch;
  150. /// The loop that this fusion candidate represents
  151. Loop *L;
  152. /// Vector of instructions in this loop that read from memory
  153. SmallVector<Instruction *, 16> MemReads;
  154. /// Vector of instructions in this loop that write to memory
  155. SmallVector<Instruction *, 16> MemWrites;
  156. /// Are all of the members of this fusion candidate still valid
  157. bool Valid;
  158. /// Guard branch of the loop, if it exists
  159. BranchInst *GuardBranch;
  160. /// Peeling Paramaters of the Loop.
  161. TTI::PeelingPreferences PP;
  162. /// Can you Peel this Loop?
  163. bool AbleToPeel;
  164. /// Has this loop been Peeled
  165. bool Peeled;
  166. /// Dominator and PostDominator trees are needed for the
  167. /// FusionCandidateCompare function, required by FusionCandidateSet to
  168. /// determine where the FusionCandidate should be inserted into the set. These
  169. /// are used to establish ordering of the FusionCandidates based on dominance.
  170. const DominatorTree *DT;
  171. const PostDominatorTree *PDT;
  172. OptimizationRemarkEmitter &ORE;
  173. FusionCandidate(Loop *L, const DominatorTree *DT,
  174. const PostDominatorTree *PDT, OptimizationRemarkEmitter &ORE,
  175. TTI::PeelingPreferences PP)
  176. : Preheader(L->getLoopPreheader()), Header(L->getHeader()),
  177. ExitingBlock(L->getExitingBlock()), ExitBlock(L->getExitBlock()),
  178. Latch(L->getLoopLatch()), L(L), Valid(true),
  179. GuardBranch(L->getLoopGuardBranch()), PP(PP), AbleToPeel(canPeel(L)),
  180. Peeled(false), DT(DT), PDT(PDT), ORE(ORE) {
  181. assert(DT && "Expected non-null DT!");
  182. // Walk over all blocks in the loop and check for conditions that may
  183. // prevent fusion. For each block, walk over all instructions and collect
  184. // the memory reads and writes If any instructions that prevent fusion are
  185. // found, invalidate this object and return.
  186. for (BasicBlock *BB : L->blocks()) {
  187. if (BB->hasAddressTaken()) {
  188. invalidate();
  189. reportInvalidCandidate(AddressTakenBB);
  190. return;
  191. }
  192. for (Instruction &I : *BB) {
  193. if (I.mayThrow()) {
  194. invalidate();
  195. reportInvalidCandidate(MayThrowException);
  196. return;
  197. }
  198. if (StoreInst *SI = dyn_cast<StoreInst>(&I)) {
  199. if (SI->isVolatile()) {
  200. invalidate();
  201. reportInvalidCandidate(ContainsVolatileAccess);
  202. return;
  203. }
  204. }
  205. if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
  206. if (LI->isVolatile()) {
  207. invalidate();
  208. reportInvalidCandidate(ContainsVolatileAccess);
  209. return;
  210. }
  211. }
  212. if (I.mayWriteToMemory())
  213. MemWrites.push_back(&I);
  214. if (I.mayReadFromMemory())
  215. MemReads.push_back(&I);
  216. }
  217. }
  218. }
  219. /// Check if all members of the class are valid.
  220. bool isValid() const {
  221. return Preheader && Header && ExitingBlock && ExitBlock && Latch && L &&
  222. !L->isInvalid() && Valid;
  223. }
  224. /// Verify that all members are in sync with the Loop object.
  225. void verify() const {
  226. assert(isValid() && "Candidate is not valid!!");
  227. assert(!L->isInvalid() && "Loop is invalid!");
  228. assert(Preheader == L->getLoopPreheader() && "Preheader is out of sync");
  229. assert(Header == L->getHeader() && "Header is out of sync");
  230. assert(ExitingBlock == L->getExitingBlock() &&
  231. "Exiting Blocks is out of sync");
  232. assert(ExitBlock == L->getExitBlock() && "Exit block is out of sync");
  233. assert(Latch == L->getLoopLatch() && "Latch is out of sync");
  234. }
  235. /// Get the entry block for this fusion candidate.
  236. ///
  237. /// If this fusion candidate represents a guarded loop, the entry block is the
  238. /// loop guard block. If it represents an unguarded loop, the entry block is
  239. /// the preheader of the loop.
  240. BasicBlock *getEntryBlock() const {
  241. if (GuardBranch)
  242. return GuardBranch->getParent();
  243. else
  244. return Preheader;
  245. }
  246. /// After Peeling the loop is modified quite a bit, hence all of the Blocks
  247. /// need to be updated accordingly.
  248. void updateAfterPeeling() {
  249. Preheader = L->getLoopPreheader();
  250. Header = L->getHeader();
  251. ExitingBlock = L->getExitingBlock();
  252. ExitBlock = L->getExitBlock();
  253. Latch = L->getLoopLatch();
  254. verify();
  255. }
  256. /// Given a guarded loop, get the successor of the guard that is not in the
  257. /// loop.
  258. ///
  259. /// This method returns the successor of the loop guard that is not located
  260. /// within the loop (i.e., the successor of the guard that is not the
  261. /// preheader).
  262. /// This method is only valid for guarded loops.
  263. BasicBlock *getNonLoopBlock() const {
  264. assert(GuardBranch && "Only valid on guarded loops.");
  265. assert(GuardBranch->isConditional() &&
  266. "Expecting guard to be a conditional branch.");
  267. if (Peeled)
  268. return GuardBranch->getSuccessor(1);
  269. return (GuardBranch->getSuccessor(0) == Preheader)
  270. ? GuardBranch->getSuccessor(1)
  271. : GuardBranch->getSuccessor(0);
  272. }
  273. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  274. LLVM_DUMP_METHOD void dump() const {
  275. dbgs() << "\tGuardBranch: ";
  276. if (GuardBranch)
  277. dbgs() << *GuardBranch;
  278. else
  279. dbgs() << "nullptr";
  280. dbgs() << "\n"
  281. << (GuardBranch ? GuardBranch->getName() : "nullptr") << "\n"
  282. << "\tPreheader: " << (Preheader ? Preheader->getName() : "nullptr")
  283. << "\n"
  284. << "\tHeader: " << (Header ? Header->getName() : "nullptr") << "\n"
  285. << "\tExitingBB: "
  286. << (ExitingBlock ? ExitingBlock->getName() : "nullptr") << "\n"
  287. << "\tExitBB: " << (ExitBlock ? ExitBlock->getName() : "nullptr")
  288. << "\n"
  289. << "\tLatch: " << (Latch ? Latch->getName() : "nullptr") << "\n"
  290. << "\tEntryBlock: "
  291. << (getEntryBlock() ? getEntryBlock()->getName() : "nullptr")
  292. << "\n";
  293. }
  294. #endif
  295. /// Determine if a fusion candidate (representing a loop) is eligible for
  296. /// fusion. Note that this only checks whether a single loop can be fused - it
  297. /// does not check whether it is *legal* to fuse two loops together.
  298. bool isEligibleForFusion(ScalarEvolution &SE) const {
  299. if (!isValid()) {
  300. LLVM_DEBUG(dbgs() << "FC has invalid CFG requirements!\n");
  301. if (!Preheader)
  302. ++InvalidPreheader;
  303. if (!Header)
  304. ++InvalidHeader;
  305. if (!ExitingBlock)
  306. ++InvalidExitingBlock;
  307. if (!ExitBlock)
  308. ++InvalidExitBlock;
  309. if (!Latch)
  310. ++InvalidLatch;
  311. if (L->isInvalid())
  312. ++InvalidLoop;
  313. return false;
  314. }
  315. // Require ScalarEvolution to be able to determine a trip count.
  316. if (!SE.hasLoopInvariantBackedgeTakenCount(L)) {
  317. LLVM_DEBUG(dbgs() << "Loop " << L->getName()
  318. << " trip count not computable!\n");
  319. return reportInvalidCandidate(UnknownTripCount);
  320. }
  321. if (!L->isLoopSimplifyForm()) {
  322. LLVM_DEBUG(dbgs() << "Loop " << L->getName()
  323. << " is not in simplified form!\n");
  324. return reportInvalidCandidate(NotSimplifiedForm);
  325. }
  326. if (!L->isRotatedForm()) {
  327. LLVM_DEBUG(dbgs() << "Loop " << L->getName() << " is not rotated!\n");
  328. return reportInvalidCandidate(NotRotated);
  329. }
  330. return true;
  331. }
  332. private:
  333. // This is only used internally for now, to clear the MemWrites and MemReads
  334. // list and setting Valid to false. I can't envision other uses of this right
  335. // now, since once FusionCandidates are put into the FusionCandidateSet they
  336. // are immutable. Thus, any time we need to change/update a FusionCandidate,
  337. // we must create a new one and insert it into the FusionCandidateSet to
  338. // ensure the FusionCandidateSet remains ordered correctly.
  339. void invalidate() {
  340. MemWrites.clear();
  341. MemReads.clear();
  342. Valid = false;
  343. }
  344. bool reportInvalidCandidate(llvm::Statistic &Stat) const {
  345. using namespace ore;
  346. assert(L && Preheader && "Fusion candidate not initialized properly!");
  347. #if LLVM_ENABLE_STATS
  348. ++Stat;
  349. ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, Stat.getName(),
  350. L->getStartLoc(), Preheader)
  351. << "[" << Preheader->getParent()->getName() << "]: "
  352. << "Loop is not a candidate for fusion: " << Stat.getDesc());
  353. #endif
  354. return false;
  355. }
  356. };
  357. struct FusionCandidateCompare {
  358. /// Comparison functor to sort two Control Flow Equivalent fusion candidates
  359. /// into dominance order.
  360. /// If LHS dominates RHS and RHS post-dominates LHS, return true;
  361. /// IF RHS dominates LHS and LHS post-dominates RHS, return false;
  362. bool operator()(const FusionCandidate &LHS,
  363. const FusionCandidate &RHS) const {
  364. const DominatorTree *DT = LHS.DT;
  365. BasicBlock *LHSEntryBlock = LHS.getEntryBlock();
  366. BasicBlock *RHSEntryBlock = RHS.getEntryBlock();
  367. // Do not save PDT to local variable as it is only used in asserts and thus
  368. // will trigger an unused variable warning if building without asserts.
  369. assert(DT && LHS.PDT && "Expecting valid dominator tree");
  370. // Do this compare first so if LHS == RHS, function returns false.
  371. if (DT->dominates(RHSEntryBlock, LHSEntryBlock)) {
  372. // RHS dominates LHS
  373. // Verify LHS post-dominates RHS
  374. assert(LHS.PDT->dominates(LHSEntryBlock, RHSEntryBlock));
  375. return false;
  376. }
  377. if (DT->dominates(LHSEntryBlock, RHSEntryBlock)) {
  378. // Verify RHS Postdominates LHS
  379. assert(LHS.PDT->dominates(RHSEntryBlock, LHSEntryBlock));
  380. return true;
  381. }
  382. // If LHS does not dominate RHS and RHS does not dominate LHS then there is
  383. // no dominance relationship between the two FusionCandidates. Thus, they
  384. // should not be in the same set together.
  385. llvm_unreachable(
  386. "No dominance relationship between these fusion candidates!");
  387. }
  388. };
  389. using LoopVector = SmallVector<Loop *, 4>;
  390. // Set of Control Flow Equivalent (CFE) Fusion Candidates, sorted in dominance
  391. // order. Thus, if FC0 comes *before* FC1 in a FusionCandidateSet, then FC0
  392. // dominates FC1 and FC1 post-dominates FC0.
  393. // std::set was chosen because we want a sorted data structure with stable
  394. // iterators. A subsequent patch to loop fusion will enable fusing non-ajdacent
  395. // loops by moving intervening code around. When this intervening code contains
  396. // loops, those loops will be moved also. The corresponding FusionCandidates
  397. // will also need to be moved accordingly. As this is done, having stable
  398. // iterators will simplify the logic. Similarly, having an efficient insert that
  399. // keeps the FusionCandidateSet sorted will also simplify the implementation.
  400. using FusionCandidateSet = std::set<FusionCandidate, FusionCandidateCompare>;
  401. using FusionCandidateCollection = SmallVector<FusionCandidateSet, 4>;
  402. #if !defined(NDEBUG)
  403. static llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
  404. const FusionCandidate &FC) {
  405. if (FC.isValid())
  406. OS << FC.Preheader->getName();
  407. else
  408. OS << "<Invalid>";
  409. return OS;
  410. }
  411. static llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
  412. const FusionCandidateSet &CandSet) {
  413. for (const FusionCandidate &FC : CandSet)
  414. OS << FC << '\n';
  415. return OS;
  416. }
  417. static void
  418. printFusionCandidates(const FusionCandidateCollection &FusionCandidates) {
  419. dbgs() << "Fusion Candidates: \n";
  420. for (const auto &CandidateSet : FusionCandidates) {
  421. dbgs() << "*** Fusion Candidate Set ***\n";
  422. dbgs() << CandidateSet;
  423. dbgs() << "****************************\n";
  424. }
  425. }
  426. #endif
  427. /// Collect all loops in function at the same nest level, starting at the
  428. /// outermost level.
  429. ///
  430. /// This data structure collects all loops at the same nest level for a
  431. /// given function (specified by the LoopInfo object). It starts at the
  432. /// outermost level.
  433. struct LoopDepthTree {
  434. using LoopsOnLevelTy = SmallVector<LoopVector, 4>;
  435. using iterator = LoopsOnLevelTy::iterator;
  436. using const_iterator = LoopsOnLevelTy::const_iterator;
  437. LoopDepthTree(LoopInfo &LI) : Depth(1) {
  438. if (!LI.empty())
  439. LoopsOnLevel.emplace_back(LoopVector(LI.rbegin(), LI.rend()));
  440. }
  441. /// Test whether a given loop has been removed from the function, and thus is
  442. /// no longer valid.
  443. bool isRemovedLoop(const Loop *L) const { return RemovedLoops.count(L); }
  444. /// Record that a given loop has been removed from the function and is no
  445. /// longer valid.
  446. void removeLoop(const Loop *L) { RemovedLoops.insert(L); }
  447. /// Descend the tree to the next (inner) nesting level
  448. void descend() {
  449. LoopsOnLevelTy LoopsOnNextLevel;
  450. for (const LoopVector &LV : *this)
  451. for (Loop *L : LV)
  452. if (!isRemovedLoop(L) && L->begin() != L->end())
  453. LoopsOnNextLevel.emplace_back(LoopVector(L->begin(), L->end()));
  454. LoopsOnLevel = LoopsOnNextLevel;
  455. RemovedLoops.clear();
  456. Depth++;
  457. }
  458. bool empty() const { return size() == 0; }
  459. size_t size() const { return LoopsOnLevel.size() - RemovedLoops.size(); }
  460. unsigned getDepth() const { return Depth; }
  461. iterator begin() { return LoopsOnLevel.begin(); }
  462. iterator end() { return LoopsOnLevel.end(); }
  463. const_iterator begin() const { return LoopsOnLevel.begin(); }
  464. const_iterator end() const { return LoopsOnLevel.end(); }
  465. private:
  466. /// Set of loops that have been removed from the function and are no longer
  467. /// valid.
  468. SmallPtrSet<const Loop *, 8> RemovedLoops;
  469. /// Depth of the current level, starting at 1 (outermost loops).
  470. unsigned Depth;
  471. /// Vector of loops at the current depth level that have the same parent loop
  472. LoopsOnLevelTy LoopsOnLevel;
  473. };
  474. #ifndef NDEBUG
  475. static void printLoopVector(const LoopVector &LV) {
  476. dbgs() << "****************************\n";
  477. for (auto L : LV)
  478. printLoop(*L, dbgs());
  479. dbgs() << "****************************\n";
  480. }
  481. #endif
  482. struct LoopFuser {
  483. private:
  484. // Sets of control flow equivalent fusion candidates for a given nest level.
  485. FusionCandidateCollection FusionCandidates;
  486. LoopDepthTree LDT;
  487. DomTreeUpdater DTU;
  488. LoopInfo &LI;
  489. DominatorTree &DT;
  490. DependenceInfo &DI;
  491. ScalarEvolution &SE;
  492. PostDominatorTree &PDT;
  493. OptimizationRemarkEmitter &ORE;
  494. AssumptionCache &AC;
  495. const TargetTransformInfo &TTI;
  496. public:
  497. LoopFuser(LoopInfo &LI, DominatorTree &DT, DependenceInfo &DI,
  498. ScalarEvolution &SE, PostDominatorTree &PDT,
  499. OptimizationRemarkEmitter &ORE, const DataLayout &DL,
  500. AssumptionCache &AC, const TargetTransformInfo &TTI)
  501. : LDT(LI), DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy), LI(LI),
  502. DT(DT), DI(DI), SE(SE), PDT(PDT), ORE(ORE), AC(AC), TTI(TTI) {}
  503. /// This is the main entry point for loop fusion. It will traverse the
  504. /// specified function and collect candidate loops to fuse, starting at the
  505. /// outermost nesting level and working inwards.
  506. bool fuseLoops(Function &F) {
  507. #ifndef NDEBUG
  508. if (VerboseFusionDebugging) {
  509. LI.print(dbgs());
  510. }
  511. #endif
  512. LLVM_DEBUG(dbgs() << "Performing Loop Fusion on function " << F.getName()
  513. << "\n");
  514. bool Changed = false;
  515. while (!LDT.empty()) {
  516. LLVM_DEBUG(dbgs() << "Got " << LDT.size() << " loop sets for depth "
  517. << LDT.getDepth() << "\n";);
  518. for (const LoopVector &LV : LDT) {
  519. assert(LV.size() > 0 && "Empty loop set was build!");
  520. // Skip singleton loop sets as they do not offer fusion opportunities on
  521. // this level.
  522. if (LV.size() == 1)
  523. continue;
  524. #ifndef NDEBUG
  525. if (VerboseFusionDebugging) {
  526. LLVM_DEBUG({
  527. dbgs() << " Visit loop set (#" << LV.size() << "):\n";
  528. printLoopVector(LV);
  529. });
  530. }
  531. #endif
  532. collectFusionCandidates(LV);
  533. Changed |= fuseCandidates();
  534. }
  535. // Finished analyzing candidates at this level.
  536. // Descend to the next level and clear all of the candidates currently
  537. // collected. Note that it will not be possible to fuse any of the
  538. // existing candidates with new candidates because the new candidates will
  539. // be at a different nest level and thus not be control flow equivalent
  540. // with all of the candidates collected so far.
  541. LLVM_DEBUG(dbgs() << "Descend one level!\n");
  542. LDT.descend();
  543. FusionCandidates.clear();
  544. }
  545. if (Changed)
  546. LLVM_DEBUG(dbgs() << "Function after Loop Fusion: \n"; F.dump(););
  547. #ifndef NDEBUG
  548. assert(DT.verify());
  549. assert(PDT.verify());
  550. LI.verify(DT);
  551. SE.verify();
  552. #endif
  553. LLVM_DEBUG(dbgs() << "Loop Fusion complete\n");
  554. return Changed;
  555. }
  556. private:
  557. /// Determine if two fusion candidates are control flow equivalent.
  558. ///
  559. /// Two fusion candidates are control flow equivalent if when one executes,
  560. /// the other is guaranteed to execute. This is determined using dominators
  561. /// and post-dominators: if A dominates B and B post-dominates A then A and B
  562. /// are control-flow equivalent.
  563. bool isControlFlowEquivalent(const FusionCandidate &FC0,
  564. const FusionCandidate &FC1) const {
  565. assert(FC0.Preheader && FC1.Preheader && "Expecting valid preheaders");
  566. return ::isControlFlowEquivalent(*FC0.getEntryBlock(), *FC1.getEntryBlock(),
  567. DT, PDT);
  568. }
  569. /// Iterate over all loops in the given loop set and identify the loops that
  570. /// are eligible for fusion. Place all eligible fusion candidates into Control
  571. /// Flow Equivalent sets, sorted by dominance.
  572. void collectFusionCandidates(const LoopVector &LV) {
  573. for (Loop *L : LV) {
  574. TTI::PeelingPreferences PP =
  575. gatherPeelingPreferences(L, SE, TTI, None, None);
  576. FusionCandidate CurrCand(L, &DT, &PDT, ORE, PP);
  577. if (!CurrCand.isEligibleForFusion(SE))
  578. continue;
  579. // Go through each list in FusionCandidates and determine if L is control
  580. // flow equivalent with the first loop in that list. If it is, append LV.
  581. // If not, go to the next list.
  582. // If no suitable list is found, start another list and add it to
  583. // FusionCandidates.
  584. bool FoundSet = false;
  585. for (auto &CurrCandSet : FusionCandidates) {
  586. if (isControlFlowEquivalent(*CurrCandSet.begin(), CurrCand)) {
  587. CurrCandSet.insert(CurrCand);
  588. FoundSet = true;
  589. #ifndef NDEBUG
  590. if (VerboseFusionDebugging)
  591. LLVM_DEBUG(dbgs() << "Adding " << CurrCand
  592. << " to existing candidate set\n");
  593. #endif
  594. break;
  595. }
  596. }
  597. if (!FoundSet) {
  598. // No set was found. Create a new set and add to FusionCandidates
  599. #ifndef NDEBUG
  600. if (VerboseFusionDebugging)
  601. LLVM_DEBUG(dbgs() << "Adding " << CurrCand << " to new set\n");
  602. #endif
  603. FusionCandidateSet NewCandSet;
  604. NewCandSet.insert(CurrCand);
  605. FusionCandidates.push_back(NewCandSet);
  606. }
  607. NumFusionCandidates++;
  608. }
  609. }
  610. /// Determine if it is beneficial to fuse two loops.
  611. ///
  612. /// For now, this method simply returns true because we want to fuse as much
  613. /// as possible (primarily to test the pass). This method will evolve, over
  614. /// time, to add heuristics for profitability of fusion.
  615. bool isBeneficialFusion(const FusionCandidate &FC0,
  616. const FusionCandidate &FC1) {
  617. return true;
  618. }
  619. /// Determine if two fusion candidates have the same trip count (i.e., they
  620. /// execute the same number of iterations).
  621. ///
  622. /// This function will return a pair of values. The first is a boolean,
  623. /// stating whether or not the two candidates are known at compile time to
  624. /// have the same TripCount. The second is the difference in the two
  625. /// TripCounts. This information can be used later to determine whether or not
  626. /// peeling can be performed on either one of the candiates.
  627. std::pair<bool, Optional<unsigned>>
  628. haveIdenticalTripCounts(const FusionCandidate &FC0,
  629. const FusionCandidate &FC1) const {
  630. const SCEV *TripCount0 = SE.getBackedgeTakenCount(FC0.L);
  631. if (isa<SCEVCouldNotCompute>(TripCount0)) {
  632. UncomputableTripCount++;
  633. LLVM_DEBUG(dbgs() << "Trip count of first loop could not be computed!");
  634. return {false, None};
  635. }
  636. const SCEV *TripCount1 = SE.getBackedgeTakenCount(FC1.L);
  637. if (isa<SCEVCouldNotCompute>(TripCount1)) {
  638. UncomputableTripCount++;
  639. LLVM_DEBUG(dbgs() << "Trip count of second loop could not be computed!");
  640. return {false, None};
  641. }
  642. LLVM_DEBUG(dbgs() << "\tTrip counts: " << *TripCount0 << " & "
  643. << *TripCount1 << " are "
  644. << (TripCount0 == TripCount1 ? "identical" : "different")
  645. << "\n");
  646. if (TripCount0 == TripCount1)
  647. return {true, 0};
  648. LLVM_DEBUG(dbgs() << "The loops do not have the same tripcount, "
  649. "determining the difference between trip counts\n");
  650. // Currently only considering loops with a single exit point
  651. // and a non-constant trip count.
  652. const unsigned TC0 = SE.getSmallConstantTripCount(FC0.L);
  653. const unsigned TC1 = SE.getSmallConstantTripCount(FC1.L);
  654. // If any of the tripcounts are zero that means that loop(s) do not have
  655. // a single exit or a constant tripcount.
  656. if (TC0 == 0 || TC1 == 0) {
  657. LLVM_DEBUG(dbgs() << "Loop(s) do not have a single exit point or do not "
  658. "have a constant number of iterations. Peeling "
  659. "is not benefical\n");
  660. return {false, None};
  661. }
  662. Optional<unsigned> Difference = None;
  663. int Diff = TC0 - TC1;
  664. if (Diff > 0)
  665. Difference = Diff;
  666. else {
  667. LLVM_DEBUG(
  668. dbgs() << "Difference is less than 0. FC1 (second loop) has more "
  669. "iterations than the first one. Currently not supported\n");
  670. }
  671. LLVM_DEBUG(dbgs() << "Difference in loop trip count is: " << Difference
  672. << "\n");
  673. return {false, Difference};
  674. }
  675. void peelFusionCandidate(FusionCandidate &FC0, const FusionCandidate &FC1,
  676. unsigned PeelCount) {
  677. assert(FC0.AbleToPeel && "Should be able to peel loop");
  678. LLVM_DEBUG(dbgs() << "Attempting to peel first " << PeelCount
  679. << " iterations of the first loop. \n");
  680. FC0.Peeled = peelLoop(FC0.L, PeelCount, &LI, &SE, DT, &AC, true);
  681. if (FC0.Peeled) {
  682. LLVM_DEBUG(dbgs() << "Done Peeling\n");
  683. #ifndef NDEBUG
  684. auto IdenticalTripCount = haveIdenticalTripCounts(FC0, FC1);
  685. assert(IdenticalTripCount.first && *IdenticalTripCount.second == 0 &&
  686. "Loops should have identical trip counts after peeling");
  687. #endif
  688. FC0.PP.PeelCount += PeelCount;
  689. // Peeling does not update the PDT
  690. PDT.recalculate(*FC0.Preheader->getParent());
  691. FC0.updateAfterPeeling();
  692. // In this case the iterations of the loop are constant, so the first
  693. // loop will execute completely (will not jump from one of
  694. // the peeled blocks to the second loop). Here we are updating the
  695. // branch conditions of each of the peeled blocks, such that it will
  696. // branch to its successor which is not the preheader of the second loop
  697. // in the case of unguarded loops, or the succesors of the exit block of
  698. // the first loop otherwise. Doing this update will ensure that the entry
  699. // block of the first loop dominates the entry block of the second loop.
  700. BasicBlock *BB =
  701. FC0.GuardBranch ? FC0.ExitBlock->getUniqueSuccessor() : FC1.Preheader;
  702. if (BB) {
  703. SmallVector<DominatorTree::UpdateType, 8> TreeUpdates;
  704. SmallVector<Instruction *, 8> WorkList;
  705. for (BasicBlock *Pred : predecessors(BB)) {
  706. if (Pred != FC0.ExitBlock) {
  707. WorkList.emplace_back(Pred->getTerminator());
  708. TreeUpdates.emplace_back(
  709. DominatorTree::UpdateType(DominatorTree::Delete, Pred, BB));
  710. }
  711. }
  712. // Cannot modify the predecessors inside the above loop as it will cause
  713. // the iterators to be nullptrs, causing memory errors.
  714. for (Instruction *CurrentBranch: WorkList) {
  715. BasicBlock *Succ = CurrentBranch->getSuccessor(0);
  716. if (Succ == BB)
  717. Succ = CurrentBranch->getSuccessor(1);
  718. ReplaceInstWithInst(CurrentBranch, BranchInst::Create(Succ));
  719. }
  720. DTU.applyUpdates(TreeUpdates);
  721. DTU.flush();
  722. }
  723. LLVM_DEBUG(
  724. dbgs() << "Sucessfully peeled " << FC0.PP.PeelCount
  725. << " iterations from the first loop.\n"
  726. "Both Loops have the same number of iterations now.\n");
  727. }
  728. }
  729. /// Walk each set of control flow equivalent fusion candidates and attempt to
  730. /// fuse them. This does a single linear traversal of all candidates in the
  731. /// set. The conditions for legal fusion are checked at this point. If a pair
  732. /// of fusion candidates passes all legality checks, they are fused together
  733. /// and a new fusion candidate is created and added to the FusionCandidateSet.
  734. /// The original fusion candidates are then removed, as they are no longer
  735. /// valid.
  736. bool fuseCandidates() {
  737. bool Fused = false;
  738. LLVM_DEBUG(printFusionCandidates(FusionCandidates));
  739. for (auto &CandidateSet : FusionCandidates) {
  740. if (CandidateSet.size() < 2)
  741. continue;
  742. LLVM_DEBUG(dbgs() << "Attempting fusion on Candidate Set:\n"
  743. << CandidateSet << "\n");
  744. for (auto FC0 = CandidateSet.begin(); FC0 != CandidateSet.end(); ++FC0) {
  745. assert(!LDT.isRemovedLoop(FC0->L) &&
  746. "Should not have removed loops in CandidateSet!");
  747. auto FC1 = FC0;
  748. for (++FC1; FC1 != CandidateSet.end(); ++FC1) {
  749. assert(!LDT.isRemovedLoop(FC1->L) &&
  750. "Should not have removed loops in CandidateSet!");
  751. LLVM_DEBUG(dbgs() << "Attempting to fuse candidate \n"; FC0->dump();
  752. dbgs() << " with\n"; FC1->dump(); dbgs() << "\n");
  753. FC0->verify();
  754. FC1->verify();
  755. // Check if the candidates have identical tripcounts (first value of
  756. // pair), and if not check the difference in the tripcounts between
  757. // the loops (second value of pair). The difference is not equal to
  758. // None iff the loops iterate a constant number of times, and have a
  759. // single exit.
  760. std::pair<bool, Optional<unsigned>> IdenticalTripCountRes =
  761. haveIdenticalTripCounts(*FC0, *FC1);
  762. bool SameTripCount = IdenticalTripCountRes.first;
  763. Optional<unsigned> TCDifference = IdenticalTripCountRes.second;
  764. // Here we are checking that FC0 (the first loop) can be peeled, and
  765. // both loops have different tripcounts.
  766. if (FC0->AbleToPeel && !SameTripCount && TCDifference) {
  767. if (*TCDifference > FusionPeelMaxCount) {
  768. LLVM_DEBUG(dbgs()
  769. << "Difference in loop trip counts: " << *TCDifference
  770. << " is greater than maximum peel count specificed: "
  771. << FusionPeelMaxCount << "\n");
  772. } else {
  773. // Dependent on peeling being performed on the first loop, and
  774. // assuming all other conditions for fusion return true.
  775. SameTripCount = true;
  776. }
  777. }
  778. if (!SameTripCount) {
  779. LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical trip "
  780. "counts. Not fusing.\n");
  781. reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
  782. NonEqualTripCount);
  783. continue;
  784. }
  785. if (!isAdjacent(*FC0, *FC1)) {
  786. LLVM_DEBUG(dbgs()
  787. << "Fusion candidates are not adjacent. Not fusing.\n");
  788. reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1, NonAdjacent);
  789. continue;
  790. }
  791. if (!FC0->GuardBranch && FC1->GuardBranch) {
  792. LLVM_DEBUG(dbgs() << "The second candidate is guarded while the "
  793. "first one is not. Not fusing.\n");
  794. reportLoopFusion<OptimizationRemarkMissed>(
  795. *FC0, *FC1, OnlySecondCandidateIsGuarded);
  796. continue;
  797. }
  798. // Ensure that FC0 and FC1 have identical guards.
  799. // If one (or both) are not guarded, this check is not necessary.
  800. if (FC0->GuardBranch && FC1->GuardBranch &&
  801. !haveIdenticalGuards(*FC0, *FC1) && !TCDifference) {
  802. LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical "
  803. "guards. Not Fusing.\n");
  804. reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
  805. NonIdenticalGuards);
  806. continue;
  807. }
  808. if (!isSafeToMoveBefore(*FC1->Preheader,
  809. *FC0->Preheader->getTerminator(), DT, &PDT,
  810. &DI)) {
  811. LLVM_DEBUG(dbgs() << "Fusion candidate contains unsafe "
  812. "instructions in preheader. Not fusing.\n");
  813. reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
  814. NonEmptyPreheader);
  815. continue;
  816. }
  817. if (FC0->GuardBranch) {
  818. assert(FC1->GuardBranch && "Expecting valid FC1 guard branch");
  819. if (!isSafeToMoveBefore(*FC0->ExitBlock,
  820. *FC1->ExitBlock->getFirstNonPHIOrDbg(), DT,
  821. &PDT, &DI)) {
  822. LLVM_DEBUG(dbgs() << "Fusion candidate contains unsafe "
  823. "instructions in exit block. Not fusing.\n");
  824. reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
  825. NonEmptyExitBlock);
  826. continue;
  827. }
  828. if (!isSafeToMoveBefore(
  829. *FC1->GuardBranch->getParent(),
  830. *FC0->GuardBranch->getParent()->getTerminator(), DT, &PDT,
  831. &DI)) {
  832. LLVM_DEBUG(dbgs()
  833. << "Fusion candidate contains unsafe "
  834. "instructions in guard block. Not fusing.\n");
  835. reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
  836. NonEmptyGuardBlock);
  837. continue;
  838. }
  839. }
  840. // Check the dependencies across the loops and do not fuse if it would
  841. // violate them.
  842. if (!dependencesAllowFusion(*FC0, *FC1)) {
  843. LLVM_DEBUG(dbgs() << "Memory dependencies do not allow fusion!\n");
  844. reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
  845. InvalidDependencies);
  846. continue;
  847. }
  848. bool BeneficialToFuse = isBeneficialFusion(*FC0, *FC1);
  849. LLVM_DEBUG(dbgs()
  850. << "\tFusion appears to be "
  851. << (BeneficialToFuse ? "" : "un") << "profitable!\n");
  852. if (!BeneficialToFuse) {
  853. reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1,
  854. FusionNotBeneficial);
  855. continue;
  856. }
  857. // All analysis has completed and has determined that fusion is legal
  858. // and profitable. At this point, start transforming the code and
  859. // perform fusion.
  860. LLVM_DEBUG(dbgs() << "\tFusion is performed: " << *FC0 << " and "
  861. << *FC1 << "\n");
  862. FusionCandidate FC0Copy = *FC0;
  863. // Peel the loop after determining that fusion is legal. The Loops
  864. // will still be safe to fuse after the peeling is performed.
  865. bool Peel = TCDifference && *TCDifference > 0;
  866. if (Peel)
  867. peelFusionCandidate(FC0Copy, *FC1, *TCDifference);
  868. // Report fusion to the Optimization Remarks.
  869. // Note this needs to be done *before* performFusion because
  870. // performFusion will change the original loops, making it not
  871. // possible to identify them after fusion is complete.
  872. reportLoopFusion<OptimizationRemark>((Peel ? FC0Copy : *FC0), *FC1,
  873. FuseCounter);
  874. FusionCandidate FusedCand(
  875. performFusion((Peel ? FC0Copy : *FC0), *FC1), &DT, &PDT, ORE,
  876. FC0Copy.PP);
  877. FusedCand.verify();
  878. assert(FusedCand.isEligibleForFusion(SE) &&
  879. "Fused candidate should be eligible for fusion!");
  880. // Notify the loop-depth-tree that these loops are not valid objects
  881. LDT.removeLoop(FC1->L);
  882. CandidateSet.erase(FC0);
  883. CandidateSet.erase(FC1);
  884. auto InsertPos = CandidateSet.insert(FusedCand);
  885. assert(InsertPos.second &&
  886. "Unable to insert TargetCandidate in CandidateSet!");
  887. // Reset FC0 and FC1 the new (fused) candidate. Subsequent iterations
  888. // of the FC1 loop will attempt to fuse the new (fused) loop with the
  889. // remaining candidates in the current candidate set.
  890. FC0 = FC1 = InsertPos.first;
  891. LLVM_DEBUG(dbgs() << "Candidate Set (after fusion): " << CandidateSet
  892. << "\n");
  893. Fused = true;
  894. }
  895. }
  896. }
  897. return Fused;
  898. }
  899. /// Rewrite all additive recurrences in a SCEV to use a new loop.
  900. class AddRecLoopReplacer : public SCEVRewriteVisitor<AddRecLoopReplacer> {
  901. public:
  902. AddRecLoopReplacer(ScalarEvolution &SE, const Loop &OldL, const Loop &NewL,
  903. bool UseMax = true)
  904. : SCEVRewriteVisitor(SE), Valid(true), UseMax(UseMax), OldL(OldL),
  905. NewL(NewL) {}
  906. const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
  907. const Loop *ExprL = Expr->getLoop();
  908. SmallVector<const SCEV *, 2> Operands;
  909. if (ExprL == &OldL) {
  910. Operands.append(Expr->op_begin(), Expr->op_end());
  911. return SE.getAddRecExpr(Operands, &NewL, Expr->getNoWrapFlags());
  912. }
  913. if (OldL.contains(ExprL)) {
  914. bool Pos = SE.isKnownPositive(Expr->getStepRecurrence(SE));
  915. if (!UseMax || !Pos || !Expr->isAffine()) {
  916. Valid = false;
  917. return Expr;
  918. }
  919. return visit(Expr->getStart());
  920. }
  921. for (const SCEV *Op : Expr->operands())
  922. Operands.push_back(visit(Op));
  923. return SE.getAddRecExpr(Operands, ExprL, Expr->getNoWrapFlags());
  924. }
  925. bool wasValidSCEV() const { return Valid; }
  926. private:
  927. bool Valid, UseMax;
  928. const Loop &OldL, &NewL;
  929. };
  930. /// Return false if the access functions of \p I0 and \p I1 could cause
  931. /// a negative dependence.
  932. bool accessDiffIsPositive(const Loop &L0, const Loop &L1, Instruction &I0,
  933. Instruction &I1, bool EqualIsInvalid) {
  934. Value *Ptr0 = getLoadStorePointerOperand(&I0);
  935. Value *Ptr1 = getLoadStorePointerOperand(&I1);
  936. if (!Ptr0 || !Ptr1)
  937. return false;
  938. const SCEV *SCEVPtr0 = SE.getSCEVAtScope(Ptr0, &L0);
  939. const SCEV *SCEVPtr1 = SE.getSCEVAtScope(Ptr1, &L1);
  940. #ifndef NDEBUG
  941. if (VerboseFusionDebugging)
  942. LLVM_DEBUG(dbgs() << " Access function check: " << *SCEVPtr0 << " vs "
  943. << *SCEVPtr1 << "\n");
  944. #endif
  945. AddRecLoopReplacer Rewriter(SE, L0, L1);
  946. SCEVPtr0 = Rewriter.visit(SCEVPtr0);
  947. #ifndef NDEBUG
  948. if (VerboseFusionDebugging)
  949. LLVM_DEBUG(dbgs() << " Access function after rewrite: " << *SCEVPtr0
  950. << " [Valid: " << Rewriter.wasValidSCEV() << "]\n");
  951. #endif
  952. if (!Rewriter.wasValidSCEV())
  953. return false;
  954. // TODO: isKnownPredicate doesnt work well when one SCEV is loop carried (by
  955. // L0) and the other is not. We could check if it is monotone and test
  956. // the beginning and end value instead.
  957. BasicBlock *L0Header = L0.getHeader();
  958. auto HasNonLinearDominanceRelation = [&](const SCEV *S) {
  959. const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S);
  960. if (!AddRec)
  961. return false;
  962. return !DT.dominates(L0Header, AddRec->getLoop()->getHeader()) &&
  963. !DT.dominates(AddRec->getLoop()->getHeader(), L0Header);
  964. };
  965. if (SCEVExprContains(SCEVPtr1, HasNonLinearDominanceRelation))
  966. return false;
  967. ICmpInst::Predicate Pred =
  968. EqualIsInvalid ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_SGE;
  969. bool IsAlwaysGE = SE.isKnownPredicate(Pred, SCEVPtr0, SCEVPtr1);
  970. #ifndef NDEBUG
  971. if (VerboseFusionDebugging)
  972. LLVM_DEBUG(dbgs() << " Relation: " << *SCEVPtr0
  973. << (IsAlwaysGE ? " >= " : " may < ") << *SCEVPtr1
  974. << "\n");
  975. #endif
  976. return IsAlwaysGE;
  977. }
  978. /// Return true if the dependences between @p I0 (in @p L0) and @p I1 (in
  979. /// @p L1) allow loop fusion of @p L0 and @p L1. The dependence analyses
  980. /// specified by @p DepChoice are used to determine this.
  981. bool dependencesAllowFusion(const FusionCandidate &FC0,
  982. const FusionCandidate &FC1, Instruction &I0,
  983. Instruction &I1, bool AnyDep,
  984. FusionDependenceAnalysisChoice DepChoice) {
  985. #ifndef NDEBUG
  986. if (VerboseFusionDebugging) {
  987. LLVM_DEBUG(dbgs() << "Check dep: " << I0 << " vs " << I1 << " : "
  988. << DepChoice << "\n");
  989. }
  990. #endif
  991. switch (DepChoice) {
  992. case FUSION_DEPENDENCE_ANALYSIS_SCEV:
  993. return accessDiffIsPositive(*FC0.L, *FC1.L, I0, I1, AnyDep);
  994. case FUSION_DEPENDENCE_ANALYSIS_DA: {
  995. auto DepResult = DI.depends(&I0, &I1, true);
  996. if (!DepResult)
  997. return true;
  998. #ifndef NDEBUG
  999. if (VerboseFusionDebugging) {
  1000. LLVM_DEBUG(dbgs() << "DA res: "; DepResult->dump(dbgs());
  1001. dbgs() << " [#l: " << DepResult->getLevels() << "][Ordered: "
  1002. << (DepResult->isOrdered() ? "true" : "false")
  1003. << "]\n");
  1004. LLVM_DEBUG(dbgs() << "DepResult Levels: " << DepResult->getLevels()
  1005. << "\n");
  1006. }
  1007. #endif
  1008. if (DepResult->getNextPredecessor() || DepResult->getNextSuccessor())
  1009. LLVM_DEBUG(
  1010. dbgs() << "TODO: Implement pred/succ dependence handling!\n");
  1011. // TODO: Can we actually use the dependence info analysis here?
  1012. return false;
  1013. }
  1014. case FUSION_DEPENDENCE_ANALYSIS_ALL:
  1015. return dependencesAllowFusion(FC0, FC1, I0, I1, AnyDep,
  1016. FUSION_DEPENDENCE_ANALYSIS_SCEV) ||
  1017. dependencesAllowFusion(FC0, FC1, I0, I1, AnyDep,
  1018. FUSION_DEPENDENCE_ANALYSIS_DA);
  1019. }
  1020. llvm_unreachable("Unknown fusion dependence analysis choice!");
  1021. }
  1022. /// Perform a dependence check and return if @p FC0 and @p FC1 can be fused.
  1023. bool dependencesAllowFusion(const FusionCandidate &FC0,
  1024. const FusionCandidate &FC1) {
  1025. LLVM_DEBUG(dbgs() << "Check if " << FC0 << " can be fused with " << FC1
  1026. << "\n");
  1027. assert(FC0.L->getLoopDepth() == FC1.L->getLoopDepth());
  1028. assert(DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()));
  1029. for (Instruction *WriteL0 : FC0.MemWrites) {
  1030. for (Instruction *WriteL1 : FC1.MemWrites)
  1031. if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1,
  1032. /* AnyDep */ false,
  1033. FusionDependenceAnalysis)) {
  1034. InvalidDependencies++;
  1035. return false;
  1036. }
  1037. for (Instruction *ReadL1 : FC1.MemReads)
  1038. if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *ReadL1,
  1039. /* AnyDep */ false,
  1040. FusionDependenceAnalysis)) {
  1041. InvalidDependencies++;
  1042. return false;
  1043. }
  1044. }
  1045. for (Instruction *WriteL1 : FC1.MemWrites) {
  1046. for (Instruction *WriteL0 : FC0.MemWrites)
  1047. if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1,
  1048. /* AnyDep */ false,
  1049. FusionDependenceAnalysis)) {
  1050. InvalidDependencies++;
  1051. return false;
  1052. }
  1053. for (Instruction *ReadL0 : FC0.MemReads)
  1054. if (!dependencesAllowFusion(FC0, FC1, *ReadL0, *WriteL1,
  1055. /* AnyDep */ false,
  1056. FusionDependenceAnalysis)) {
  1057. InvalidDependencies++;
  1058. return false;
  1059. }
  1060. }
  1061. // Walk through all uses in FC1. For each use, find the reaching def. If the
  1062. // def is located in FC0 then it is is not safe to fuse.
  1063. for (BasicBlock *BB : FC1.L->blocks())
  1064. for (Instruction &I : *BB)
  1065. for (auto &Op : I.operands())
  1066. if (Instruction *Def = dyn_cast<Instruction>(Op))
  1067. if (FC0.L->contains(Def->getParent())) {
  1068. InvalidDependencies++;
  1069. return false;
  1070. }
  1071. return true;
  1072. }
  1073. /// Determine if two fusion candidates are adjacent in the CFG.
  1074. ///
  1075. /// This method will determine if there are additional basic blocks in the CFG
  1076. /// between the exit of \p FC0 and the entry of \p FC1.
  1077. /// If the two candidates are guarded loops, then it checks whether the
  1078. /// non-loop successor of the \p FC0 guard branch is the entry block of \p
  1079. /// FC1. If not, then the loops are not adjacent. If the two candidates are
  1080. /// not guarded loops, then it checks whether the exit block of \p FC0 is the
  1081. /// preheader of \p FC1.
  1082. bool isAdjacent(const FusionCandidate &FC0,
  1083. const FusionCandidate &FC1) const {
  1084. // If the successor of the guard branch is FC1, then the loops are adjacent
  1085. if (FC0.GuardBranch)
  1086. return FC0.getNonLoopBlock() == FC1.getEntryBlock();
  1087. else
  1088. return FC0.ExitBlock == FC1.getEntryBlock();
  1089. }
  1090. /// Determine if two fusion candidates have identical guards
  1091. ///
  1092. /// This method will determine if two fusion candidates have the same guards.
  1093. /// The guards are considered the same if:
  1094. /// 1. The instructions to compute the condition used in the compare are
  1095. /// identical.
  1096. /// 2. The successors of the guard have the same flow into/around the loop.
  1097. /// If the compare instructions are identical, then the first successor of the
  1098. /// guard must go to the same place (either the preheader of the loop or the
  1099. /// NonLoopBlock). In other words, the the first successor of both loops must
  1100. /// both go into the loop (i.e., the preheader) or go around the loop (i.e.,
  1101. /// the NonLoopBlock). The same must be true for the second successor.
  1102. bool haveIdenticalGuards(const FusionCandidate &FC0,
  1103. const FusionCandidate &FC1) const {
  1104. assert(FC0.GuardBranch && FC1.GuardBranch &&
  1105. "Expecting FC0 and FC1 to be guarded loops.");
  1106. if (auto FC0CmpInst =
  1107. dyn_cast<Instruction>(FC0.GuardBranch->getCondition()))
  1108. if (auto FC1CmpInst =
  1109. dyn_cast<Instruction>(FC1.GuardBranch->getCondition()))
  1110. if (!FC0CmpInst->isIdenticalTo(FC1CmpInst))
  1111. return false;
  1112. // The compare instructions are identical.
  1113. // Now make sure the successor of the guards have the same flow into/around
  1114. // the loop
  1115. if (FC0.GuardBranch->getSuccessor(0) == FC0.Preheader)
  1116. return (FC1.GuardBranch->getSuccessor(0) == FC1.Preheader);
  1117. else
  1118. return (FC1.GuardBranch->getSuccessor(1) == FC1.Preheader);
  1119. }
  1120. /// Modify the latch branch of FC to be unconditional since successors of the
  1121. /// branch are the same.
  1122. void simplifyLatchBranch(const FusionCandidate &FC) const {
  1123. BranchInst *FCLatchBranch = dyn_cast<BranchInst>(FC.Latch->getTerminator());
  1124. if (FCLatchBranch) {
  1125. assert(FCLatchBranch->isConditional() &&
  1126. FCLatchBranch->getSuccessor(0) == FCLatchBranch->getSuccessor(1) &&
  1127. "Expecting the two successors of FCLatchBranch to be the same");
  1128. BranchInst *NewBranch =
  1129. BranchInst::Create(FCLatchBranch->getSuccessor(0));
  1130. ReplaceInstWithInst(FCLatchBranch, NewBranch);
  1131. }
  1132. }
  1133. /// Move instructions from FC0.Latch to FC1.Latch. If FC0.Latch has an unique
  1134. /// successor, then merge FC0.Latch with its unique successor.
  1135. void mergeLatch(const FusionCandidate &FC0, const FusionCandidate &FC1) {
  1136. moveInstructionsToTheBeginning(*FC0.Latch, *FC1.Latch, DT, PDT, DI);
  1137. if (BasicBlock *Succ = FC0.Latch->getUniqueSuccessor()) {
  1138. MergeBlockIntoPredecessor(Succ, &DTU, &LI);
  1139. DTU.flush();
  1140. }
  1141. }
  1142. /// Fuse two fusion candidates, creating a new fused loop.
  1143. ///
  1144. /// This method contains the mechanics of fusing two loops, represented by \p
  1145. /// FC0 and \p FC1. It is assumed that \p FC0 dominates \p FC1 and \p FC1
  1146. /// postdominates \p FC0 (making them control flow equivalent). It also
  1147. /// assumes that the other conditions for fusion have been met: adjacent,
  1148. /// identical trip counts, and no negative distance dependencies exist that
  1149. /// would prevent fusion. Thus, there is no checking for these conditions in
  1150. /// this method.
  1151. ///
  1152. /// Fusion is performed by rewiring the CFG to update successor blocks of the
  1153. /// components of tho loop. Specifically, the following changes are done:
  1154. ///
  1155. /// 1. The preheader of \p FC1 is removed as it is no longer necessary
  1156. /// (because it is currently only a single statement block).
  1157. /// 2. The latch of \p FC0 is modified to jump to the header of \p FC1.
  1158. /// 3. The latch of \p FC1 i modified to jump to the header of \p FC0.
  1159. /// 4. All blocks from \p FC1 are removed from FC1 and added to FC0.
  1160. ///
  1161. /// All of these modifications are done with dominator tree updates, thus
  1162. /// keeping the dominator (and post dominator) information up-to-date.
  1163. ///
  1164. /// This can be improved in the future by actually merging blocks during
  1165. /// fusion. For example, the preheader of \p FC1 can be merged with the
  1166. /// preheader of \p FC0. This would allow loops with more than a single
  1167. /// statement in the preheader to be fused. Similarly, the latch blocks of the
  1168. /// two loops could also be fused into a single block. This will require
  1169. /// analysis to prove it is safe to move the contents of the block past
  1170. /// existing code, which currently has not been implemented.
  1171. Loop *performFusion(const FusionCandidate &FC0, const FusionCandidate &FC1) {
  1172. assert(FC0.isValid() && FC1.isValid() &&
  1173. "Expecting valid fusion candidates");
  1174. LLVM_DEBUG(dbgs() << "Fusion Candidate 0: \n"; FC0.dump();
  1175. dbgs() << "Fusion Candidate 1: \n"; FC1.dump(););
  1176. // Move instructions from the preheader of FC1 to the end of the preheader
  1177. // of FC0.
  1178. moveInstructionsToTheEnd(*FC1.Preheader, *FC0.Preheader, DT, PDT, DI);
  1179. // Fusing guarded loops is handled slightly differently than non-guarded
  1180. // loops and has been broken out into a separate method instead of trying to
  1181. // intersperse the logic within a single method.
  1182. if (FC0.GuardBranch)
  1183. return fuseGuardedLoops(FC0, FC1);
  1184. assert(FC1.Preheader ==
  1185. (FC0.Peeled ? FC0.ExitBlock->getUniqueSuccessor() : FC0.ExitBlock));
  1186. assert(FC1.Preheader->size() == 1 &&
  1187. FC1.Preheader->getSingleSuccessor() == FC1.Header);
  1188. // Remember the phi nodes originally in the header of FC0 in order to rewire
  1189. // them later. However, this is only necessary if the new loop carried
  1190. // values might not dominate the exiting branch. While we do not generally
  1191. // test if this is the case but simply insert intermediate phi nodes, we
  1192. // need to make sure these intermediate phi nodes have different
  1193. // predecessors. To this end, we filter the special case where the exiting
  1194. // block is the latch block of the first loop. Nothing needs to be done
  1195. // anyway as all loop carried values dominate the latch and thereby also the
  1196. // exiting branch.
  1197. SmallVector<PHINode *, 8> OriginalFC0PHIs;
  1198. if (FC0.ExitingBlock != FC0.Latch)
  1199. for (PHINode &PHI : FC0.Header->phis())
  1200. OriginalFC0PHIs.push_back(&PHI);
  1201. // Replace incoming blocks for header PHIs first.
  1202. FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
  1203. FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
  1204. // Then modify the control flow and update DT and PDT.
  1205. SmallVector<DominatorTree::UpdateType, 8> TreeUpdates;
  1206. // The old exiting block of the first loop (FC0) has to jump to the header
  1207. // of the second as we need to execute the code in the second header block
  1208. // regardless of the trip count. That is, if the trip count is 0, so the
  1209. // back edge is never taken, we still have to execute both loop headers,
  1210. // especially (but not only!) if the second is a do-while style loop.
  1211. // However, doing so might invalidate the phi nodes of the first loop as
  1212. // the new values do only need to dominate their latch and not the exiting
  1213. // predicate. To remedy this potential problem we always introduce phi
  1214. // nodes in the header of the second loop later that select the loop carried
  1215. // value, if the second header was reached through an old latch of the
  1216. // first, or undef otherwise. This is sound as exiting the first implies the
  1217. // second will exit too, __without__ taking the back-edge. [Their
  1218. // trip-counts are equal after all.
  1219. // KB: Would this sequence be simpler to just just make FC0.ExitingBlock go
  1220. // to FC1.Header? I think this is basically what the three sequences are
  1221. // trying to accomplish; however, doing this directly in the CFG may mean
  1222. // the DT/PDT becomes invalid
  1223. if (!FC0.Peeled) {
  1224. FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC1.Preheader,
  1225. FC1.Header);
  1226. TreeUpdates.emplace_back(DominatorTree::UpdateType(
  1227. DominatorTree::Delete, FC0.ExitingBlock, FC1.Preheader));
  1228. TreeUpdates.emplace_back(DominatorTree::UpdateType(
  1229. DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
  1230. } else {
  1231. TreeUpdates.emplace_back(DominatorTree::UpdateType(
  1232. DominatorTree::Delete, FC0.ExitBlock, FC1.Preheader));
  1233. // Remove the ExitBlock of the first Loop (also not needed)
  1234. FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC0.ExitBlock,
  1235. FC1.Header);
  1236. TreeUpdates.emplace_back(DominatorTree::UpdateType(
  1237. DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
  1238. FC0.ExitBlock->getTerminator()->eraseFromParent();
  1239. TreeUpdates.emplace_back(DominatorTree::UpdateType(
  1240. DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
  1241. new UnreachableInst(FC0.ExitBlock->getContext(), FC0.ExitBlock);
  1242. }
  1243. // The pre-header of L1 is not necessary anymore.
  1244. assert(pred_empty(FC1.Preheader));
  1245. FC1.Preheader->getTerminator()->eraseFromParent();
  1246. new UnreachableInst(FC1.Preheader->getContext(), FC1.Preheader);
  1247. TreeUpdates.emplace_back(DominatorTree::UpdateType(
  1248. DominatorTree::Delete, FC1.Preheader, FC1.Header));
  1249. // Moves the phi nodes from the second to the first loops header block.
  1250. while (PHINode *PHI = dyn_cast<PHINode>(&FC1.Header->front())) {
  1251. if (SE.isSCEVable(PHI->getType()))
  1252. SE.forgetValue(PHI);
  1253. if (PHI->hasNUsesOrMore(1))
  1254. PHI->moveBefore(&*FC0.Header->getFirstInsertionPt());
  1255. else
  1256. PHI->eraseFromParent();
  1257. }
  1258. // Introduce new phi nodes in the second loop header to ensure
  1259. // exiting the first and jumping to the header of the second does not break
  1260. // the SSA property of the phis originally in the first loop. See also the
  1261. // comment above.
  1262. Instruction *L1HeaderIP = &FC1.Header->front();
  1263. for (PHINode *LCPHI : OriginalFC0PHIs) {
  1264. int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
  1265. assert(L1LatchBBIdx >= 0 &&
  1266. "Expected loop carried value to be rewired at this point!");
  1267. Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
  1268. PHINode *L1HeaderPHI = PHINode::Create(
  1269. LCV->getType(), 2, LCPHI->getName() + ".afterFC0", L1HeaderIP);
  1270. L1HeaderPHI->addIncoming(LCV, FC0.Latch);
  1271. L1HeaderPHI->addIncoming(UndefValue::get(LCV->getType()),
  1272. FC0.ExitingBlock);
  1273. LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
  1274. }
  1275. // Replace latch terminator destinations.
  1276. FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header);
  1277. FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header);
  1278. // Modify the latch branch of FC0 to be unconditional as both successors of
  1279. // the branch are the same.
  1280. simplifyLatchBranch(FC0);
  1281. // If FC0.Latch and FC0.ExitingBlock are the same then we have already
  1282. // performed the updates above.
  1283. if (FC0.Latch != FC0.ExitingBlock)
  1284. TreeUpdates.emplace_back(DominatorTree::UpdateType(
  1285. DominatorTree::Insert, FC0.Latch, FC1.Header));
  1286. TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
  1287. FC0.Latch, FC0.Header));
  1288. TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
  1289. FC1.Latch, FC0.Header));
  1290. TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
  1291. FC1.Latch, FC1.Header));
  1292. // Update DT/PDT
  1293. DTU.applyUpdates(TreeUpdates);
  1294. LI.removeBlock(FC1.Preheader);
  1295. DTU.deleteBB(FC1.Preheader);
  1296. if (FC0.Peeled) {
  1297. LI.removeBlock(FC0.ExitBlock);
  1298. DTU.deleteBB(FC0.ExitBlock);
  1299. }
  1300. DTU.flush();
  1301. // Is there a way to keep SE up-to-date so we don't need to forget the loops
  1302. // and rebuild the information in subsequent passes of fusion?
  1303. // Note: Need to forget the loops before merging the loop latches, as
  1304. // mergeLatch may remove the only block in FC1.
  1305. SE.forgetLoop(FC1.L);
  1306. SE.forgetLoop(FC0.L);
  1307. // Move instructions from FC0.Latch to FC1.Latch.
  1308. // Note: mergeLatch requires an updated DT.
  1309. mergeLatch(FC0, FC1);
  1310. // Merge the loops.
  1311. SmallVector<BasicBlock *, 8> Blocks(FC1.L->blocks());
  1312. for (BasicBlock *BB : Blocks) {
  1313. FC0.L->addBlockEntry(BB);
  1314. FC1.L->removeBlockFromLoop(BB);
  1315. if (LI.getLoopFor(BB) != FC1.L)
  1316. continue;
  1317. LI.changeLoopFor(BB, FC0.L);
  1318. }
  1319. while (!FC1.L->isInnermost()) {
  1320. const auto &ChildLoopIt = FC1.L->begin();
  1321. Loop *ChildLoop = *ChildLoopIt;
  1322. FC1.L->removeChildLoop(ChildLoopIt);
  1323. FC0.L->addChildLoop(ChildLoop);
  1324. }
  1325. // Delete the now empty loop L1.
  1326. LI.erase(FC1.L);
  1327. #ifndef NDEBUG
  1328. assert(!verifyFunction(*FC0.Header->getParent(), &errs()));
  1329. assert(DT.verify(DominatorTree::VerificationLevel::Fast));
  1330. assert(PDT.verify());
  1331. LI.verify(DT);
  1332. SE.verify();
  1333. #endif
  1334. LLVM_DEBUG(dbgs() << "Fusion done:\n");
  1335. return FC0.L;
  1336. }
  1337. /// Report details on loop fusion opportunities.
  1338. ///
  1339. /// This template function can be used to report both successful and missed
  1340. /// loop fusion opportunities, based on the RemarkKind. The RemarkKind should
  1341. /// be one of:
  1342. /// - OptimizationRemarkMissed to report when loop fusion is unsuccessful
  1343. /// given two valid fusion candidates.
  1344. /// - OptimizationRemark to report successful fusion of two fusion
  1345. /// candidates.
  1346. /// The remarks will be printed using the form:
  1347. /// <path/filename>:<line number>:<column number>: [<function name>]:
  1348. /// <Cand1 Preheader> and <Cand2 Preheader>: <Stat Description>
  1349. template <typename RemarkKind>
  1350. void reportLoopFusion(const FusionCandidate &FC0, const FusionCandidate &FC1,
  1351. llvm::Statistic &Stat) {
  1352. assert(FC0.Preheader && FC1.Preheader &&
  1353. "Expecting valid fusion candidates");
  1354. using namespace ore;
  1355. #if LLVM_ENABLE_STATS
  1356. ++Stat;
  1357. ORE.emit(RemarkKind(DEBUG_TYPE, Stat.getName(), FC0.L->getStartLoc(),
  1358. FC0.Preheader)
  1359. << "[" << FC0.Preheader->getParent()->getName()
  1360. << "]: " << NV("Cand1", StringRef(FC0.Preheader->getName()))
  1361. << " and " << NV("Cand2", StringRef(FC1.Preheader->getName()))
  1362. << ": " << Stat.getDesc());
  1363. #endif
  1364. }
  1365. /// Fuse two guarded fusion candidates, creating a new fused loop.
  1366. ///
  1367. /// Fusing guarded loops is handled much the same way as fusing non-guarded
  1368. /// loops. The rewiring of the CFG is slightly different though, because of
  1369. /// the presence of the guards around the loops and the exit blocks after the
  1370. /// loop body. As such, the new loop is rewired as follows:
  1371. /// 1. Keep the guard branch from FC0 and use the non-loop block target
  1372. /// from the FC1 guard branch.
  1373. /// 2. Remove the exit block from FC0 (this exit block should be empty
  1374. /// right now).
  1375. /// 3. Remove the guard branch for FC1
  1376. /// 4. Remove the preheader for FC1.
  1377. /// The exit block successor for the latch of FC0 is updated to be the header
  1378. /// of FC1 and the non-exit block successor of the latch of FC1 is updated to
  1379. /// be the header of FC0, thus creating the fused loop.
  1380. Loop *fuseGuardedLoops(const FusionCandidate &FC0,
  1381. const FusionCandidate &FC1) {
  1382. assert(FC0.GuardBranch && FC1.GuardBranch && "Expecting guarded loops");
  1383. BasicBlock *FC0GuardBlock = FC0.GuardBranch->getParent();
  1384. BasicBlock *FC1GuardBlock = FC1.GuardBranch->getParent();
  1385. BasicBlock *FC0NonLoopBlock = FC0.getNonLoopBlock();
  1386. BasicBlock *FC1NonLoopBlock = FC1.getNonLoopBlock();
  1387. BasicBlock *FC0ExitBlockSuccessor = FC0.ExitBlock->getUniqueSuccessor();
  1388. // Move instructions from the exit block of FC0 to the beginning of the exit
  1389. // block of FC1, in the case that the FC0 loop has not been peeled. In the
  1390. // case that FC0 loop is peeled, then move the instructions of the successor
  1391. // of the FC0 Exit block to the beginning of the exit block of FC1.
  1392. moveInstructionsToTheBeginning(
  1393. (FC0.Peeled ? *FC0ExitBlockSuccessor : *FC0.ExitBlock), *FC1.ExitBlock,
  1394. DT, PDT, DI);
  1395. // Move instructions from the guard block of FC1 to the end of the guard
  1396. // block of FC0.
  1397. moveInstructionsToTheEnd(*FC1GuardBlock, *FC0GuardBlock, DT, PDT, DI);
  1398. assert(FC0NonLoopBlock == FC1GuardBlock && "Loops are not adjacent");
  1399. SmallVector<DominatorTree::UpdateType, 8> TreeUpdates;
  1400. ////////////////////////////////////////////////////////////////////////////
  1401. // Update the Loop Guard
  1402. ////////////////////////////////////////////////////////////////////////////
  1403. // The guard for FC0 is updated to guard both FC0 and FC1. This is done by
  1404. // changing the NonLoopGuardBlock for FC0 to the NonLoopGuardBlock for FC1.
  1405. // Thus, one path from the guard goes to the preheader for FC0 (and thus
  1406. // executes the new fused loop) and the other path goes to the NonLoopBlock
  1407. // for FC1 (where FC1 guard would have gone if FC1 was not executed).
  1408. FC1NonLoopBlock->replacePhiUsesWith(FC1GuardBlock, FC0GuardBlock);
  1409. FC0.GuardBranch->replaceUsesOfWith(FC0NonLoopBlock, FC1NonLoopBlock);
  1410. BasicBlock *BBToUpdate = FC0.Peeled ? FC0ExitBlockSuccessor : FC0.ExitBlock;
  1411. BBToUpdate->getTerminator()->replaceUsesOfWith(FC1GuardBlock, FC1.Header);
  1412. // The guard of FC1 is not necessary anymore.
  1413. FC1.GuardBranch->eraseFromParent();
  1414. new UnreachableInst(FC1GuardBlock->getContext(), FC1GuardBlock);
  1415. TreeUpdates.emplace_back(DominatorTree::UpdateType(
  1416. DominatorTree::Delete, FC1GuardBlock, FC1.Preheader));
  1417. TreeUpdates.emplace_back(DominatorTree::UpdateType(
  1418. DominatorTree::Delete, FC1GuardBlock, FC1NonLoopBlock));
  1419. TreeUpdates.emplace_back(DominatorTree::UpdateType(
  1420. DominatorTree::Delete, FC0GuardBlock, FC1GuardBlock));
  1421. TreeUpdates.emplace_back(DominatorTree::UpdateType(
  1422. DominatorTree::Insert, FC0GuardBlock, FC1NonLoopBlock));
  1423. if (FC0.Peeled) {
  1424. // Remove the Block after the ExitBlock of FC0
  1425. TreeUpdates.emplace_back(DominatorTree::UpdateType(
  1426. DominatorTree::Delete, FC0ExitBlockSuccessor, FC1GuardBlock));
  1427. FC0ExitBlockSuccessor->getTerminator()->eraseFromParent();
  1428. new UnreachableInst(FC0ExitBlockSuccessor->getContext(),
  1429. FC0ExitBlockSuccessor);
  1430. }
  1431. assert(pred_empty(FC1GuardBlock) &&
  1432. "Expecting guard block to have no predecessors");
  1433. assert(succ_empty(FC1GuardBlock) &&
  1434. "Expecting guard block to have no successors");
  1435. // Remember the phi nodes originally in the header of FC0 in order to rewire
  1436. // them later. However, this is only necessary if the new loop carried
  1437. // values might not dominate the exiting branch. While we do not generally
  1438. // test if this is the case but simply insert intermediate phi nodes, we
  1439. // need to make sure these intermediate phi nodes have different
  1440. // predecessors. To this end, we filter the special case where the exiting
  1441. // block is the latch block of the first loop. Nothing needs to be done
  1442. // anyway as all loop carried values dominate the latch and thereby also the
  1443. // exiting branch.
  1444. // KB: This is no longer necessary because FC0.ExitingBlock == FC0.Latch
  1445. // (because the loops are rotated. Thus, nothing will ever be added to
  1446. // OriginalFC0PHIs.
  1447. SmallVector<PHINode *, 8> OriginalFC0PHIs;
  1448. if (FC0.ExitingBlock != FC0.Latch)
  1449. for (PHINode &PHI : FC0.Header->phis())
  1450. OriginalFC0PHIs.push_back(&PHI);
  1451. assert(OriginalFC0PHIs.empty() && "Expecting OriginalFC0PHIs to be empty!");
  1452. // Replace incoming blocks for header PHIs first.
  1453. FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
  1454. FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
  1455. // The old exiting block of the first loop (FC0) has to jump to the header
  1456. // of the second as we need to execute the code in the second header block
  1457. // regardless of the trip count. That is, if the trip count is 0, so the
  1458. // back edge is never taken, we still have to execute both loop headers,
  1459. // especially (but not only!) if the second is a do-while style loop.
  1460. // However, doing so might invalidate the phi nodes of the first loop as
  1461. // the new values do only need to dominate their latch and not the exiting
  1462. // predicate. To remedy this potential problem we always introduce phi
  1463. // nodes in the header of the second loop later that select the loop carried
  1464. // value, if the second header was reached through an old latch of the
  1465. // first, or undef otherwise. This is sound as exiting the first implies the
  1466. // second will exit too, __without__ taking the back-edge (their
  1467. // trip-counts are equal after all).
  1468. FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC0.ExitBlock,
  1469. FC1.Header);
  1470. TreeUpdates.emplace_back(DominatorTree::UpdateType(
  1471. DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
  1472. TreeUpdates.emplace_back(DominatorTree::UpdateType(
  1473. DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
  1474. // Remove FC0 Exit Block
  1475. // The exit block for FC0 is no longer needed since control will flow
  1476. // directly to the header of FC1. Since it is an empty block, it can be
  1477. // removed at this point.
  1478. // TODO: In the future, we can handle non-empty exit blocks my merging any
  1479. // instructions from FC0 exit block into FC1 exit block prior to removing
  1480. // the block.
  1481. assert(pred_empty(FC0.ExitBlock) && "Expecting exit block to be empty");
  1482. FC0.ExitBlock->getTerminator()->eraseFromParent();
  1483. new UnreachableInst(FC0.ExitBlock->getContext(), FC0.ExitBlock);
  1484. // Remove FC1 Preheader
  1485. // The pre-header of L1 is not necessary anymore.
  1486. assert(pred_empty(FC1.Preheader));
  1487. FC1.Preheader->getTerminator()->eraseFromParent();
  1488. new UnreachableInst(FC1.Preheader->getContext(), FC1.Preheader);
  1489. TreeUpdates.emplace_back(DominatorTree::UpdateType(
  1490. DominatorTree::Delete, FC1.Preheader, FC1.Header));
  1491. // Moves the phi nodes from the second to the first loops header block.
  1492. while (PHINode *PHI = dyn_cast<PHINode>(&FC1.Header->front())) {
  1493. if (SE.isSCEVable(PHI->getType()))
  1494. SE.forgetValue(PHI);
  1495. if (PHI->hasNUsesOrMore(1))
  1496. PHI->moveBefore(&*FC0.Header->getFirstInsertionPt());
  1497. else
  1498. PHI->eraseFromParent();
  1499. }
  1500. // Introduce new phi nodes in the second loop header to ensure
  1501. // exiting the first and jumping to the header of the second does not break
  1502. // the SSA property of the phis originally in the first loop. See also the
  1503. // comment above.
  1504. Instruction *L1HeaderIP = &FC1.Header->front();
  1505. for (PHINode *LCPHI : OriginalFC0PHIs) {
  1506. int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
  1507. assert(L1LatchBBIdx >= 0 &&
  1508. "Expected loop carried value to be rewired at this point!");
  1509. Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
  1510. PHINode *L1HeaderPHI = PHINode::Create(
  1511. LCV->getType(), 2, LCPHI->getName() + ".afterFC0", L1HeaderIP);
  1512. L1HeaderPHI->addIncoming(LCV, FC0.Latch);
  1513. L1HeaderPHI->addIncoming(UndefValue::get(LCV->getType()),
  1514. FC0.ExitingBlock);
  1515. LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
  1516. }
  1517. // Update the latches
  1518. // Replace latch terminator destinations.
  1519. FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header);
  1520. FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header);
  1521. // Modify the latch branch of FC0 to be unconditional as both successors of
  1522. // the branch are the same.
  1523. simplifyLatchBranch(FC0);
  1524. // If FC0.Latch and FC0.ExitingBlock are the same then we have already
  1525. // performed the updates above.
  1526. if (FC0.Latch != FC0.ExitingBlock)
  1527. TreeUpdates.emplace_back(DominatorTree::UpdateType(
  1528. DominatorTree::Insert, FC0.Latch, FC1.Header));
  1529. TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
  1530. FC0.Latch, FC0.Header));
  1531. TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
  1532. FC1.Latch, FC0.Header));
  1533. TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
  1534. FC1.Latch, FC1.Header));
  1535. // All done
  1536. // Apply the updates to the Dominator Tree and cleanup.
  1537. assert(succ_empty(FC1GuardBlock) && "FC1GuardBlock has successors!!");
  1538. assert(pred_empty(FC1GuardBlock) && "FC1GuardBlock has predecessors!!");
  1539. // Update DT/PDT
  1540. DTU.applyUpdates(TreeUpdates);
  1541. LI.removeBlock(FC1GuardBlock);
  1542. LI.removeBlock(FC1.Preheader);
  1543. LI.removeBlock(FC0.ExitBlock);
  1544. if (FC0.Peeled) {
  1545. LI.removeBlock(FC0ExitBlockSuccessor);
  1546. DTU.deleteBB(FC0ExitBlockSuccessor);
  1547. }
  1548. DTU.deleteBB(FC1GuardBlock);
  1549. DTU.deleteBB(FC1.Preheader);
  1550. DTU.deleteBB(FC0.ExitBlock);
  1551. DTU.flush();
  1552. // Is there a way to keep SE up-to-date so we don't need to forget the loops
  1553. // and rebuild the information in subsequent passes of fusion?
  1554. // Note: Need to forget the loops before merging the loop latches, as
  1555. // mergeLatch may remove the only block in FC1.
  1556. SE.forgetLoop(FC1.L);
  1557. SE.forgetLoop(FC0.L);
  1558. // Move instructions from FC0.Latch to FC1.Latch.
  1559. // Note: mergeLatch requires an updated DT.
  1560. mergeLatch(FC0, FC1);
  1561. // Merge the loops.
  1562. SmallVector<BasicBlock *, 8> Blocks(FC1.L->blocks());
  1563. for (BasicBlock *BB : Blocks) {
  1564. FC0.L->addBlockEntry(BB);
  1565. FC1.L->removeBlockFromLoop(BB);
  1566. if (LI.getLoopFor(BB) != FC1.L)
  1567. continue;
  1568. LI.changeLoopFor(BB, FC0.L);
  1569. }
  1570. while (!FC1.L->isInnermost()) {
  1571. const auto &ChildLoopIt = FC1.L->begin();
  1572. Loop *ChildLoop = *ChildLoopIt;
  1573. FC1.L->removeChildLoop(ChildLoopIt);
  1574. FC0.L->addChildLoop(ChildLoop);
  1575. }
  1576. // Delete the now empty loop L1.
  1577. LI.erase(FC1.L);
  1578. #ifndef NDEBUG
  1579. assert(!verifyFunction(*FC0.Header->getParent(), &errs()));
  1580. assert(DT.verify(DominatorTree::VerificationLevel::Fast));
  1581. assert(PDT.verify());
  1582. LI.verify(DT);
  1583. SE.verify();
  1584. #endif
  1585. LLVM_DEBUG(dbgs() << "Fusion done:\n");
  1586. return FC0.L;
  1587. }
  1588. };
  1589. struct LoopFuseLegacy : public FunctionPass {
  1590. static char ID;
  1591. LoopFuseLegacy() : FunctionPass(ID) {
  1592. initializeLoopFuseLegacyPass(*PassRegistry::getPassRegistry());
  1593. }
  1594. void getAnalysisUsage(AnalysisUsage &AU) const override {
  1595. AU.addRequiredID(LoopSimplifyID);
  1596. AU.addRequired<ScalarEvolutionWrapperPass>();
  1597. AU.addRequired<LoopInfoWrapperPass>();
  1598. AU.addRequired<DominatorTreeWrapperPass>();
  1599. AU.addRequired<PostDominatorTreeWrapperPass>();
  1600. AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
  1601. AU.addRequired<DependenceAnalysisWrapperPass>();
  1602. AU.addRequired<AssumptionCacheTracker>();
  1603. AU.addRequired<TargetTransformInfoWrapperPass>();
  1604. AU.addPreserved<ScalarEvolutionWrapperPass>();
  1605. AU.addPreserved<LoopInfoWrapperPass>();
  1606. AU.addPreserved<DominatorTreeWrapperPass>();
  1607. AU.addPreserved<PostDominatorTreeWrapperPass>();
  1608. }
  1609. bool runOnFunction(Function &F) override {
  1610. if (skipFunction(F))
  1611. return false;
  1612. auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  1613. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1614. auto &DI = getAnalysis<DependenceAnalysisWrapperPass>().getDI();
  1615. auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  1616. auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
  1617. auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
  1618. auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  1619. const TargetTransformInfo &TTI =
  1620. getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  1621. const DataLayout &DL = F.getParent()->getDataLayout();
  1622. LoopFuser LF(LI, DT, DI, SE, PDT, ORE, DL, AC, TTI);
  1623. return LF.fuseLoops(F);
  1624. }
  1625. };
  1626. } // namespace
  1627. PreservedAnalyses LoopFusePass::run(Function &F, FunctionAnalysisManager &AM) {
  1628. auto &LI = AM.getResult<LoopAnalysis>(F);
  1629. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  1630. auto &DI = AM.getResult<DependenceAnalysis>(F);
  1631. auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
  1632. auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
  1633. auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
  1634. auto &AC = AM.getResult<AssumptionAnalysis>(F);
  1635. const TargetTransformInfo &TTI = AM.getResult<TargetIRAnalysis>(F);
  1636. const DataLayout &DL = F.getParent()->getDataLayout();
  1637. LoopFuser LF(LI, DT, DI, SE, PDT, ORE, DL, AC, TTI);
  1638. bool Changed = LF.fuseLoops(F);
  1639. if (!Changed)
  1640. return PreservedAnalyses::all();
  1641. PreservedAnalyses PA;
  1642. PA.preserve<DominatorTreeAnalysis>();
  1643. PA.preserve<PostDominatorTreeAnalysis>();
  1644. PA.preserve<ScalarEvolutionAnalysis>();
  1645. PA.preserve<LoopAnalysis>();
  1646. return PA;
  1647. }
  1648. char LoopFuseLegacy::ID = 0;
  1649. INITIALIZE_PASS_BEGIN(LoopFuseLegacy, "loop-fusion", "Loop Fusion", false,
  1650. false)
  1651. INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
  1652. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  1653. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  1654. INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass)
  1655. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  1656. INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
  1657. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  1658. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  1659. INITIALIZE_PASS_END(LoopFuseLegacy, "loop-fusion", "Loop Fusion", false, false)
  1660. FunctionPass *llvm::createLoopFusePass() { return new LoopFuseLegacy(); }