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