LLVM 23.0.0git
LoopFuse.cpp
Go to the documentation of this file.
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
48#include "llvm/ADT/Statistic.h"
57#include "llvm/IR/Function.h"
58#include "llvm/IR/Verifier.h"
60#include "llvm/Support/Debug.h"
66#include <list>
67
68using namespace llvm;
69
70#define DEBUG_TYPE "loop-fusion"
71
72STATISTIC(FuseCounter, "Loops fused");
73STATISTIC(NumFusionCandidates, "Number of candidates for loop fusion");
74STATISTIC(InvalidLoopStructure, "Loop has invalid structure");
75STATISTIC(AddressTakenBB, "Basic block has address taken");
76STATISTIC(MayThrowException, "Loop may throw an exception");
77STATISTIC(ContainsVolatileAccess, "Loop contains a volatile access");
78STATISTIC(ContainsAtomicAccess, "Loop contains an atomic access");
79STATISTIC(NotSimplifiedForm, "Loop is not in simplified form");
80STATISTIC(InvalidDependencies, "Dependencies prevent fusion");
81STATISTIC(UnknownTripCount, "Loop has unknown trip count");
82STATISTIC(UncomputableTripCount, "SCEV cannot compute trip count of loop");
83STATISTIC(NonEqualTripCount, "Loop trip counts are not the same");
85 NonEmptyPreheader,
86 "Loop has a non-empty preheader with instructions that cannot be moved");
87STATISTIC(FusionNotBeneficial, "Fusion is not beneficial");
88STATISTIC(NonIdenticalGuards, "Candidates have different guards");
89STATISTIC(NonEmptyExitBlock, "Candidate has a non-empty exit block with "
90 "instructions that cannot be moved");
91STATISTIC(NonEmptyGuardBlock, "Candidate has a non-empty guard block with "
92 "instructions that cannot be moved");
93STATISTIC(NotRotated, "Candidate is not rotated");
94STATISTIC(OnlySecondCandidateIsGuarded,
95 "The second candidate is guarded while the first one is not");
96STATISTIC(NumHoistedInsts, "Number of hoisted preheader instructions.");
97STATISTIC(NumSunkInsts, "Number of sunk preheader instructions.");
98STATISTIC(NumDA, "DA checks passed");
99
101 "loop-fusion-peel-max-count", cl::init(0), cl::Hidden,
102 cl::desc("Max number of iterations to be peeled from a loop, such that "
103 "fusion can take place"));
104
105#ifndef NDEBUG
106static cl::opt<bool>
107 VerboseFusionDebugging("loop-fusion-verbose-debug",
108 cl::desc("Enable verbose debugging for Loop Fusion"),
109 cl::Hidden, cl::init(false));
110#endif
111
112namespace {
113/// This class is used to represent a candidate for loop fusion. When it is
114/// constructed, it checks the conditions for loop fusion to ensure that it
115/// represents a valid candidate. It caches several parts of a loop that are
116/// used throughout loop fusion (e.g., loop preheader, loop header, etc) instead
117/// of continually querying the underlying Loop to retrieve these values. It is
118/// assumed these will not change throughout loop fusion.
119///
120/// The invalidate method should be used to indicate that the FusionCandidate is
121/// no longer a valid candidate for fusion. Similarly, the isValid() method can
122/// be used to ensure that the FusionCandidate is still valid for fusion.
123struct FusionCandidate {
124 /// Cache of parts of the loop used throughout loop fusion. These should not
125 /// need to change throughout the analysis and transformation.
126 /// These parts are cached to avoid repeatedly looking up in the Loop class.
127
128 /// Preheader of the loop this candidate represents
129 BasicBlock *Preheader;
130 /// Header of the loop this candidate represents
131 BasicBlock *Header;
132 /// Blocks in the loop that exit the loop
133 BasicBlock *ExitingBlock;
134 /// The successor block of this loop (where the exiting blocks go to)
135 BasicBlock *ExitBlock;
136 /// Latch of the loop
137 BasicBlock *Latch;
138 /// The loop that this fusion candidate represents
139 Loop *L;
140 /// Vector of instructions in this loop that read from memory
142 /// Vector of instructions in this loop that write to memory
144 /// Are all of the members of this fusion candidate still valid
145 bool Valid;
146 /// Guard branch of the loop, if it exists
147 CondBrInst *GuardBranch;
148 /// Peeling Paramaters of the Loop.
150 /// Can you Peel this Loop?
151 bool AbleToPeel;
152 /// Has this loop been Peeled
153 bool Peeled;
154
155 DominatorTree &DT;
156 const PostDominatorTree *PDT;
157
159
160 FusionCandidate(Loop *L, DominatorTree &DT, const PostDominatorTree *PDT,
162 : Preheader(L->getLoopPreheader()), Header(L->getHeader()),
163 ExitingBlock(L->getExitingBlock()), ExitBlock(L->getExitBlock()),
164 Latch(L->getLoopLatch()), L(L), Valid(true),
165 GuardBranch(L->getLoopGuardBranch()), PP(PP), AbleToPeel(canPeel(L)),
166 Peeled(false), DT(DT), PDT(PDT), ORE(ORE) {
167
168 // Walk over all blocks in the loop and check for conditions that may
169 // prevent fusion. For each block, walk over all instructions and collect
170 // the memory reads and writes If any instructions that prevent fusion are
171 // found, invalidate this object and return.
172 for (BasicBlock *BB : L->blocks()) {
173 if (BB->hasAddressTaken()) {
174 invalidate();
175 reportInvalidCandidate(AddressTakenBB);
176 return;
177 }
178
179 for (Instruction &I : *BB) {
180 if (I.mayThrow()) {
181 invalidate();
182 reportInvalidCandidate(MayThrowException);
183 return;
184 }
185 if (I.isVolatile()) {
186 invalidate();
187 reportInvalidCandidate(ContainsVolatileAccess);
188 return;
189 }
190 // Atomic accesses impose ordering/synchronization constraints that the
191 // dependence analysis used for fusion does not model, so reordering
192 // them across the fused body could be unsafe.
193 if (I.isAtomic()) {
194 invalidate();
195 reportInvalidCandidate(ContainsAtomicAccess);
196 return;
197 }
198 if (I.mayWriteToMemory())
199 MemWrites.push_back(&I);
200 if (I.mayReadFromMemory())
201 MemReads.push_back(&I);
202 }
203 }
204 }
205
206 /// Check if all members of the class are valid.
207 bool isValid() const {
208 return Preheader && ExitingBlock && ExitBlock && Latch && L &&
209 !L->isInvalid() && Valid;
210 }
211
212 /// Verify that all members are in sync with the Loop object.
213 void verify() const {
214 assert(isValid() && "Candidate is not valid!!");
215 assert(!L->isInvalid() && "Loop is invalid!");
216 assert(Preheader == L->getLoopPreheader() && "Preheader is out of sync");
217 assert(Header == L->getHeader() && "Header is out of sync");
218 assert(ExitingBlock == L->getExitingBlock() &&
219 "Exiting Blocks is out of sync");
220 assert(ExitBlock == L->getExitBlock() && "Exit block is out of sync");
221 assert(Latch == L->getLoopLatch() && "Latch is out of sync");
222 }
223
224 /// Get the entry block for this fusion candidate.
225 ///
226 /// If this fusion candidate represents a guarded loop, the entry block is the
227 /// loop guard block. If it represents an unguarded loop, the entry block is
228 /// the preheader of the loop.
229 BasicBlock *getEntryBlock() const {
230 if (GuardBranch)
231 return GuardBranch->getParent();
232 return Preheader;
233 }
234
235 /// After Peeling the loop is modified quite a bit, hence all of the Blocks
236 /// need to be updated accordingly.
237 void updateAfterPeeling() {
238 Preheader = L->getLoopPreheader();
239 Header = L->getHeader();
240 ExitingBlock = L->getExitingBlock();
241 ExitBlock = L->getExitBlock();
242 Latch = L->getLoopLatch();
243 verify();
244 }
245
246 /// Given a guarded loop, get the successor of the guard that is not in the
247 /// loop.
248 ///
249 /// This method returns the successor of the loop guard that is not located
250 /// within the loop (i.e., the successor of the guard that is not the
251 /// preheader).
252 /// This method is only valid for guarded loops.
253 BasicBlock *getNonLoopBlock() const {
254 assert(GuardBranch && "Only valid on guarded loops.");
255 if (Peeled)
256 return GuardBranch->getSuccessor(1);
257 return (GuardBranch->getSuccessor(0) == Preheader)
258 ? GuardBranch->getSuccessor(1)
259 : GuardBranch->getSuccessor(0);
260 }
261
262#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
263 LLVM_DUMP_METHOD void dump() const {
264 dbgs() << "\tGuardBranch: ";
265 if (GuardBranch)
266 dbgs() << *GuardBranch;
267 else
268 dbgs() << "nullptr";
269 dbgs() << "\n"
270 << (GuardBranch ? GuardBranch->getName() : "nullptr") << "\n"
271 << "\tPreheader: " << (Preheader ? Preheader->getName() : "nullptr")
272 << "\n"
273 << "\tHeader: " << (Header ? Header->getName() : "nullptr") << "\n"
274 << "\tExitingBB: "
275 << (ExitingBlock ? ExitingBlock->getName() : "nullptr") << "\n"
276 << "\tExitBB: " << (ExitBlock ? ExitBlock->getName() : "nullptr")
277 << "\n"
278 << "\tLatch: " << (Latch ? Latch->getName() : "nullptr") << "\n"
279 << "\tEntryBlock: "
280 << (getEntryBlock() ? getEntryBlock()->getName() : "nullptr")
281 << "\n";
282 }
283#endif
284
285 /// Determine if a fusion candidate (representing a loop) is eligible for
286 /// fusion. Note that this only checks whether a single loop can be fused - it
287 /// does not check whether it is *legal* to fuse two loops together.
288 bool isEligibleForFusion(ScalarEvolution &SE) const {
289 if (!isValid()) {
290 LLVM_DEBUG(dbgs() << "FC has invalid CFG requirements!\n");
291 assert(Header && "Header should be guaranteed to exist!");
292 ++InvalidLoopStructure;
293 return false;
294 }
295
296 // Require ScalarEvolution to be able to determine a trip count.
298 LLVM_DEBUG(dbgs() << "Loop " << L->getName()
299 << " trip count not computable!\n");
300 return reportInvalidCandidate(UnknownTripCount);
301 }
302
303 if (!L->isLoopSimplifyForm()) {
304 LLVM_DEBUG(dbgs() << "Loop " << L->getName()
305 << " is not in simplified form!\n");
306 return reportInvalidCandidate(NotSimplifiedForm);
307 }
308
309 if (!L->isRotatedForm()) {
310 LLVM_DEBUG(dbgs() << "Loop " << L->getName() << " is not rotated!\n");
311 return reportInvalidCandidate(NotRotated);
312 }
313
314 return true;
315 }
316
317private:
318 // This is only used internally for now, to clear the MemWrites and MemReads
319 // list and setting Valid to false. I can't envision other uses of this right
320 // now, since once FusionCandidates are put into the FusionCandidateList they
321 // are immutable. Thus, any time we need to change/update a FusionCandidate,
322 // we must create a new one and insert it into the FusionCandidateList to
323 // ensure the FusionCandidateList remains ordered correctly.
324 void invalidate() {
325 MemWrites.clear();
326 MemReads.clear();
327 Valid = false;
328 }
329
330 bool reportInvalidCandidate(Statistic &Stat) const {
331 using namespace ore;
332 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "InvalidCandidate",
333 L->getStartLoc(), L->getHeader())
334 << "Loop is not a candidate for fusion");
335
336#if LLVM_ENABLE_STATS
337 ++Stat;
338 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, Stat.getName(),
339 L->getStartLoc(), L->getHeader())
340 << "[" << L->getHeader()->getParent()->getName() << "]: "
341 << "Loop is not a candidate for fusion: " << Stat.getDesc());
342#endif
343 return false;
344 }
345};
346} // namespace
347
349
350// List of adjacent fusion candidates in order. Thus, if FC0 comes *before* FC1
351// in a FusionCandidateList, then FC0 dominates FC1, FC1 post-dominates FC0,
352// and they are adjacent.
353using FusionCandidateList = std::list<FusionCandidate>;
355
356#ifndef NDEBUG
357static void printLoopVector(const LoopVector &LV) {
358 dbgs() << "****************************\n";
359 for (const Loop *L : LV)
360 printLoop(*L, dbgs());
361 dbgs() << "****************************\n";
362}
363
364static raw_ostream &operator<<(raw_ostream &OS, const FusionCandidate &FC) {
365 if (FC.isValid())
366 OS << FC.Preheader->getName();
367 else
368 OS << "<Invalid>";
369
370 return OS;
371}
372
374 const FusionCandidateList &CandList) {
375 for (const FusionCandidate &FC : CandList)
376 OS << FC << '\n';
377
378 return OS;
379}
380
381static void
383 dbgs() << "Fusion Candidates: \n";
384 for (const auto &CandidateList : FusionCandidates) {
385 dbgs() << "*** Fusion Candidate List ***\n";
386 dbgs() << CandidateList;
387 dbgs() << "****************************\n";
388 }
389}
390#endif // NDEBUG
391
392namespace {
393
394/// Collect all loops in function at the same nest level, starting at the
395/// outermost level.
396///
397/// This data structure collects all loops at the same nest level for a
398/// given function (specified by the LoopInfo object). It starts at the
399/// outermost level.
400struct LoopDepthTree {
401 using LoopsOnLevelTy = SmallVector<LoopVector, 4>;
402 using iterator = LoopsOnLevelTy::iterator;
403 using const_iterator = LoopsOnLevelTy::const_iterator;
404
405 LoopDepthTree(LoopInfo &LI) : Depth(1) {
406 if (!LI.empty())
407 LoopsOnLevel.emplace_back(LoopVector(LI.rbegin(), LI.rend()));
408 }
409
410 /// Test whether a given loop has been removed from the function, and thus is
411 /// no longer valid.
412 bool isRemovedLoop(const Loop *L) const { return RemovedLoops.count(L); }
413
414 /// Record that a given loop has been removed from the function and is no
415 /// longer valid.
416 void removeLoop(const Loop *L) { RemovedLoops.insert(L); }
417
418 /// Descend the tree to the next (inner) nesting level
419 void descend() {
420 LoopsOnLevelTy LoopsOnNextLevel;
421
422 for (const LoopVector &LV : *this)
423 for (Loop *L : LV)
424 if (!isRemovedLoop(L) && L->begin() != L->end())
425 LoopsOnNextLevel.emplace_back(LoopVector(L->begin(), L->end()));
426
427 LoopsOnLevel = LoopsOnNextLevel;
428 RemovedLoops.clear();
429 Depth++;
430 }
431
432 bool empty() const { return size() == 0; }
433 size_t size() const { return LoopsOnLevel.size() - RemovedLoops.size(); }
434 unsigned getDepth() const { return Depth; }
435
436 iterator begin() { return LoopsOnLevel.begin(); }
437 iterator end() { return LoopsOnLevel.end(); }
438 const_iterator begin() const { return LoopsOnLevel.begin(); }
439 const_iterator end() const { return LoopsOnLevel.end(); }
440
441private:
442 /// Set of loops that have been removed from the function and are no longer
443 /// valid.
444 SmallPtrSet<const Loop *, 8> RemovedLoops;
445
446 /// Depth of the current level, starting at 1 (outermost loops).
447 unsigned Depth;
448
449 /// Vector of loops at the current depth level that have the same parent loop
450 LoopsOnLevelTy LoopsOnLevel;
451};
452
453struct LoopFuser {
454private:
455 // Sets of control flow equivalent fusion candidates for a given nest level.
456 FusionCandidateCollection FusionCandidates;
457
458 LoopDepthTree LDT;
459 DomTreeUpdater DTU;
460
461 LoopInfo &LI;
462 DominatorTree &DT;
463 DependenceInfo &DI;
464 ScalarEvolution &SE;
465 PostDominatorTree &PDT;
466 OptimizationRemarkEmitter &ORE;
467 AssumptionCache &AC;
468 const TargetTransformInfo &TTI;
469
470public:
471 LoopFuser(LoopInfo &LI, DominatorTree &DT, DependenceInfo &DI,
472 ScalarEvolution &SE, PostDominatorTree &PDT,
473 OptimizationRemarkEmitter &ORE, const DataLayout &DL,
474 AssumptionCache &AC, const TargetTransformInfo &TTI)
475 : LDT(LI), DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy), LI(LI),
476 DT(DT), DI(DI), SE(SE), PDT(PDT), ORE(ORE), AC(AC), TTI(TTI) {}
477
478 /// This is the main entry point for loop fusion. It will traverse the
479 /// specified function and collect candidate loops to fuse, starting at the
480 /// outermost nesting level and working inwards.
481 bool fuseLoops(Function &F) {
482#ifndef NDEBUG
484 LI.print(dbgs());
485 }
486#endif
487
488 LLVM_DEBUG(dbgs() << "Performing Loop Fusion on function " << F.getName()
489 << "\n");
490 bool Changed = false;
491
492 while (!LDT.empty()) {
493 LLVM_DEBUG(dbgs() << "Got " << LDT.size() << " loop sets for depth "
494 << LDT.getDepth() << "\n";);
495
496 for (const LoopVector &LV : LDT) {
497 assert(LV.size() > 0 && "Empty loop set was build!");
498
499 // Skip singleton loop sets as they do not offer fusion opportunities on
500 // this level.
501 if (LV.size() == 1)
502 continue;
503#ifndef NDEBUG
505 LLVM_DEBUG({
506 dbgs() << " Visit loop set (#" << LV.size() << "):\n";
507 printLoopVector(LV);
508 });
509 }
510#endif
511
512 collectFusionCandidates(LV);
513 Changed |= fuseCandidates();
514 // All loops in the candidate sets have a common parent (or no parent).
515 // Next loop vector will correspond to a different parent. It is safe
516 // to remove all the candidates currently in the set.
517 FusionCandidates.clear();
518 }
519
520 // Finished analyzing candidates at this level. Descend to the next level.
521 LLVM_DEBUG(dbgs() << "Descend one level!\n");
522 LDT.descend();
523 }
524
525 if (Changed)
526 LLVM_DEBUG(dbgs() << "Function after Loop Fusion: \n"; F.dump(););
527
528#ifndef NDEBUG
529 assert(DT.verify());
530 assert(PDT.verify());
531 LI.verify(DT);
532 SE.verify();
533#endif
534
535 LLVM_DEBUG(dbgs() << "Loop Fusion complete\n");
536 return Changed;
537 }
538
539private:
540 /// Iterate over all loops in the given loop set and identify the loops that
541 /// are eligible for fusion. Place all eligible fusion candidates into Control
542 /// Flow Equivalent sets, sorted by dominance.
543 void collectFusionCandidates(const LoopVector &LV) {
544 for (Loop *L : LV) {
546 gatherPeelingPreferences(L, SE, TTI, std::nullopt, std::nullopt);
547 FusionCandidate CurrCand(L, DT, &PDT, ORE, PP);
548 if (!CurrCand.isEligibleForFusion(SE))
549 continue;
550
551 // Go through each list in FusionCandidates and determine if the first or
552 // last loop in the list is strictly adjacent to L. If it is, append L.
553 // If not, go to the next list.
554 // If no suitable list is found, start another list and add it to
555 // FusionCandidates.
556 bool FoundAdjacent = false;
557 for (auto &CurrCandList : FusionCandidates) {
558 if (isStrictlyAdjacent(CurrCandList.back(), CurrCand)) {
559 CurrCandList.push_back(CurrCand);
560 FoundAdjacent = true;
561 NumFusionCandidates++;
562#ifndef NDEBUG
564 LLVM_DEBUG(dbgs() << "Adding " << CurrCand
565 << " to existing candidate list\n");
566#endif
567 break;
568 }
569 }
570 if (!FoundAdjacent) {
571 // No list was found. Create a new list and add to FusionCandidates
572#ifndef NDEBUG
574 LLVM_DEBUG(dbgs() << "Adding " << CurrCand << " to new list\n");
575#endif
576 FusionCandidateList NewCandList;
577 NewCandList.push_back(CurrCand);
578 FusionCandidates.push_back(NewCandList);
579 }
580 }
581 }
582
583 /// Determine if it is beneficial to fuse two loops.
584 ///
585 /// For now, this method simply returns true because we want to fuse as much
586 /// as possible (primarily to test the pass). This method will evolve, over
587 /// time, to add heuristics for profitability of fusion.
588 bool isBeneficialFusion(const FusionCandidate &FC0,
589 const FusionCandidate &FC1) {
590 return true;
591 }
592
593 /// Computes the integer difference in trip counts:
594 /// TripCount(FC0) - TripCount(FC1).
595 ///
596 /// \returns The integer difference, or std::nullopt if it
597 /// cannot be determined.
598 std::optional<int64_t>
599 calculateTripCountDiff(const FusionCandidate &FC0,
600 const FusionCandidate &FC1) const {
601 const SCEV *TripCount0 = SE.getBackedgeTakenCount(FC0.L);
602 if (isa<SCEVCouldNotCompute>(TripCount0)) {
603 UncomputableTripCount++;
604 LLVM_DEBUG(dbgs() << "Trip count of first loop could not be computed!");
605 return std::nullopt;
606 }
607
608 const SCEV *TripCount1 = SE.getBackedgeTakenCount(FC1.L);
609 if (isa<SCEVCouldNotCompute>(TripCount1)) {
610 UncomputableTripCount++;
611 LLVM_DEBUG(dbgs() << "Trip count of second loop could not be computed!");
612 return std::nullopt;
613 }
614
615 LLVM_DEBUG(dbgs() << "\tTrip counts: " << *TripCount0 << " & "
616 << *TripCount1 << " are "
617 << (TripCount0 == TripCount1 ? "identical" : "different")
618 << "\n");
619
620 if (TripCount0 == TripCount1)
621 return 0;
622
623 LLVM_DEBUG(dbgs() << "The loops do not have the same tripcount, "
624 "determining the difference between trip counts\n");
625
626 // Currently only considering loops with a single exit point
627 // and a non-constant trip count. Note that the return value
628 // of getSmallConstantTripCount is a 32 bit number, based on
629 // the existing implementation.
630 const int64_t TC0 =
631 static_cast<int64_t>(SE.getSmallConstantTripCount(FC0.L));
632 const int64_t TC1 =
633 static_cast<int64_t>(SE.getSmallConstantTripCount(FC1.L));
634
635 // If any of the tripcounts are zero that means that loop(s) do not have
636 // a single exit or a constant tripcount.
637 if (TC0 == 0 || TC1 == 0) {
638 LLVM_DEBUG(dbgs() << "Loop(s) do not have a single exit point or do not "
639 "have a constant number of iterations. Peeling "
640 "is not benefical\n");
641 return std::nullopt;
642 }
643
644 return TC0 - TC1;
645 }
646
647 void peelFusionCandidate(FusionCandidate &FC0, const FusionCandidate &FC1,
648 unsigned PeelCount) {
649 assert(FC0.AbleToPeel && "Should be able to peel loop");
650
651 LLVM_DEBUG(dbgs() << "Attempting to peel first " << PeelCount
652 << " iterations of the first loop. \n");
653
655 // LoopFusion is a function pass that neither requires nor preserves
656 // LCSSA, so peelLoop need not preserve it across its internal
657 // simplifyLoop call.
658 peelLoop(FC0.L, PeelCount, /*PeelLast=*/false, &LI, &SE, DT, &AC,
659 /*PreserveLCSSA=*/false, VMap);
660 FC0.Peeled = true;
661 LLVM_DEBUG(dbgs() << "Done Peeling\n");
662
663#ifndef NDEBUG
664 auto TCDiff = calculateTripCountDiff(FC0, FC1);
665
666 assert(TCDiff && *TCDiff == 0 &&
667 "Loops should have identical trip counts after peeling");
668#endif
669
670 FC0.PP.PeelCount += PeelCount;
671
672 // Peeling does not update the PDT
673 PDT.recalculate(*FC0.Preheader->getParent());
674
675 FC0.updateAfterPeeling();
676
677 // In this case the iterations of the loop are constant, so the first
678 // loop will execute completely (will not jump from one of
679 // the peeled blocks to the second loop). Here we are updating the
680 // branch conditions of each of the peeled blocks, such that it will
681 // branch to its successor which is not the preheader of the second loop
682 // in the case of unguarded loops, or the succesors of the exit block of
683 // the first loop otherwise. Doing this update will ensure that the entry
684 // block of the first loop dominates the entry block of the second loop.
685 BasicBlock *BB =
686 FC0.GuardBranch ? FC0.ExitBlock->getUniqueSuccessor() : FC1.Preheader;
687 if (BB) {
689 SmallVector<Instruction *, 8> WorkList;
690 for (BasicBlock *Pred : predecessors(BB)) {
691 if (Pred != FC0.ExitBlock) {
692 WorkList.emplace_back(Pred->getTerminator());
693 TreeUpdates.emplace_back(
694 DominatorTree::UpdateType(DominatorTree::Delete, Pred, BB));
695 }
696 }
697 // Cannot modify the predecessors inside the above loop as it will cause
698 // the iterators to be nullptrs, causing memory errors.
699 for (Instruction *CurrentBranch : WorkList) {
700 BasicBlock *Succ = CurrentBranch->getSuccessor(0);
701 if (Succ == BB)
702 Succ = CurrentBranch->getSuccessor(1);
703 ReplaceInstWithInst(CurrentBranch, UncondBrInst::Create(Succ));
704 }
705
706 DTU.applyUpdates(TreeUpdates);
707 DTU.flush();
708 }
710 dbgs() << "Sucessfully peeled " << FC0.PP.PeelCount
711 << " iterations from the first loop.\n"
712 "Both Loops have the same number of iterations now.\n");
713 }
714
715 /// Walk each set of strictly adjacent fusion candidates and attempt to fuse
716 /// them. This does a single linear traversal of all candidates in the list.
717 /// The conditions for legal fusion are checked at this point. If a pair of
718 /// fusion candidates passes all legality checks, they are fused together and
719 /// a new fusion candidate is created and added to the FusionCandidateList.
720 /// The original fusion candidates are then removed, as they are no longer
721 /// valid.
722 bool fuseCandidates() {
723 bool Fused = false;
724 LLVM_DEBUG(printFusionCandidates(FusionCandidates));
725 for (auto &CandidateList : FusionCandidates) {
726 if (CandidateList.size() < 2)
727 continue;
728
729 LLVM_DEBUG(dbgs() << "Attempting fusion on Candidate List:\n"
730 << CandidateList << "\n");
731
732 for (auto It = CandidateList.begin(), NextIt = std::next(It);
733 NextIt != CandidateList.end(); It = NextIt, NextIt = std::next(It)) {
734
735 auto FC0 = *It;
736 auto FC1 = *NextIt;
737
738 assert(!LDT.isRemovedLoop(FC0.L) &&
739 "Should not have removed loops in CandidateList!");
740 assert(!LDT.isRemovedLoop(FC1.L) &&
741 "Should not have removed loops in CandidateList!");
742
743 LLVM_DEBUG(dbgs() << "Attempting to fuse candidate \n"; FC0.dump();
744 dbgs() << " with\n"; FC1.dump(); dbgs() << "\n");
745
746 FC0.verify();
747 FC1.verify();
748
749 std::optional<int64_t> TCDifference = calculateTripCountDiff(FC0, FC1);
750 // Here we are checking that FC0 (the first loop) can be peeled, and
751 // the first loop has a larger trip count. In this case it is possible
752 // that the first loop is peeled to expose the fusion opportunity.
753 // Peeling the second loop is not currently supported.
754 bool WillPeel =
755 FC0.AbleToPeel && TCDifference && *TCDifference > 0 &&
756 *TCDifference <= static_cast<int64_t>(FusionPeelMaxCount);
757
758 if (!WillPeel && (!TCDifference || *TCDifference != 0)) {
759 LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical trip "
760 "counts and peeling is not supported for this "
761 "case. Not fusing.\n");
762 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
763 NonEqualTripCount);
764 continue;
765 }
766
767 if ((!FC0.GuardBranch && FC1.GuardBranch) ||
768 (FC0.GuardBranch && !FC1.GuardBranch)) {
769 LLVM_DEBUG(dbgs() << "The one of candidate is guarded while the "
770 "another one is not. Not fusing.\n");
771 reportLoopFusion<OptimizationRemarkMissed>(
772 FC0, FC1, OnlySecondCandidateIsGuarded);
773 continue;
774 }
775
776 // If TCDifference is not set or if it is zero, peeling is not needed.
777 // In this case we must ensure if the loops are guarded the guards
778 // are identical.
779 if (!TCDifference || *TCDifference == 0) {
780 if (FC0.GuardBranch && FC1.GuardBranch &&
781 !haveIdenticalGuards(FC0, FC1)) {
782 LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical "
783 "guards. Not Fusing.\n");
784 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
785 NonIdenticalGuards);
786 continue;
787 }
788 }
789
790 if (FC0.GuardBranch) {
791 assert(FC1.GuardBranch && "Expecting valid FC1 guard branch");
792
793 if (!isSafeToMoveBefore(*FC0.ExitBlock,
794 *FC1.ExitBlock->getFirstNonPHIOrDbg(), DT,
795 &PDT, &DI)) {
796 LLVM_DEBUG(dbgs() << "Fusion candidate contains unsafe "
797 "instructions in exit block. Not fusing.\n");
798 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
799 NonEmptyExitBlock);
800 continue;
801 }
802
804 *FC1.GuardBranch->getParent(),
805 *FC0.GuardBranch->getParent()->getTerminator(), DT, &PDT,
806 &DI)) {
807 LLVM_DEBUG(dbgs() << "Fusion candidate contains unsafe "
808 "instructions in guard block. Not fusing.\n");
809 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
810 NonEmptyGuardBlock);
811 continue;
812 }
813 }
814
815 // Check the dependencies across the loops and do not fuse if it would
816 // violate them.
817 if (!dependencesAllowFusion(FC0, FC1)) {
818 LLVM_DEBUG(dbgs() << "Memory dependencies do not allow fusion!\n");
819 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
820 InvalidDependencies);
821 continue;
822 }
823
824 // If the second loop has instructions in the pre-header, attempt to
825 // hoist them up to the first loop's pre-header or sink them into the
826 // body of the second loop.
827 SmallVector<Instruction *, 4> SafeToHoist;
828 SmallVector<Instruction *, 4> SafeToSink;
829 // At this point, this is the last remaining legality check.
830 // Which means if we can make this pre-header empty, we can fuse
831 // these loops
832 if (!isEmptyPreheader(FC1)) {
833 LLVM_DEBUG(dbgs() << "Fusion candidate does not have empty "
834 "preheader.\n");
835
836 // If it is not safe to hoist/sink all instructions in the
837 // pre-header, we cannot fuse these loops.
838 if (!collectMovablePreheaderInsts(FC0, FC1, SafeToHoist,
839 SafeToSink)) {
840 LLVM_DEBUG(dbgs() << "Could not hoist/sink all instructions in "
841 "Fusion Candidate Pre-header.\n"
842 << "Not Fusing.\n");
843 reportLoopFusion<OptimizationRemarkMissed>(FC0, FC1,
844 NonEmptyPreheader);
845 continue;
846 }
847 }
848
849 bool BeneficialToFuse = isBeneficialFusion(FC0, FC1);
850 LLVM_DEBUG(dbgs() << "\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
861 // Execute the hoist/sink operations on preheader instructions
862 movePreheaderInsts(FC0, FC1, SafeToHoist, SafeToSink);
863
864 LLVM_DEBUG(dbgs() << "\tFusion is performed: " << FC0 << " and " << FC1
865 << "\n");
866
867 FusionCandidate FC0Copy = FC0;
868 // Peel the loop after determining that fusion is legal. The Loops
869 // will still be safe to fuse after the peeling is performed.
870 bool Peel = TCDifference && *TCDifference > 0;
871 if (Peel)
872 peelFusionCandidate(FC0Copy, FC1, *TCDifference);
873
874 // Report fusion to the Optimization Remarks.
875 // Note this needs to be done *before* performFusion because
876 // performFusion will change the original loops, making it not
877 // possible to identify them after fusion is complete.
878 reportLoopFusion<OptimizationRemark>((Peel ? FC0Copy : FC0), FC1,
879 FuseCounter);
880
881 FusionCandidate FusedCand(performFusion((Peel ? FC0Copy : FC0), FC1),
882 DT, &PDT, ORE, FC0Copy.PP);
883 FusedCand.verify();
884 assert(FusedCand.isEligibleForFusion(SE) &&
885 "Fused candidate should be eligible for fusion!");
886
887 // Notify the loop-depth-tree that these loops are not valid objects
888 LDT.removeLoop(FC1.L);
889
890 // Replace FC0 and FC1 with their fused loop
891 It = CandidateList.erase(It);
892 It = CandidateList.erase(It);
893 It = CandidateList.insert(It, FusedCand);
894
895 // Start from FusedCand in the next iteration
896 NextIt = It;
897
898 LLVM_DEBUG(dbgs() << "Candidate List (after fusion): " << CandidateList
899 << "\n");
900
901 Fused = true;
902 }
903 }
904 return Fused;
905 }
906
907 // Returns true if the instruction \p I can be hoisted to the end of the
908 // preheader of \p FC0. \p SafeToHoist contains the instructions that are
909 // known to be safe to hoist. The instructions encountered that cannot be
910 // hoisted are in \p NotHoisting.
911 // TODO: Move functionality into CodeMoverUtils
912 bool canHoistInst(Instruction &I,
913 const SmallVector<Instruction *, 4> &SafeToHoist,
914 const SmallVector<Instruction *, 4> &NotHoisting,
915 const FusionCandidate &FC0) const {
916 const BasicBlock *FC0PreheaderTarget = FC0.Preheader->getSingleSuccessor();
917 assert(FC0PreheaderTarget &&
918 "Expected single successor for loop preheader.");
919
920 for (Use &Op : I.operands()) {
921 if (auto *OpInst = dyn_cast<Instruction>(Op)) {
922 bool OpHoisted = is_contained(SafeToHoist, OpInst);
923 // Check if we have already decided to hoist this operand. In this
924 // case, it does not dominate FC0 *yet*, but will after we hoist it.
925 if (!(OpHoisted || DT.dominates(OpInst, FC0PreheaderTarget))) {
926 return false;
927 }
928 }
929 }
930
931 // PHIs in FC1's header only have FC0 blocks as predecessors. PHIs
932 // cannot be hoisted and should be sunk to the exit of the fused loop.
933 if (isa<PHINode>(I))
934 return false;
935
936 // If this isn't a memory inst, hoisting is safe
937 if (!I.mayReadOrWriteMemory())
938 return true;
939
940 LLVM_DEBUG(dbgs() << "Checking if this mem inst can be hoisted.\n");
941 for (Instruction *NotHoistedInst : NotHoisting) {
942 if (auto D = DI.depends(&I, NotHoistedInst)) {
943 // Dependency is not read-before-write, write-before-read or
944 // write-before-write
945 if (D->isFlow() || D->isAnti() || D->isOutput()) {
946 LLVM_DEBUG(dbgs() << "Inst depends on an instruction in FC1's "
947 "preheader that is not being hoisted.\n");
948 return false;
949 }
950 }
951 }
952
953 for (Instruction *ReadInst : FC0.MemReads) {
954 if (auto D = DI.depends(ReadInst, &I)) {
955 // Dependency is not read-before-write
956 if (D->isAnti()) {
957 LLVM_DEBUG(dbgs() << "Inst depends on a read instruction in FC0.\n");
958 return false;
959 }
960 }
961 }
962
963 for (Instruction *WriteInst : FC0.MemWrites) {
964 if (auto D = DI.depends(WriteInst, &I)) {
965 // Dependency is not write-before-read or write-before-write
966 if (D->isFlow() || D->isOutput()) {
967 LLVM_DEBUG(dbgs() << "Inst depends on a write instruction in FC0.\n");
968 return false;
969 }
970 }
971 }
972 return true;
973 }
974
975 // Returns true if the instruction \p I can be sunk to the top of the exit
976 // block of \p FC1.
977 // TODO: Move functionality into CodeMoverUtils
978 bool canSinkInst(Instruction &I, const FusionCandidate &FC1) const {
979 for (User *U : I.users()) {
980 if (auto *UI{dyn_cast<Instruction>(U)}) {
981 // Cannot sink if user in loop
982 // If FC1 has phi users of this value, we cannot sink it into FC1.
983 if (FC1.L->contains(UI)) {
984 // Cannot hoist or sink this instruction. No hoisting/sinking
985 // should take place, loops should not fuse
986 return false;
987 }
988 }
989 }
990
991 // If this isn't a memory inst, sinking is safe
992 if (!I.mayReadOrWriteMemory())
993 return true;
994
995 for (Instruction *ReadInst : FC1.MemReads) {
996 if (auto D = DI.depends(&I, ReadInst)) {
997 // Dependency is not write-before-read
998 if (D->isFlow()) {
999 LLVM_DEBUG(dbgs() << "Inst depends on a read instruction in FC1.\n");
1000 return false;
1001 }
1002 }
1003 }
1004
1005 for (Instruction *WriteInst : FC1.MemWrites) {
1006 if (auto D = DI.depends(&I, WriteInst)) {
1007 // Dependency is not write-before-write or read-before-write
1008 if (D->isOutput() || D->isAnti()) {
1009 LLVM_DEBUG(dbgs() << "Inst depends on a write instruction in FC1.\n");
1010 return false;
1011 }
1012 }
1013 }
1014
1015 return true;
1016 }
1017
1018 /// Collect instructions in the \p FC1 Preheader that can be hoisted
1019 /// to the \p FC0 Preheader or sunk into the \p FC1 Body
1020 bool collectMovablePreheaderInsts(
1021 const FusionCandidate &FC0, const FusionCandidate &FC1,
1022 SmallVector<Instruction *, 4> &SafeToHoist,
1023 SmallVector<Instruction *, 4> &SafeToSink) const {
1024 BasicBlock *FC1Preheader = FC1.Preheader;
1025 // Save the instructions that are not being hoisted, so we know not to hoist
1026 // mem insts that they dominate.
1027 SmallVector<Instruction *, 4> NotHoisting;
1028
1029 for (Instruction &I : *FC1Preheader) {
1030 // Can't move a branch
1031 if (&I == FC1Preheader->getTerminator())
1032 continue;
1033 // If the instruction has side-effects, give up.
1034 // TODO: The case of mayReadFromMemory we can handle but requires
1035 // additional work with a dependence analysis so for now we give
1036 // up on memory reads.
1037 if (I.mayThrow() || !I.willReturn()) {
1038 LLVM_DEBUG(dbgs() << "Inst: " << I << " may throw or won't return.\n");
1039 return false;
1040 }
1041
1042 LLVM_DEBUG(dbgs() << "Checking Inst: " << I << "\n");
1043
1044 if (I.isAtomic() || I.isVolatile()) {
1045 LLVM_DEBUG(
1046 dbgs() << "\tInstruction is volatile or atomic. Cannot move it.\n");
1047 return false;
1048 }
1049
1050 if (canHoistInst(I, SafeToHoist, NotHoisting, FC0)) {
1051 SafeToHoist.push_back(&I);
1052 LLVM_DEBUG(dbgs() << "\tSafe to hoist.\n");
1053 } else {
1054 LLVM_DEBUG(dbgs() << "\tCould not hoist. Trying to sink...\n");
1055 NotHoisting.push_back(&I);
1056
1057 if (canSinkInst(I, FC1)) {
1058 SafeToSink.push_back(&I);
1059 LLVM_DEBUG(dbgs() << "\tSafe to sink.\n");
1060 } else {
1061 LLVM_DEBUG(dbgs() << "\tCould not sink.\n");
1062 return false;
1063 }
1064 }
1065 }
1066 LLVM_DEBUG(
1067 dbgs() << "All preheader instructions could be sunk or hoisted!\n");
1068 return true;
1069 }
1070
1071 /// Return true if the dependences between @p I0 (in @p L0) and @p I1 (in
1072 /// @p L1) allow loop fusion of @p L0 and @p L1.
1073 bool dependencesAllowFusion(const FusionCandidate &FC0,
1074 const FusionCandidate &FC1, Instruction &I0,
1075 Instruction &I1) {
1076#ifndef NDEBUG
1078 LLVM_DEBUG(dbgs() << "Check dep: " << I0 << " vs " << I1 << "\n");
1079 }
1080#endif
1081 auto DepResult = DI.depends(&I0, &I1);
1082 if (!DepResult)
1083 return true;
1084#ifndef NDEBUG
1086 LLVM_DEBUG(dbgs() << "DA res: "; DepResult->dump(dbgs());
1087 dbgs() << " [#l: " << DepResult->getLevels() << "][Ordered: "
1088 << (DepResult->isOrdered() ? "true" : "false")
1089 << "]\n");
1090 LLVM_DEBUG(dbgs() << "DepResult Levels: " << DepResult->getLevels()
1091 << "\n");
1092 }
1093#endif
1094 unsigned Levels = DepResult->getLevels();
1095 unsigned SameSDLevels = DepResult->getSameSDLevels();
1096 unsigned CurLoopLevel = FC0.L->getLoopDepth();
1097
1098 // Check if DA is missing info regarding the current loop level
1099 if (CurLoopLevel > Levels + SameSDLevels)
1100 return false;
1101
1102 // Iterating over the outer levels.
1103 for (unsigned Level = 1; Level <= std::min(CurLoopLevel - 1, Levels);
1104 ++Level) {
1105 unsigned Direction = DepResult->getDirection(Level, false);
1106
1107 // Check if the direction vector does not include equality. If an outer
1108 // loop has a non-equal direction, outer indicies are different and it
1109 // is safe to fuse.
1111 LLVM_DEBUG(dbgs() << "Safe to fuse due to non-equal acceses in the "
1112 "outer loops\n");
1113 NumDA++;
1114 return true;
1115 }
1116 }
1117
1118 assert(CurLoopLevel > Levels && "Fusion candidates are not separated");
1119
1120 if (DepResult->isScalar(CurLoopLevel, true)) {
1121 if (DepResult->isInput() || DepResult->isOutput()) {
1122 LLVM_DEBUG(dbgs() << "Safe to fuse due to a loop-invariant "
1123 << (DepResult->isInput() ? "input" : "output")
1124 << " dependency\n");
1125 NumDA++;
1126 return true;
1127 }
1128 LLVM_DEBUG(
1129 dbgs() << "Not safe to fuse due to a scalar flow dependency\n");
1130 return false;
1131 }
1132
1133 unsigned CurDir = DepResult->getDirection(CurLoopLevel, true);
1134
1135 // Check if the direction vector does not include greater direction. In
1136 // that case, the dependency is not a backward loop-carried and is legal
1137 // to fuse. For example here we have a forward dependency
1138 // for (int i = 0; i < n; i++)
1139 // A[i] = ...;
1140 // for (int i = 0; i < n; i++)
1141 // ... = A[i-1];
1142 if (!(CurDir & Dependence::DVEntry::GT)) {
1143 LLVM_DEBUG(dbgs() << "Safe to fuse with no backward loop-carried "
1144 "dependency\n");
1145 NumDA++;
1146 return true;
1147 }
1148
1149 if (DepResult->getNextPredecessor() || DepResult->getNextSuccessor())
1150 LLVM_DEBUG(dbgs() << "TODO: Implement pred/succ dependence handling!\n");
1151
1152 return false;
1153 }
1154
1155 /// Perform a dependence check and return if @p FC0 and @p FC1 can be fused.
1156 bool dependencesAllowFusion(const FusionCandidate &FC0,
1157 const FusionCandidate &FC1) {
1158 LLVM_DEBUG(dbgs() << "Check if " << FC0 << " can be fused with " << FC1
1159 << "\n");
1160 assert(FC0.L->getLoopDepth() == FC1.L->getLoopDepth());
1161 assert(DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()));
1162
1163 for (Instruction *WriteL0 : FC0.MemWrites) {
1164 for (Instruction *WriteL1 : FC1.MemWrites)
1165 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1)) {
1166 return false;
1167 }
1168 for (Instruction *ReadL1 : FC1.MemReads)
1169 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *ReadL1)) {
1170 return false;
1171 }
1172 }
1173
1174 for (Instruction *WriteL1 : FC1.MemWrites) {
1175 for (Instruction *WriteL0 : FC0.MemWrites)
1176 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1)) {
1177 return false;
1178 }
1179 for (Instruction *ReadL0 : FC0.MemReads)
1180 if (!dependencesAllowFusion(FC0, FC1, *ReadL0, *WriteL1)) {
1181 return false;
1182 }
1183 }
1184
1185 // Walk through all uses in FC1. For each use, find the reaching def. If the
1186 // def is located in FC0 then it is not safe to fuse.
1187 for (BasicBlock *BB : FC1.L->blocks())
1188 for (Instruction &I : *BB)
1189 for (auto &Op : I.operands())
1190 if (Instruction *Def = dyn_cast<Instruction>(Op))
1191 if (FC0.L->contains(Def->getParent())) {
1192 return false;
1193 }
1194
1195 return true;
1196 }
1197
1198 /// Determine if two fusion candidates are strictly adjacent in the CFG.
1199 ///
1200 /// This method will determine if there are additional basic blocks in the CFG
1201 /// between the exit of \p FC0 and the entry of \p FC1.
1202 /// If the two candidates are guarded loops, then it checks whether the
1203 /// exit block of the \p FC0 is the predecessor of the \p FC1 preheader. This
1204 /// implicitly ensures that the non-loop successor of the \p FC0 guard branch
1205 /// is the entry block of \p FC1. If not, then the loops are not adjacent. If
1206 /// the two candidates are not guarded loops, then it checks whether the exit
1207 /// block of \p FC0 is the preheader of \p FC1.
1208 /// Strictly means there is no predecessor for FC1 unless it is from FC0,
1209 /// i.e., FC0 dominates FC1.
1210 bool isStrictlyAdjacent(const FusionCandidate &FC0,
1211 const FusionCandidate &FC1) const {
1212 // If the successor of the guard branch is FC1, then the loops are adjacent
1213 if (FC0.GuardBranch)
1214 return DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock()) &&
1215 FC0.ExitBlock->getSingleSuccessor() == FC1.getEntryBlock();
1216 return FC0.ExitBlock == FC1.getEntryBlock();
1217 }
1218
1219 bool isEmptyPreheader(const FusionCandidate &FC) const {
1220 return FC.Preheader->size() == 1;
1221 }
1222
1223 /// Hoist \p FC1 Preheader instructions to \p FC0 Preheader
1224 /// and sink others into the body of \p FC1.
1225 void movePreheaderInsts(const FusionCandidate &FC0,
1226 const FusionCandidate &FC1,
1227 SmallVector<Instruction *, 4> &HoistInsts,
1228 SmallVector<Instruction *, 4> &SinkInsts) const {
1229 // All preheader instructions except the branch must be hoisted or sunk
1230 assert(HoistInsts.size() + SinkInsts.size() == FC1.Preheader->size() - 1 &&
1231 "Attempting to sink and hoist preheader instructions, but not all "
1232 "the preheader instructions are accounted for.");
1233
1234 NumHoistedInsts += HoistInsts.size();
1235 NumSunkInsts += SinkInsts.size();
1236
1238 if (!HoistInsts.empty())
1239 dbgs() << "Hoisting: \n";
1240 for (Instruction *I : HoistInsts)
1241 dbgs() << *I << "\n";
1242 if (!SinkInsts.empty())
1243 dbgs() << "Sinking: \n";
1244 for (Instruction *I : SinkInsts)
1245 dbgs() << *I << "\n";
1246 });
1247
1248 for (Instruction *I : HoistInsts) {
1249 assert(I->getParent() == FC1.Preheader);
1250 I->moveBefore(*FC0.Preheader,
1251 FC0.Preheader->getTerminator()->getIterator());
1252 }
1253 // insert instructions in reverse order to maintain dominance relationship
1254 for (Instruction *I : reverse(SinkInsts)) {
1255 assert(I->getParent() == FC1.Preheader);
1256 if (isa<PHINode>(I)) {
1257 // The Phis to be sunk should have only one incoming value, as is
1258 // assured by the condition that the second loop is dominated by the
1259 // first one which is enforced by isStrictlyAdjacent().
1260 // Replace the phi uses with the corresponding incoming value to clean
1261 // up the code.
1262 assert(cast<PHINode>(I)->getNumIncomingValues() == 1 &&
1263 "Expected the sunk PHI node to have 1 incoming value.");
1264 I->replaceAllUsesWith(I->getOperand(0));
1265 I->eraseFromParent();
1266 } else
1267 I->moveBefore(*FC1.ExitBlock, FC1.ExitBlock->getFirstInsertionPt());
1268 }
1269 }
1270
1271 /// Determine if two fusion candidates have identical guards
1272 ///
1273 /// This method will determine if two fusion candidates have the same guards.
1274 /// The guards are considered the same if:
1275 /// 1. The instructions to compute the condition used in the compare are
1276 /// identical.
1277 /// 2. The successors of the guard have the same flow into/around the loop.
1278 /// If the compare instructions are identical, then the first successor of the
1279 /// guard must go to the same place (either the preheader of the loop or the
1280 /// NonLoopBlock). In other words, the first successor of both loops must
1281 /// both go into the loop (i.e., the preheader) or go around the loop (i.e.,
1282 /// the NonLoopBlock). The same must be true for the second successor.
1283 bool haveIdenticalGuards(const FusionCandidate &FC0,
1284 const FusionCandidate &FC1) const {
1285 assert(FC0.GuardBranch && FC1.GuardBranch &&
1286 "Expecting FC0 and FC1 to be guarded loops.");
1287
1288 auto *FC0CmpInst = dyn_cast<Instruction>(FC0.GuardBranch->getCondition());
1289 auto *FC1CmpInst = dyn_cast<Instruction>(FC1.GuardBranch->getCondition());
1290 if ((!FC0CmpInst || !FC1CmpInst) &&
1291 FC0.GuardBranch->getCondition() != FC1.GuardBranch->getCondition())
1292 return false;
1293
1294 if (FC0CmpInst && FC1CmpInst && !FC0CmpInst->isIdenticalTo(FC1CmpInst))
1295 return false;
1296
1297 // The compare instructions are identical.
1298 // Now make sure the successor of the guards have the same flow into/around
1299 // the loop
1300 if (FC0.GuardBranch->getSuccessor(0) == FC0.Preheader)
1301 return (FC1.GuardBranch->getSuccessor(0) == FC1.Preheader);
1302 return (FC1.GuardBranch->getSuccessor(1) == FC1.Preheader);
1303 }
1304
1305 /// Modify the latch branch of FC to be unconditional since successors of the
1306 /// branch are the same.
1307 void simplifyLatchBranch(const FusionCandidate &FC) const {
1308 CondBrInst *FCLatchBranch = dyn_cast<CondBrInst>(FC.Latch->getTerminator());
1309 if (FCLatchBranch) {
1310 assert(FCLatchBranch->getSuccessor(0) == FCLatchBranch->getSuccessor(1) &&
1311 "Expecting the two successors of FCLatchBranch to be the same");
1312 UncondBrInst *NewBranch =
1313 UncondBrInst::Create(FCLatchBranch->getSuccessor(0));
1314 ReplaceInstWithInst(FCLatchBranch, NewBranch);
1315 }
1316 }
1317
1318 /// Move instructions from FC0.Latch to FC1.Latch. If FC0.Latch has an unique
1319 /// successor, then merge FC0.Latch with its unique successor.
1320 void mergeLatch(const FusionCandidate &FC0, const FusionCandidate &FC1) {
1321 moveInstructionsToTheBeginning(*FC0.Latch, *FC1.Latch, DT, PDT, DI, SE);
1322 if (BasicBlock *Succ = FC0.Latch->getUniqueSuccessor()) {
1323 MergeBlockIntoPredecessor(Succ, &DTU, &LI);
1324 DTU.flush();
1325 }
1326 }
1327
1328 /// Fuse two fusion candidates, creating a new fused loop.
1329 ///
1330 /// This method contains the mechanics of fusing two loops, represented by \p
1331 /// FC0 and \p FC1. It is assumed that \p FC0 dominates \p FC1 and \p FC1
1332 /// postdominates \p FC0 (making them control flow equivalent). It also
1333 /// assumes that the other conditions for fusion have been met: adjacent,
1334 /// identical trip counts, and no negative distance dependencies exist that
1335 /// would prevent fusion. Thus, there is no checking for these conditions in
1336 /// this method.
1337 ///
1338 /// Fusion is performed by rewiring the CFG to update successor blocks of the
1339 /// components of tho loop. Specifically, the following changes are done:
1340 ///
1341 /// 1. The preheader of \p FC1 is removed as it is no longer necessary
1342 /// (because it is currently only a single statement block).
1343 /// 2. The latch of \p FC0 is modified to jump to the header of \p FC1.
1344 /// 3. The latch of \p FC1 i modified to jump to the header of \p FC0.
1345 /// 4. All blocks from \p FC1 are removed from FC1 and added to FC0.
1346 ///
1347 /// All of these modifications are done with dominator tree updates, thus
1348 /// keeping the dominator (and post dominator) information up-to-date.
1349 ///
1350 /// This can be improved in the future by actually merging blocks during
1351 /// fusion. For example, the preheader of \p FC1 can be merged with the
1352 /// preheader of \p FC0. This would allow loops with more than a single
1353 /// statement in the preheader to be fused. Similarly, the latch blocks of the
1354 /// two loops could also be fused into a single block. This will require
1355 /// analysis to prove it is safe to move the contents of the block past
1356 /// existing code, which currently has not been implemented.
1357 Loop *performFusion(const FusionCandidate &FC0, const FusionCandidate &FC1) {
1358 assert(FC0.isValid() && FC1.isValid() &&
1359 "Expecting valid fusion candidates");
1360
1361 LLVM_DEBUG(dbgs() << "Fusion Candidate 0: \n"; FC0.dump();
1362 dbgs() << "Fusion Candidate 1: \n"; FC1.dump(););
1363
1364 // Move instructions from the preheader of FC1 to the end of the preheader
1365 // of FC0.
1366 moveInstructionsToTheEnd(*FC1.Preheader, *FC0.Preheader, DT, PDT, DI, SE);
1367
1368 // Fusing guarded loops is handled slightly differently than non-guarded
1369 // loops and has been broken out into a separate method instead of trying to
1370 // intersperse the logic within a single method.
1371 if (FC0.GuardBranch)
1372 return fuseGuardedLoops(FC0, FC1);
1373
1374 assert(FC1.Preheader ==
1375 (FC0.Peeled ? FC0.ExitBlock->getUniqueSuccessor() : FC0.ExitBlock));
1376 assert(FC1.Preheader->size() == 1 &&
1377 FC1.Preheader->getSingleSuccessor() == FC1.Header);
1378
1379 // Remember the phi nodes originally in the header of FC0 in order to rewire
1380 // them later. However, this is only necessary if the new loop carried
1381 // values might not dominate the exiting branch. While we do not generally
1382 // test if this is the case but simply insert intermediate phi nodes, we
1383 // need to make sure these intermediate phi nodes have different
1384 // predecessors. To this end, we filter the special case where the exiting
1385 // block is the latch block of the first loop. Nothing needs to be done
1386 // anyway as all loop carried values dominate the latch and thereby also the
1387 // exiting branch.
1388 SmallVector<PHINode *, 8> OriginalFC0PHIs;
1389 if (FC0.ExitingBlock != FC0.Latch)
1390 for (PHINode &PHI : FC0.Header->phis())
1391 OriginalFC0PHIs.push_back(&PHI);
1392
1393 // Replace incoming blocks for header PHIs first.
1394 FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
1395 FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
1396
1397 // Then modify the control flow and update DT and PDT.
1399
1400 // The old exiting block of the first loop (FC0) has to jump to the header
1401 // of the second as we need to execute the code in the second header block
1402 // regardless of the trip count. That is, if the trip count is 0, so the
1403 // back edge is never taken, we still have to execute both loop headers,
1404 // especially (but not only!) if the second is a do-while style loop.
1405 // However, doing so might invalidate the phi nodes of the first loop as
1406 // the new values do only need to dominate their latch and not the exiting
1407 // predicate. To remedy this potential problem we always introduce phi
1408 // nodes in the header of the second loop later that select the loop carried
1409 // value, if the second header was reached through an old latch of the
1410 // first, or undef otherwise. This is sound as exiting the first implies the
1411 // second will exit too, __without__ taking the back-edge. [Their
1412 // trip-counts are equal after all.
1413 // KB: Would this sequence be simpler to just make FC0.ExitingBlock go
1414 // to FC1.Header? I think this is basically what the three sequences are
1415 // trying to accomplish; however, doing this directly in the CFG may mean
1416 // the DT/PDT becomes invalid
1417 if (!FC0.Peeled) {
1418 FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC1.Preheader,
1419 FC1.Header);
1420 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1421 DominatorTree::Delete, FC0.ExitingBlock, FC1.Preheader));
1422 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1423 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1424 } else {
1425 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1426 DominatorTree::Delete, FC0.ExitBlock, FC1.Preheader));
1427
1428 // Remove the ExitBlock of the first Loop (also not needed)
1429 FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC0.ExitBlock,
1430 FC1.Header);
1431 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1432 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1433 FC0.ExitBlock->getTerminator()->eraseFromParent();
1434 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1435 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1436 new UnreachableInst(FC0.ExitBlock->getContext(), FC0.ExitBlock);
1437 }
1438
1439 // The pre-header of L1 is not necessary anymore.
1440 assert(pred_empty(FC1.Preheader));
1441 FC1.Preheader->getTerminator()->eraseFromParent();
1442 new UnreachableInst(FC1.Preheader->getContext(), FC1.Preheader);
1443 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1444 DominatorTree::Delete, FC1.Preheader, FC1.Header));
1445
1446 // Moves the phi nodes from the second to the first loops header block.
1447 while (PHINode *PHI = dyn_cast<PHINode>(&FC1.Header->front())) {
1448 if (SE.isSCEVable(PHI->getType()))
1449 SE.forgetValue(PHI);
1450 if (PHI->hasNUsesOrMore(1))
1451 PHI->moveBefore(FC0.Header->getFirstInsertionPt());
1452 else
1453 PHI->eraseFromParent();
1454 }
1455
1456 // Introduce new phi nodes in the second loop header to ensure
1457 // exiting the first and jumping to the header of the second does not break
1458 // the SSA property of the phis originally in the first loop. See also the
1459 // comment above.
1460 BasicBlock::iterator L1HeaderIP = FC1.Header->begin();
1461 for (PHINode *LCPHI : OriginalFC0PHIs) {
1462 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1463 assert(L1LatchBBIdx >= 0 &&
1464 "Expected loop carried value to be rewired at this point!");
1465
1466 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1467
1468 PHINode *L1HeaderPHI =
1469 PHINode::Create(LCV->getType(), 2, LCPHI->getName() + ".afterFC0");
1470 L1HeaderPHI->insertBefore(L1HeaderIP);
1471 L1HeaderPHI->addIncoming(LCV, FC0.Latch);
1472 L1HeaderPHI->addIncoming(PoisonValue::get(LCV->getType()),
1473 FC0.ExitingBlock);
1474
1475 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1476 }
1477
1478 // Replace latch terminator destinations.
1479 FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header);
1480 FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header);
1481
1482 // Modify the latch branch of FC0 to be unconditional as both successors of
1483 // the branch are the same.
1484 simplifyLatchBranch(FC0);
1485
1486 // If FC0.Latch and FC0.ExitingBlock are the same then we have already
1487 // performed the updates above.
1488 if (FC0.Latch != FC0.ExitingBlock)
1489 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1490 DominatorTree::Insert, FC0.Latch, FC1.Header));
1491
1492 TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1493 FC0.Latch, FC0.Header));
1494 TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
1495 FC1.Latch, FC0.Header));
1496 TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1497 FC1.Latch, FC1.Header));
1498
1499 // Update DT/PDT
1500 DTU.applyUpdates(TreeUpdates);
1501
1502 LI.removeBlock(FC1.Preheader);
1503 DTU.deleteBB(FC1.Preheader);
1504 if (FC0.Peeled) {
1505 LI.removeBlock(FC0.ExitBlock);
1506 DTU.deleteBB(FC0.ExitBlock);
1507 }
1508
1509 DTU.flush();
1510
1511 // Is there a way to keep SE up-to-date so we don't need to forget the loops
1512 // and rebuild the information in subsequent passes of fusion?
1513 // Note: Need to forget the loops before merging the loop latches, as
1514 // mergeLatch may remove the only block in FC1.
1515 SE.forgetLoop(FC1.L);
1516 SE.forgetLoop(FC0.L);
1517
1518 // Merge the loops.
1519 SmallVector<BasicBlock *, 8> Blocks(FC1.L->blocks());
1520 for (BasicBlock *BB : Blocks) {
1521 FC0.L->addBlockEntry(BB);
1522 FC1.L->removeBlockFromLoop(BB);
1523 if (LI.getLoopFor(BB) != FC1.L)
1524 continue;
1525 LI.changeLoopFor(BB, FC0.L);
1526 }
1527 while (!FC1.L->isInnermost()) {
1528 const auto &ChildLoopIt = FC1.L->begin();
1529 Loop *ChildLoop = *ChildLoopIt;
1530 FC1.L->removeChildLoop(ChildLoopIt);
1531 FC0.L->addChildLoop(ChildLoop);
1532 }
1533
1534 // Delete the now empty loop L1.
1535 LI.erase(FC1.L);
1536
1537 // Forget block dispositions as well, so that there are no dangling
1538 // pointers to erased/free'ed blocks. It should be done after mergeLatch()
1539 // since merging the latches may affect the dispositions.
1540 SE.forgetBlockAndLoopDispositions();
1541
1542 // Move instructions from FC0.Latch to FC1.Latch.
1543 // Note: mergeLatch requires an updated DT.
1544 mergeLatch(FC0, FC1);
1545
1546#ifndef NDEBUG
1547 assert(!verifyFunction(*FC0.Header->getParent(), &errs()));
1548 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1549 assert(PDT.verify());
1550 LI.verify(DT);
1551 SE.verify();
1552#endif
1553
1554 LLVM_DEBUG(dbgs() << "Fusion done:\n");
1555
1556 return FC0.L;
1557 }
1558
1559 /// Report details on loop fusion opportunities.
1560 ///
1561 /// This template function can be used to report both successful and missed
1562 /// loop fusion opportunities, based on the RemarkKind. The RemarkKind should
1563 /// be one of:
1564 /// - OptimizationRemarkMissed to report when loop fusion is unsuccessful
1565 /// given two valid fusion candidates.
1566 /// - OptimizationRemark to report successful fusion of two fusion
1567 /// candidates.
1568 /// The remarks will be printed using the form:
1569 /// <path/filename>:<line number>:<column number>: [<function name>]:
1570 /// <Cand1 Preheader> and <Cand2 Preheader>: <Stat Description>
1571 template <typename RemarkKind>
1572 void reportLoopFusion(const FusionCandidate &FC0, const FusionCandidate &FC1,
1573 Statistic &Stat) {
1574 assert(FC0.Preheader && FC1.Preheader &&
1575 "Expecting valid fusion candidates");
1576 using namespace ore;
1577#if LLVM_ENABLE_STATS
1578 ++Stat;
1579 ORE.emit(RemarkKind(DEBUG_TYPE, Stat.getName(), FC0.L->getStartLoc(),
1580 FC0.Preheader)
1581 << "[" << FC0.Preheader->getParent()->getName()
1582 << "]: " << NV("Cand1", StringRef(FC0.Preheader->getName()))
1583 << " and " << NV("Cand2", StringRef(FC1.Preheader->getName()))
1584 << ": " << Stat.getDesc());
1585#endif
1586 }
1587
1588 /// Fuse two guarded fusion candidates, creating a new fused loop.
1589 ///
1590 /// Fusing guarded loops is handled much the same way as fusing non-guarded
1591 /// loops. The rewiring of the CFG is slightly different though, because of
1592 /// the presence of the guards around the loops and the exit blocks after the
1593 /// loop body. As such, the new loop is rewired as follows:
1594 /// 1. Keep the guard branch from FC0 and use the non-loop block target
1595 /// from the FC1 guard branch.
1596 /// 2. Remove the exit block from FC0 (this exit block should be empty
1597 /// right now).
1598 /// 3. Remove the guard branch for FC1
1599 /// 4. Remove the preheader for FC1.
1600 /// The exit block successor for the latch of FC0 is updated to be the header
1601 /// of FC1 and the non-exit block successor of the latch of FC1 is updated to
1602 /// be the header of FC0, thus creating the fused loop.
1603 Loop *fuseGuardedLoops(const FusionCandidate &FC0,
1604 const FusionCandidate &FC1) {
1605 assert(FC0.GuardBranch && FC1.GuardBranch && "Expecting guarded loops");
1606
1607 BasicBlock *FC0GuardBlock = FC0.GuardBranch->getParent();
1608 BasicBlock *FC1GuardBlock = FC1.GuardBranch->getParent();
1609 BasicBlock *FC0NonLoopBlock = FC0.getNonLoopBlock();
1610 BasicBlock *FC1NonLoopBlock = FC1.getNonLoopBlock();
1611 BasicBlock *FC0ExitBlockSuccessor = FC0.ExitBlock->getUniqueSuccessor();
1612
1613 // Move instructions from the exit block of FC0 to the beginning of the exit
1614 // block of FC1, in the case that the FC0 loop has not been peeled. In the
1615 // case that FC0 loop is peeled, then move the instructions of the successor
1616 // of the FC0 Exit block to the beginning of the exit block of FC1.
1618 (FC0.Peeled ? *FC0ExitBlockSuccessor : *FC0.ExitBlock), *FC1.ExitBlock,
1619 DT, PDT, DI, SE);
1620
1621 // Move instructions from the guard block of FC1 to the end of the guard
1622 // block of FC0.
1623 moveInstructionsToTheEnd(*FC1GuardBlock, *FC0GuardBlock, DT, PDT, DI, SE);
1624
1625 assert(FC0NonLoopBlock == FC1GuardBlock && "Loops are not adjacent");
1626
1628
1629 ////////////////////////////////////////////////////////////////////////////
1630 // Update the Loop Guard
1631 ////////////////////////////////////////////////////////////////////////////
1632 // The guard for FC0 is updated to guard both FC0 and FC1. This is done by
1633 // changing the NonLoopGuardBlock for FC0 to the NonLoopGuardBlock for FC1.
1634 // Thus, one path from the guard goes to the preheader for FC0 (and thus
1635 // executes the new fused loop) and the other path goes to the NonLoopBlock
1636 // for FC1 (where FC1 guard would have gone if FC1 was not executed).
1637 FC1NonLoopBlock->replacePhiUsesWith(FC1GuardBlock, FC0GuardBlock);
1638 FC0.GuardBranch->replaceUsesOfWith(FC0NonLoopBlock, FC1NonLoopBlock);
1639
1640 BasicBlock *BBToUpdate = FC0.Peeled ? FC0ExitBlockSuccessor : FC0.ExitBlock;
1641 BBToUpdate->getTerminator()->replaceUsesOfWith(FC1GuardBlock, FC1.Header);
1642
1643 // The guard of FC1 is not necessary anymore.
1644 FC1.GuardBranch->eraseFromParent();
1645 new UnreachableInst(FC1GuardBlock->getContext(), FC1GuardBlock);
1646
1647 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1648 DominatorTree::Delete, FC1GuardBlock, FC1.Preheader));
1649 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1650 DominatorTree::Delete, FC1GuardBlock, FC1NonLoopBlock));
1651 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1652 DominatorTree::Delete, FC0GuardBlock, FC1GuardBlock));
1653 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1654 DominatorTree::Insert, FC0GuardBlock, FC1NonLoopBlock));
1655
1656 if (FC0.Peeled) {
1657 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1658 DominatorTree::Delete, FC0.ExitBlock, FC0ExitBlockSuccessor));
1659 // Remove the Block after the ExitBlock of FC0
1660 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1661 DominatorTree::Delete, FC0ExitBlockSuccessor, FC1GuardBlock));
1662 FC0ExitBlockSuccessor->getTerminator()->eraseFromParent();
1663 new UnreachableInst(FC0ExitBlockSuccessor->getContext(),
1664 FC0ExitBlockSuccessor);
1665 }
1666
1667 assert(pred_empty(FC1GuardBlock) &&
1668 "Expecting guard block to have no predecessors");
1669 assert(succ_empty(FC1GuardBlock) &&
1670 "Expecting guard block to have no successors");
1671
1672 // Remember the phi nodes originally in the header of FC0 in order to rewire
1673 // them later. However, this is only necessary if the new loop carried
1674 // values might not dominate the exiting branch. While we do not generally
1675 // test if this is the case but simply insert intermediate phi nodes, we
1676 // need to make sure these intermediate phi nodes have different
1677 // predecessors. To this end, we filter the special case where the exiting
1678 // block is the latch block of the first loop. Nothing needs to be done
1679 // anyway as all loop carried values dominate the latch and thereby also the
1680 // exiting branch.
1681 // KB: This is no longer necessary because FC0.ExitingBlock == FC0.Latch
1682 // (because the loops are rotated. Thus, nothing will ever be added to
1683 // OriginalFC0PHIs.
1684 SmallVector<PHINode *, 8> OriginalFC0PHIs;
1685 if (FC0.ExitingBlock != FC0.Latch)
1686 for (PHINode &PHI : FC0.Header->phis())
1687 OriginalFC0PHIs.push_back(&PHI);
1688
1689 assert(OriginalFC0PHIs.empty() && "Expecting OriginalFC0PHIs to be empty!");
1690
1691 // Replace incoming blocks for header PHIs first.
1692 FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader);
1693 FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch);
1694
1695 // The old exiting block of the first loop (FC0) has to jump to the header
1696 // of the second as we need to execute the code in the second header block
1697 // regardless of the trip count. That is, if the trip count is 0, so the
1698 // back edge is never taken, we still have to execute both loop headers,
1699 // especially (but not only!) if the second is a do-while style loop.
1700 // However, doing so might invalidate the phi nodes of the first loop as
1701 // the new values do only need to dominate their latch and not the exiting
1702 // predicate. To remedy this potential problem we always introduce phi
1703 // nodes in the header of the second loop later that select the loop carried
1704 // value, if the second header was reached through an old latch of the
1705 // first, or undef otherwise. This is sound as exiting the first implies the
1706 // second will exit too, __without__ taking the back-edge (their
1707 // trip-counts are equal after all).
1708 FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC0.ExitBlock,
1709 FC1.Header);
1710
1711 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1712 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock));
1713 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1714 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header));
1715
1716 // Remove FC0 Exit Block
1717 // The exit block for FC0 is no longer needed since control will flow
1718 // directly to the header of FC1. Since it is an empty block, it can be
1719 // removed at this point.
1720 // TODO: In the future, we can handle non-empty exit blocks my merging any
1721 // instructions from FC0 exit block into FC1 exit block prior to removing
1722 // the block.
1723 assert(pred_empty(FC0.ExitBlock) && "Expecting exit block to be empty");
1724 FC0.ExitBlock->getTerminator()->eraseFromParent();
1725 new UnreachableInst(FC0.ExitBlock->getContext(), FC0.ExitBlock);
1726
1727 // Remove FC1 Preheader
1728 // The pre-header of L1 is not necessary anymore.
1729 assert(pred_empty(FC1.Preheader));
1730 FC1.Preheader->getTerminator()->eraseFromParent();
1731 new UnreachableInst(FC1.Preheader->getContext(), FC1.Preheader);
1732 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1733 DominatorTree::Delete, FC1.Preheader, FC1.Header));
1734
1735 // Moves the phi nodes from the second to the first loops header block.
1736 while (PHINode *PHI = dyn_cast<PHINode>(&FC1.Header->front())) {
1737 if (SE.isSCEVable(PHI->getType()))
1738 SE.forgetValue(PHI);
1739 if (PHI->hasNUsesOrMore(1))
1740 PHI->moveBefore(FC0.Header->getFirstInsertionPt());
1741 else
1742 PHI->eraseFromParent();
1743 }
1744
1745 // Introduce new phi nodes in the second loop header to ensure
1746 // exiting the first and jumping to the header of the second does not break
1747 // the SSA property of the phis originally in the first loop. See also the
1748 // comment above.
1749 BasicBlock::iterator L1HeaderIP = FC1.Header->begin();
1750 for (PHINode *LCPHI : OriginalFC0PHIs) {
1751 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch);
1752 assert(L1LatchBBIdx >= 0 &&
1753 "Expected loop carried value to be rewired at this point!");
1754
1755 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx);
1756
1757 PHINode *L1HeaderPHI =
1758 PHINode::Create(LCV->getType(), 2, LCPHI->getName() + ".afterFC0");
1759 L1HeaderPHI->insertBefore(L1HeaderIP);
1760 L1HeaderPHI->addIncoming(LCV, FC0.Latch);
1761 L1HeaderPHI->addIncoming(PoisonValue::get(LCV->getType()),
1762 FC0.ExitingBlock);
1763
1764 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI);
1765 }
1766
1767 // Update the latches
1768
1769 // Replace latch terminator destinations.
1770 FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header);
1771 FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header);
1772
1773 // Modify the latch branch of FC0 to be unconditional as both successors of
1774 // the branch are the same.
1775 simplifyLatchBranch(FC0);
1776
1777 // If FC0.Latch and FC0.ExitingBlock are the same then we have already
1778 // performed the updates above.
1779 if (FC0.Latch != FC0.ExitingBlock)
1780 TreeUpdates.emplace_back(DominatorTree::UpdateType(
1781 DominatorTree::Insert, FC0.Latch, FC1.Header));
1782
1783 TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1784 FC0.Latch, FC0.Header));
1785 TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Insert,
1786 FC1.Latch, FC0.Header));
1787 TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete,
1788 FC1.Latch, FC1.Header));
1789
1790 // All done
1791 // Apply the updates to the Dominator Tree and cleanup.
1792
1793 assert(succ_empty(FC1GuardBlock) && "FC1GuardBlock has successors!!");
1794 assert(pred_empty(FC1GuardBlock) && "FC1GuardBlock has predecessors!!");
1795
1796 // Update DT/PDT
1797 DTU.applyUpdates(TreeUpdates);
1798
1799 LI.removeBlock(FC1GuardBlock);
1800 LI.removeBlock(FC1.Preheader);
1801 LI.removeBlock(FC0.ExitBlock);
1802 if (FC0.Peeled) {
1803 LI.removeBlock(FC0ExitBlockSuccessor);
1804 DTU.deleteBB(FC0ExitBlockSuccessor);
1805 }
1806 DTU.deleteBB(FC1GuardBlock);
1807 DTU.deleteBB(FC1.Preheader);
1808 DTU.deleteBB(FC0.ExitBlock);
1809 DTU.flush();
1810
1811 // Is there a way to keep SE up-to-date so we don't need to forget the loops
1812 // and rebuild the information in subsequent passes of fusion?
1813 // Note: Need to forget the loops before merging the loop latches, as
1814 // mergeLatch may remove the only block in FC1.
1815 SE.forgetLoop(FC1.L);
1816 SE.forgetLoop(FC0.L);
1817
1818 // Merge the loops.
1819 SmallVector<BasicBlock *, 8> Blocks(FC1.L->blocks());
1820 for (BasicBlock *BB : Blocks) {
1821 FC0.L->addBlockEntry(BB);
1822 FC1.L->removeBlockFromLoop(BB);
1823 if (LI.getLoopFor(BB) != FC1.L)
1824 continue;
1825 LI.changeLoopFor(BB, FC0.L);
1826 }
1827 while (!FC1.L->isInnermost()) {
1828 const auto &ChildLoopIt = FC1.L->begin();
1829 Loop *ChildLoop = *ChildLoopIt;
1830 FC1.L->removeChildLoop(ChildLoopIt);
1831 FC0.L->addChildLoop(ChildLoop);
1832 }
1833
1834 // Delete the now empty loop L1.
1835 LI.erase(FC1.L);
1836
1837 // Forget block dispositions as well, so that there are no dangling
1838 // pointers to erased/free'ed blocks. It should be done after mergeLatch()
1839 // since merging the latches may affect the dispositions.
1840 SE.forgetBlockAndLoopDispositions();
1841
1842 // Move instructions from FC0.Latch to FC1.Latch.
1843 // Note: mergeLatch requires an updated DT.
1844 mergeLatch(FC0, FC1);
1845
1846#ifndef NDEBUG
1847 assert(!verifyFunction(*FC0.Header->getParent(), &errs()));
1848 assert(DT.verify(DominatorTree::VerificationLevel::Fast));
1849 assert(PDT.verify());
1850 LI.verify(DT);
1851 SE.verify();
1852#endif
1853
1854 LLVM_DEBUG(dbgs() << "Fusion done:\n");
1855
1856 return FC0.L;
1857 }
1858};
1859} // namespace
1860
1862 auto &LI = AM.getResult<LoopAnalysis>(F);
1863 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1864 auto &DI = AM.getResult<DependenceAnalysis>(F);
1865 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
1866 auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
1868 auto &AC = AM.getResult<AssumptionAnalysis>(F);
1870 const DataLayout &DL = F.getDataLayout();
1871
1872 // Ensure loops are in simplifed form which is a pre-requisite for loop fusion
1873 // pass. Added only for new PM since the legacy PM has already added
1874 // LoopSimplify pass as a dependency.
1875 bool Changed = false;
1876 for (auto &L : LI) {
1877 Changed |=
1878 simplifyLoop(L, &DT, &LI, &SE, &AC, nullptr, false /* PreserveLCSSA */);
1879 }
1880 if (Changed)
1881 PDT.recalculate(F);
1882
1883 LoopFuser LF(LI, DT, DI, SE, PDT, ORE, DL, AC, TTI);
1884 Changed |= LF.fuseLoops(F);
1885 if (!Changed)
1886 return PreservedAnalyses::all();
1887
1892 PA.preserve<LoopAnalysis>();
1893 return PA;
1894}
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static bool reportInvalidCandidate(const Instruction &I, llvm::Statistic &Stat)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:661
#define DEBUG_TYPE
static cl::opt< uint32_t > FusionPeelMaxCount("loop-fusion-peel-max-count", cl::init(0), cl::Hidden, cl::desc("Max number of iterations to be peeled from a loop, such that " "fusion can take place"))
static void printFusionCandidates(const FusionCandidateCollection &FusionCandidates)
Definition LoopFuse.cpp:382
std::list< FusionCandidate > FusionCandidateList
Definition LoopFuse.cpp:353
SmallVector< FusionCandidateList, 4 > FusionCandidateCollection
Definition LoopFuse.cpp:354
static void printLoopVector(const LoopVector &LV)
Definition LoopFuse.cpp:357
SmallVector< Loop *, 4 > LoopVector
Definition LoopFuse.cpp:348
static cl::opt< bool > VerboseFusionDebugging("loop-fusion-verbose-debug", cl::desc("Enable verbose debugging for Loop Fusion"), cl::Hidden, cl::init(false))
#define DEBUG_TYPE
Definition LoopFuse.cpp:70
This file implements the Loop Fusion pass.
Loop::LoopBounds::Direction Direction
Definition LoopInfo.cpp:253
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
ppc ctr loops verify
static bool isValid(const char C)
Returns true if C is a valid mangled character: <0-9a-zA-Z_>.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
A function analysis which provides an AssumptionCache.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI void replaceSuccessorsPhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block's successors to refer to basic block New instead of basic bl...
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:461
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:530
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
const Instruction & front() const
Definition BasicBlock.h:484
LLVM_ABI void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
size_t size() const
Definition BasicBlock.h:482
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Conditional Branch instruction.
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
AnalysisPass to compute dependence information in a function.
Analysis pass which computes a DominatorTree.
Definition Dominators.h:274
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:155
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:587
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
bool isInnermost() const
Return true if the loop does not contain any (natural) loops.
void removeBlockFromLoop(BlockT *BB)
This removes the specified basic block from the current loop, updating the Blocks as appropriate.
unsigned getLoopDepth() const
Return the nesting level of this loop.
iterator_range< block_iterator > blocks() const
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
void addBlockEntry(BlockT *BB)
This adds a basic block directly to the basic block list.
iterator begin() const
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
reverse_iterator rend() const
reverse_iterator rbegin() const
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
Definition LoopInfo.cpp:659
Diagnostic information for optimization analysis remarks.
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Analysis pass which computes a PostDominatorTree.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
Analysis pass that exposes the ScalarEvolution for a function.
The main scalar evolution driver.
LLVM_ABI bool hasLoopInvariantBackedgeTakenCount(const Loop *L)
Return true if the specified loop has an analyzable loop-invariant backedge-taken count.
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Analysis pass providing the TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:25
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Changed
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
bool empty() const
Definition BasicBlock.h:101
iterator end() const
Definition BasicBlock.h:89
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
LLVM_ABI void ReplaceInstWithInst(BasicBlock *BB, BasicBlock::iterator &BI, Instruction *I)
Replace the instruction specified by BI with the instruction specified by I.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1668
bool succ_empty(const Instruction *I)
Definition CFG.h:141
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
LLVM_ABI void moveInstructionsToTheEnd(BasicBlock &FromBB, BasicBlock &ToBB, DominatorTree &DT, const PostDominatorTree &PDT, DependenceInfo &DI, ScalarEvolution &SE)
Move instructions, in an order-preserving manner, from FromBB to the end of ToBB when proven safe.
LLVM_ABI void moveInstructionsToTheBeginning(BasicBlock &FromBB, BasicBlock &ToBB, DominatorTree &DT, const PostDominatorTree &PDT, DependenceInfo &DI, ScalarEvolution &SE)
Move instructions, in an order-preserving manner, from FromBB to the beginning of ToBB when proven sa...
LLVM_ABI bool canPeel(const Loop *L)
Definition LoopPeel.cpp:97
NoopStatistic Statistic
Definition Statistic.h:162
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
LLVM_ABI TargetTransformInfo::PeelingPreferences gatherPeelingPreferences(Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, std::optional< bool > UserAllowPeeling, std::optional< bool > UserAllowProfileBasedPeeling, bool UnrollingSpecficValues=false)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI void peelLoop(Loop *L, unsigned PeelCount, bool PeelLast, LoopInfo *LI, ScalarEvolution *SE, DominatorTree &DT, AssumptionCache *AC, bool PreserveLCSSA, ValueToValueMapTy &VMap)
VMap is the value-map that maps instructions from the original loop to instructions in the last peele...
TargetTransformInfo TTI
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
LLVM_ABI void printLoop(const Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop's contents as LLVM's text IR assembly.
DWARFExpression::Operation Op
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1946
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI bool isSafeToMoveBefore(Instruction &I, Instruction &InsertPoint, DominatorTree &DT, const PostDominatorTree *PDT=nullptr, DependenceInfo *DI=nullptr, bool CheckForEntireBlock=false)
Return true if I can be safely moved before InsertPoint.
unsigned PeelCount
A forced peeling factor (the number of bodied of the original loop that should be peeled off before t...