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