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