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