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 47 #include "llvm/Transforms/Scalar/LoopFuse.h" 48 #include "llvm/ADT/Statistic.h" 49 #include "llvm/Analysis/DependenceAnalysis.h" 50 #include "llvm/Analysis/DomTreeUpdater.h" 51 #include "llvm/Analysis/LoopInfo.h" 52 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 53 #include "llvm/Analysis/PostDominators.h" 54 #include "llvm/Analysis/ScalarEvolution.h" 55 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 56 #include "llvm/IR/Function.h" 57 #include "llvm/IR/Verifier.h" 58 #include "llvm/InitializePasses.h" 59 #include "llvm/Pass.h" 60 #include "llvm/Support/CommandLine.h" 61 #include "llvm/Support/Debug.h" 62 #include "llvm/Support/raw_ostream.h" 63 #include "llvm/Transforms/Scalar.h" 64 #include "llvm/Transforms/Utils.h" 65 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 66 #include "llvm/Transforms/Utils/CodeMoverUtils.h" 67 68 using namespace llvm; 69 70 #define DEBUG_TYPE "loop-fusion" 71 72 STATISTIC(FuseCounter, "Loops fused"); 73 STATISTIC(NumFusionCandidates, "Number of candidates for loop fusion"); 74 STATISTIC(InvalidPreheader, "Loop has invalid preheader"); 75 STATISTIC(InvalidHeader, "Loop has invalid header"); 76 STATISTIC(InvalidExitingBlock, "Loop has invalid exiting blocks"); 77 STATISTIC(InvalidExitBlock, "Loop has invalid exit block"); 78 STATISTIC(InvalidLatch, "Loop has invalid latch"); 79 STATISTIC(InvalidLoop, "Loop is invalid"); 80 STATISTIC(AddressTakenBB, "Basic block has address taken"); 81 STATISTIC(MayThrowException, "Loop may throw an exception"); 82 STATISTIC(ContainsVolatileAccess, "Loop contains a volatile access"); 83 STATISTIC(NotSimplifiedForm, "Loop is not in simplified form"); 84 STATISTIC(InvalidDependencies, "Dependencies prevent fusion"); 85 STATISTIC(UnknownTripCount, "Loop has unknown trip count"); 86 STATISTIC(UncomputableTripCount, "SCEV cannot compute trip count of loop"); 87 STATISTIC(NonEqualTripCount, "Loop trip counts are not the same"); 88 STATISTIC(NonAdjacent, "Loops are not adjacent"); 89 STATISTIC( 90 NonEmptyPreheader, 91 "Loop has a non-empty preheader with instructions that cannot be moved"); 92 STATISTIC(FusionNotBeneficial, "Fusion is not beneficial"); 93 STATISTIC(NonIdenticalGuards, "Candidates have different guards"); 94 STATISTIC(NonEmptyExitBlock, "Candidate has a non-empty exit block"); 95 STATISTIC(NonEmptyGuardBlock, "Candidate has a non-empty guard block"); 96 STATISTIC(NotRotated, "Candidate is not rotated"); 97 98 enum FusionDependenceAnalysisChoice { 99 FUSION_DEPENDENCE_ANALYSIS_SCEV, 100 FUSION_DEPENDENCE_ANALYSIS_DA, 101 FUSION_DEPENDENCE_ANALYSIS_ALL, 102 }; 103 104 static cl::opt<FusionDependenceAnalysisChoice> FusionDependenceAnalysis( 105 "loop-fusion-dependence-analysis", 106 cl::desc("Which dependence analysis should loop fusion use?"), 107 cl::values(clEnumValN(FUSION_DEPENDENCE_ANALYSIS_SCEV, "scev", 108 "Use the scalar evolution interface"), 109 clEnumValN(FUSION_DEPENDENCE_ANALYSIS_DA, "da", 110 "Use the dependence analysis interface"), 111 clEnumValN(FUSION_DEPENDENCE_ANALYSIS_ALL, "all", 112 "Use all available analyses")), 113 cl::Hidden, cl::init(FUSION_DEPENDENCE_ANALYSIS_ALL), cl::ZeroOrMore); 114 115 #ifndef NDEBUG 116 static cl::opt<bool> 117 VerboseFusionDebugging("loop-fusion-verbose-debug", 118 cl::desc("Enable verbose debugging for Loop Fusion"), 119 cl::Hidden, cl::init(false), cl::ZeroOrMore); 120 #endif 121 122 namespace { 123 /// This class is used to represent a candidate for loop fusion. When it is 124 /// constructed, it checks the conditions for loop fusion to ensure that it 125 /// represents a valid candidate. It caches several parts of a loop that are 126 /// used throughout loop fusion (e.g., loop preheader, loop header, etc) instead 127 /// of continually querying the underlying Loop to retrieve these values. It is 128 /// assumed these will not change throughout loop fusion. 129 /// 130 /// The invalidate method should be used to indicate that the FusionCandidate is 131 /// no longer a valid candidate for fusion. Similarly, the isValid() method can 132 /// be used to ensure that the FusionCandidate is still valid for fusion. 133 struct FusionCandidate { 134 /// Cache of parts of the loop used throughout loop fusion. These should not 135 /// need to change throughout the analysis and transformation. 136 /// These parts are cached to avoid repeatedly looking up in the Loop class. 137 138 /// Preheader of the loop this candidate represents 139 BasicBlock *Preheader; 140 /// Header of the loop this candidate represents 141 BasicBlock *Header; 142 /// Blocks in the loop that exit the loop 143 BasicBlock *ExitingBlock; 144 /// The successor block of this loop (where the exiting blocks go to) 145 BasicBlock *ExitBlock; 146 /// Latch of the loop 147 BasicBlock *Latch; 148 /// The loop that this fusion candidate represents 149 Loop *L; 150 /// Vector of instructions in this loop that read from memory 151 SmallVector<Instruction *, 16> MemReads; 152 /// Vector of instructions in this loop that write to memory 153 SmallVector<Instruction *, 16> MemWrites; 154 /// Are all of the members of this fusion candidate still valid 155 bool Valid; 156 /// Guard branch of the loop, if it exists 157 BranchInst *GuardBranch; 158 159 /// Dominator and PostDominator trees are needed for the 160 /// FusionCandidateCompare function, required by FusionCandidateSet to 161 /// determine where the FusionCandidate should be inserted into the set. These 162 /// are used to establish ordering of the FusionCandidates based on dominance. 163 const DominatorTree *DT; 164 const PostDominatorTree *PDT; 165 166 OptimizationRemarkEmitter &ORE; 167 168 FusionCandidate(Loop *L, const DominatorTree *DT, 169 const PostDominatorTree *PDT, OptimizationRemarkEmitter &ORE) 170 : Preheader(L->getLoopPreheader()), Header(L->getHeader()), 171 ExitingBlock(L->getExitingBlock()), ExitBlock(L->getExitBlock()), 172 Latch(L->getLoopLatch()), L(L), Valid(true), 173 GuardBranch(L->getLoopGuardBranch()), DT(DT), PDT(PDT), ORE(ORE) { 174 175 // Walk over all blocks in the loop and check for conditions that may 176 // prevent fusion. For each block, walk over all instructions and collect 177 // the memory reads and writes If any instructions that prevent fusion are 178 // found, invalidate this object and return. 179 for (BasicBlock *BB : L->blocks()) { 180 if (BB->hasAddressTaken()) { 181 invalidate(); 182 reportInvalidCandidate(AddressTakenBB); 183 return; 184 } 185 186 for (Instruction &I : *BB) { 187 if (I.mayThrow()) { 188 invalidate(); 189 reportInvalidCandidate(MayThrowException); 190 return; 191 } 192 if (StoreInst *SI = dyn_cast<StoreInst>(&I)) { 193 if (SI->isVolatile()) { 194 invalidate(); 195 reportInvalidCandidate(ContainsVolatileAccess); 196 return; 197 } 198 } 199 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) { 200 if (LI->isVolatile()) { 201 invalidate(); 202 reportInvalidCandidate(ContainsVolatileAccess); 203 return; 204 } 205 } 206 if (I.mayWriteToMemory()) 207 MemWrites.push_back(&I); 208 if (I.mayReadFromMemory()) 209 MemReads.push_back(&I); 210 } 211 } 212 } 213 214 /// Check if all members of the class are valid. 215 bool isValid() const { 216 return Preheader && Header && ExitingBlock && ExitBlock && Latch && L && 217 !L->isInvalid() && Valid; 218 } 219 220 /// Verify that all members are in sync with the Loop object. 221 void verify() const { 222 assert(isValid() && "Candidate is not valid!!"); 223 assert(!L->isInvalid() && "Loop is invalid!"); 224 assert(Preheader == L->getLoopPreheader() && "Preheader is out of sync"); 225 assert(Header == L->getHeader() && "Header is out of sync"); 226 assert(ExitingBlock == L->getExitingBlock() && 227 "Exiting Blocks is out of sync"); 228 assert(ExitBlock == L->getExitBlock() && "Exit block is out of sync"); 229 assert(Latch == L->getLoopLatch() && "Latch is out of sync"); 230 } 231 232 /// Get the entry block for this fusion candidate. 233 /// 234 /// If this fusion candidate represents a guarded loop, the entry block is the 235 /// loop guard block. If it represents an unguarded loop, the entry block is 236 /// the preheader of the loop. 237 BasicBlock *getEntryBlock() const { 238 if (GuardBranch) 239 return GuardBranch->getParent(); 240 else 241 return Preheader; 242 } 243 244 /// Given a guarded loop, get the successor of the guard that is not in the 245 /// loop. 246 /// 247 /// This method returns the successor of the loop guard that is not located 248 /// within the loop (i.e., the successor of the guard that is not the 249 /// preheader). 250 /// This method is only valid for guarded loops. 251 BasicBlock *getNonLoopBlock() const { 252 assert(GuardBranch && "Only valid on guarded loops."); 253 assert(GuardBranch->isConditional() && 254 "Expecting guard to be a conditional branch."); 255 return (GuardBranch->getSuccessor(0) == Preheader) 256 ? GuardBranch->getSuccessor(1) 257 : GuardBranch->getSuccessor(0); 258 } 259 260 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 261 LLVM_DUMP_METHOD void dump() const { 262 dbgs() << "\tGuardBranch: "; 263 if (GuardBranch) 264 dbgs() << *GuardBranch; 265 else 266 dbgs() << "nullptr"; 267 dbgs() << "\n" 268 << (GuardBranch ? GuardBranch->getName() : "nullptr") << "\n" 269 << "\tPreheader: " << (Preheader ? Preheader->getName() : "nullptr") 270 << "\n" 271 << "\tHeader: " << (Header ? Header->getName() : "nullptr") << "\n" 272 << "\tExitingBB: " 273 << (ExitingBlock ? ExitingBlock->getName() : "nullptr") << "\n" 274 << "\tExitBB: " << (ExitBlock ? ExitBlock->getName() : "nullptr") 275 << "\n" 276 << "\tLatch: " << (Latch ? Latch->getName() : "nullptr") << "\n" 277 << "\tEntryBlock: " 278 << (getEntryBlock() ? getEntryBlock()->getName() : "nullptr") 279 << "\n"; 280 } 281 #endif 282 283 /// Determine if a fusion candidate (representing a loop) is eligible for 284 /// fusion. Note that this only checks whether a single loop can be fused - it 285 /// does not check whether it is *legal* to fuse two loops together. 286 bool isEligibleForFusion(ScalarEvolution &SE) const { 287 if (!isValid()) { 288 LLVM_DEBUG(dbgs() << "FC has invalid CFG requirements!\n"); 289 if (!Preheader) 290 ++InvalidPreheader; 291 if (!Header) 292 ++InvalidHeader; 293 if (!ExitingBlock) 294 ++InvalidExitingBlock; 295 if (!ExitBlock) 296 ++InvalidExitBlock; 297 if (!Latch) 298 ++InvalidLatch; 299 if (L->isInvalid()) 300 ++InvalidLoop; 301 302 return false; 303 } 304 305 // Require ScalarEvolution to be able to determine a trip count. 306 if (!SE.hasLoopInvariantBackedgeTakenCount(L)) { 307 LLVM_DEBUG(dbgs() << "Loop " << L->getName() 308 << " trip count not computable!\n"); 309 return reportInvalidCandidate(UnknownTripCount); 310 } 311 312 if (!L->isLoopSimplifyForm()) { 313 LLVM_DEBUG(dbgs() << "Loop " << L->getName() 314 << " is not in simplified form!\n"); 315 return reportInvalidCandidate(NotSimplifiedForm); 316 } 317 318 if (!L->isRotatedForm()) { 319 LLVM_DEBUG(dbgs() << "Loop " << L->getName() << " is not rotated!\n"); 320 return reportInvalidCandidate(NotRotated); 321 } 322 323 return true; 324 } 325 326 private: 327 // This is only used internally for now, to clear the MemWrites and MemReads 328 // list and setting Valid to false. I can't envision other uses of this right 329 // now, since once FusionCandidates are put into the FusionCandidateSet they 330 // are immutable. Thus, any time we need to change/update a FusionCandidate, 331 // we must create a new one and insert it into the FusionCandidateSet to 332 // ensure the FusionCandidateSet remains ordered correctly. 333 void invalidate() { 334 MemWrites.clear(); 335 MemReads.clear(); 336 Valid = false; 337 } 338 339 bool reportInvalidCandidate(llvm::Statistic &Stat) const { 340 using namespace ore; 341 assert(L && Preheader && "Fusion candidate not initialized properly!"); 342 ++Stat; 343 ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, Stat.getName(), 344 L->getStartLoc(), Preheader) 345 << "[" << Preheader->getParent()->getName() << "]: " 346 << "Loop is not a candidate for fusion: " << Stat.getDesc()); 347 return false; 348 } 349 }; 350 351 struct FusionCandidateCompare { 352 /// Comparison functor to sort two Control Flow Equivalent fusion candidates 353 /// into dominance order. 354 /// If LHS dominates RHS and RHS post-dominates LHS, return true; 355 /// IF RHS dominates LHS and LHS post-dominates RHS, return false; 356 bool operator()(const FusionCandidate &LHS, 357 const FusionCandidate &RHS) const { 358 const DominatorTree *DT = LHS.DT; 359 360 BasicBlock *LHSEntryBlock = LHS.getEntryBlock(); 361 BasicBlock *RHSEntryBlock = RHS.getEntryBlock(); 362 363 // Do not save PDT to local variable as it is only used in asserts and thus 364 // will trigger an unused variable warning if building without asserts. 365 assert(DT && LHS.PDT && "Expecting valid dominator tree"); 366 367 // Do this compare first so if LHS == RHS, function returns false. 368 if (DT->dominates(RHSEntryBlock, LHSEntryBlock)) { 369 // RHS dominates LHS 370 // Verify LHS post-dominates RHS 371 assert(LHS.PDT->dominates(LHSEntryBlock, RHSEntryBlock)); 372 return false; 373 } 374 375 if (DT->dominates(LHSEntryBlock, RHSEntryBlock)) { 376 // Verify RHS Postdominates LHS 377 assert(LHS.PDT->dominates(RHSEntryBlock, LHSEntryBlock)); 378 return true; 379 } 380 381 // If LHS does not dominate RHS and RHS does not dominate LHS then there is 382 // no dominance relationship between the two FusionCandidates. Thus, they 383 // should not be in the same set together. 384 llvm_unreachable( 385 "No dominance relationship between these fusion candidates!"); 386 } 387 }; 388 389 using LoopVector = SmallVector<Loop *, 4>; 390 391 // Set of Control Flow Equivalent (CFE) Fusion Candidates, sorted in dominance 392 // order. Thus, if FC0 comes *before* FC1 in a FusionCandidateSet, then FC0 393 // dominates FC1 and FC1 post-dominates FC0. 394 // std::set was chosen because we want a sorted data structure with stable 395 // iterators. A subsequent patch to loop fusion will enable fusing non-ajdacent 396 // loops by moving intervening code around. When this intervening code contains 397 // loops, those loops will be moved also. The corresponding FusionCandidates 398 // will also need to be moved accordingly. As this is done, having stable 399 // iterators will simplify the logic. Similarly, having an efficient insert that 400 // keeps the FusionCandidateSet sorted will also simplify the implementation. 401 using FusionCandidateSet = std::set<FusionCandidate, FusionCandidateCompare>; 402 using FusionCandidateCollection = SmallVector<FusionCandidateSet, 4>; 403 404 #if !defined(NDEBUG) 405 static llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, 406 const FusionCandidate &FC) { 407 if (FC.isValid()) 408 OS << FC.Preheader->getName(); 409 else 410 OS << "<Invalid>"; 411 412 return OS; 413 } 414 415 static llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, 416 const FusionCandidateSet &CandSet) { 417 for (const FusionCandidate &FC : CandSet) 418 OS << FC << '\n'; 419 420 return OS; 421 } 422 423 static void 424 printFusionCandidates(const FusionCandidateCollection &FusionCandidates) { 425 dbgs() << "Fusion Candidates: \n"; 426 for (const auto &CandidateSet : FusionCandidates) { 427 dbgs() << "*** Fusion Candidate Set ***\n"; 428 dbgs() << CandidateSet; 429 dbgs() << "****************************\n"; 430 } 431 } 432 #endif 433 434 /// Collect all loops in function at the same nest level, starting at the 435 /// outermost level. 436 /// 437 /// This data structure collects all loops at the same nest level for a 438 /// given function (specified by the LoopInfo object). It starts at the 439 /// outermost level. 440 struct LoopDepthTree { 441 using LoopsOnLevelTy = SmallVector<LoopVector, 4>; 442 using iterator = LoopsOnLevelTy::iterator; 443 using const_iterator = LoopsOnLevelTy::const_iterator; 444 445 LoopDepthTree(LoopInfo &LI) : Depth(1) { 446 if (!LI.empty()) 447 LoopsOnLevel.emplace_back(LoopVector(LI.rbegin(), LI.rend())); 448 } 449 450 /// Test whether a given loop has been removed from the function, and thus is 451 /// no longer valid. 452 bool isRemovedLoop(const Loop *L) const { return RemovedLoops.count(L); } 453 454 /// Record that a given loop has been removed from the function and is no 455 /// longer valid. 456 void removeLoop(const Loop *L) { RemovedLoops.insert(L); } 457 458 /// Descend the tree to the next (inner) nesting level 459 void descend() { 460 LoopsOnLevelTy LoopsOnNextLevel; 461 462 for (const LoopVector &LV : *this) 463 for (Loop *L : LV) 464 if (!isRemovedLoop(L) && L->begin() != L->end()) 465 LoopsOnNextLevel.emplace_back(LoopVector(L->begin(), L->end())); 466 467 LoopsOnLevel = LoopsOnNextLevel; 468 RemovedLoops.clear(); 469 Depth++; 470 } 471 472 bool empty() const { return size() == 0; } 473 size_t size() const { return LoopsOnLevel.size() - RemovedLoops.size(); } 474 unsigned getDepth() const { return Depth; } 475 476 iterator begin() { return LoopsOnLevel.begin(); } 477 iterator end() { return LoopsOnLevel.end(); } 478 const_iterator begin() const { return LoopsOnLevel.begin(); } 479 const_iterator end() const { return LoopsOnLevel.end(); } 480 481 private: 482 /// Set of loops that have been removed from the function and are no longer 483 /// valid. 484 SmallPtrSet<const Loop *, 8> RemovedLoops; 485 486 /// Depth of the current level, starting at 1 (outermost loops). 487 unsigned Depth; 488 489 /// Vector of loops at the current depth level that have the same parent loop 490 LoopsOnLevelTy LoopsOnLevel; 491 }; 492 493 #ifndef NDEBUG 494 static void printLoopVector(const LoopVector &LV) { 495 dbgs() << "****************************\n"; 496 for (auto L : LV) 497 printLoop(*L, dbgs()); 498 dbgs() << "****************************\n"; 499 } 500 #endif 501 502 struct LoopFuser { 503 private: 504 // Sets of control flow equivalent fusion candidates for a given nest level. 505 FusionCandidateCollection FusionCandidates; 506 507 LoopDepthTree LDT; 508 DomTreeUpdater DTU; 509 510 LoopInfo &LI; 511 DominatorTree &DT; 512 DependenceInfo &DI; 513 ScalarEvolution &SE; 514 PostDominatorTree &PDT; 515 OptimizationRemarkEmitter &ORE; 516 517 public: 518 LoopFuser(LoopInfo &LI, DominatorTree &DT, DependenceInfo &DI, 519 ScalarEvolution &SE, PostDominatorTree &PDT, 520 OptimizationRemarkEmitter &ORE, const DataLayout &DL) 521 : LDT(LI), DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy), LI(LI), 522 DT(DT), DI(DI), SE(SE), PDT(PDT), ORE(ORE) {} 523 524 /// This is the main entry point for loop fusion. It will traverse the 525 /// specified function and collect candidate loops to fuse, starting at the 526 /// outermost nesting level and working inwards. 527 bool fuseLoops(Function &F) { 528 #ifndef NDEBUG 529 if (VerboseFusionDebugging) { 530 LI.print(dbgs()); 531 } 532 #endif 533 534 LLVM_DEBUG(dbgs() << "Performing Loop Fusion on function " << F.getName() 535 << "\n"); 536 bool Changed = false; 537 538 while (!LDT.empty()) { 539 LLVM_DEBUG(dbgs() << "Got " << LDT.size() << " loop sets for depth " 540 << LDT.getDepth() << "\n";); 541 542 for (const LoopVector &LV : LDT) { 543 assert(LV.size() > 0 && "Empty loop set was build!"); 544 545 // Skip singleton loop sets as they do not offer fusion opportunities on 546 // this level. 547 if (LV.size() == 1) 548 continue; 549 #ifndef NDEBUG 550 if (VerboseFusionDebugging) { 551 LLVM_DEBUG({ 552 dbgs() << " Visit loop set (#" << LV.size() << "):\n"; 553 printLoopVector(LV); 554 }); 555 } 556 #endif 557 558 collectFusionCandidates(LV); 559 Changed |= fuseCandidates(); 560 } 561 562 // Finished analyzing candidates at this level. 563 // Descend to the next level and clear all of the candidates currently 564 // collected. Note that it will not be possible to fuse any of the 565 // existing candidates with new candidates because the new candidates will 566 // be at a different nest level and thus not be control flow equivalent 567 // with all of the candidates collected so far. 568 LLVM_DEBUG(dbgs() << "Descend one level!\n"); 569 LDT.descend(); 570 FusionCandidates.clear(); 571 } 572 573 if (Changed) 574 LLVM_DEBUG(dbgs() << "Function after Loop Fusion: \n"; F.dump();); 575 576 #ifndef NDEBUG 577 assert(DT.verify()); 578 assert(PDT.verify()); 579 LI.verify(DT); 580 SE.verify(); 581 #endif 582 583 LLVM_DEBUG(dbgs() << "Loop Fusion complete\n"); 584 return Changed; 585 } 586 587 private: 588 /// Determine if two fusion candidates are control flow equivalent. 589 /// 590 /// Two fusion candidates are control flow equivalent if when one executes, 591 /// the other is guaranteed to execute. This is determined using dominators 592 /// and post-dominators: if A dominates B and B post-dominates A then A and B 593 /// are control-flow equivalent. 594 bool isControlFlowEquivalent(const FusionCandidate &FC0, 595 const FusionCandidate &FC1) const { 596 assert(FC0.Preheader && FC1.Preheader && "Expecting valid preheaders"); 597 598 return ::isControlFlowEquivalent(*FC0.getEntryBlock(), *FC1.getEntryBlock(), 599 DT, PDT); 600 } 601 602 /// Iterate over all loops in the given loop set and identify the loops that 603 /// are eligible for fusion. Place all eligible fusion candidates into Control 604 /// Flow Equivalent sets, sorted by dominance. 605 void collectFusionCandidates(const LoopVector &LV) { 606 for (Loop *L : LV) { 607 FusionCandidate CurrCand(L, &DT, &PDT, ORE); 608 if (!CurrCand.isEligibleForFusion(SE)) 609 continue; 610 611 // Go through each list in FusionCandidates and determine if L is control 612 // flow equivalent with the first loop in that list. If it is, append LV. 613 // If not, go to the next list. 614 // If no suitable list is found, start another list and add it to 615 // FusionCandidates. 616 bool FoundSet = false; 617 618 for (auto &CurrCandSet : FusionCandidates) { 619 if (isControlFlowEquivalent(*CurrCandSet.begin(), CurrCand)) { 620 CurrCandSet.insert(CurrCand); 621 FoundSet = true; 622 #ifndef NDEBUG 623 if (VerboseFusionDebugging) 624 LLVM_DEBUG(dbgs() << "Adding " << CurrCand 625 << " to existing candidate set\n"); 626 #endif 627 break; 628 } 629 } 630 if (!FoundSet) { 631 // No set was found. Create a new set and add to FusionCandidates 632 #ifndef NDEBUG 633 if (VerboseFusionDebugging) 634 LLVM_DEBUG(dbgs() << "Adding " << CurrCand << " to new set\n"); 635 #endif 636 FusionCandidateSet NewCandSet; 637 NewCandSet.insert(CurrCand); 638 FusionCandidates.push_back(NewCandSet); 639 } 640 NumFusionCandidates++; 641 } 642 } 643 644 /// Determine if it is beneficial to fuse two loops. 645 /// 646 /// For now, this method simply returns true because we want to fuse as much 647 /// as possible (primarily to test the pass). This method will evolve, over 648 /// time, to add heuristics for profitability of fusion. 649 bool isBeneficialFusion(const FusionCandidate &FC0, 650 const FusionCandidate &FC1) { 651 return true; 652 } 653 654 /// Determine if two fusion candidates have the same trip count (i.e., they 655 /// execute the same number of iterations). 656 /// 657 /// Note that for now this method simply returns a boolean value because there 658 /// are no mechanisms in loop fusion to handle different trip counts. In the 659 /// future, this behaviour can be extended to adjust one of the loops to make 660 /// the trip counts equal (e.g., loop peeling). When this is added, this 661 /// interface may need to change to return more information than just a 662 /// boolean value. 663 bool identicalTripCounts(const FusionCandidate &FC0, 664 const FusionCandidate &FC1) const { 665 const SCEV *TripCount0 = SE.getBackedgeTakenCount(FC0.L); 666 if (isa<SCEVCouldNotCompute>(TripCount0)) { 667 UncomputableTripCount++; 668 LLVM_DEBUG(dbgs() << "Trip count of first loop could not be computed!"); 669 return false; 670 } 671 672 const SCEV *TripCount1 = SE.getBackedgeTakenCount(FC1.L); 673 if (isa<SCEVCouldNotCompute>(TripCount1)) { 674 UncomputableTripCount++; 675 LLVM_DEBUG(dbgs() << "Trip count of second loop could not be computed!"); 676 return false; 677 } 678 LLVM_DEBUG(dbgs() << "\tTrip counts: " << *TripCount0 << " & " 679 << *TripCount1 << " are " 680 << (TripCount0 == TripCount1 ? "identical" : "different") 681 << "\n"); 682 683 return (TripCount0 == TripCount1); 684 } 685 686 /// Walk each set of control flow equivalent fusion candidates and attempt to 687 /// fuse them. This does a single linear traversal of all candidates in the 688 /// set. The conditions for legal fusion are checked at this point. If a pair 689 /// of fusion candidates passes all legality checks, they are fused together 690 /// and a new fusion candidate is created and added to the FusionCandidateSet. 691 /// The original fusion candidates are then removed, as they are no longer 692 /// valid. 693 bool fuseCandidates() { 694 bool Fused = false; 695 LLVM_DEBUG(printFusionCandidates(FusionCandidates)); 696 for (auto &CandidateSet : FusionCandidates) { 697 if (CandidateSet.size() < 2) 698 continue; 699 700 LLVM_DEBUG(dbgs() << "Attempting fusion on Candidate Set:\n" 701 << CandidateSet << "\n"); 702 703 for (auto FC0 = CandidateSet.begin(); FC0 != CandidateSet.end(); ++FC0) { 704 assert(!LDT.isRemovedLoop(FC0->L) && 705 "Should not have removed loops in CandidateSet!"); 706 auto FC1 = FC0; 707 for (++FC1; FC1 != CandidateSet.end(); ++FC1) { 708 assert(!LDT.isRemovedLoop(FC1->L) && 709 "Should not have removed loops in CandidateSet!"); 710 711 LLVM_DEBUG(dbgs() << "Attempting to fuse candidate \n"; FC0->dump(); 712 dbgs() << " with\n"; FC1->dump(); dbgs() << "\n"); 713 714 FC0->verify(); 715 FC1->verify(); 716 717 if (!identicalTripCounts(*FC0, *FC1)) { 718 LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical trip " 719 "counts. Not fusing.\n"); 720 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1, 721 NonEqualTripCount); 722 continue; 723 } 724 725 if (!isAdjacent(*FC0, *FC1)) { 726 LLVM_DEBUG(dbgs() 727 << "Fusion candidates are not adjacent. Not fusing.\n"); 728 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1, NonAdjacent); 729 continue; 730 } 731 732 // Ensure that FC0 and FC1 have identical guards. 733 // If one (or both) are not guarded, this check is not necessary. 734 if (FC0->GuardBranch && FC1->GuardBranch && 735 !haveIdenticalGuards(*FC0, *FC1)) { 736 LLVM_DEBUG(dbgs() << "Fusion candidates do not have identical " 737 "guards. Not Fusing.\n"); 738 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1, 739 NonIdenticalGuards); 740 continue; 741 } 742 743 if (!isSafeToMoveBefore(*FC1->Preheader, 744 *FC0->Preheader->getTerminator(), DT, PDT, 745 DI)) { 746 LLVM_DEBUG(dbgs() << "Fusion candidate contains unsafe " 747 "instructions in preheader. Not fusing.\n"); 748 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1, 749 NonEmptyPreheader); 750 continue; 751 } 752 753 // The following two checks look for empty blocks in FC0 and FC1. If 754 // any of these blocks are non-empty, we do not fuse. This is done 755 // because we currently do not have the safety checks to determine if 756 // it is safe to move the blocks past other blocks in the loop. Once 757 // these checks are added, these conditions can be relaxed. 758 if (FC0->GuardBranch && !isEmptyExitBlock(*FC0)) { 759 LLVM_DEBUG(dbgs() << "Fusion candidate does not have empty exit " 760 "block. Not fusing.\n"); 761 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1, 762 NonEmptyExitBlock); 763 continue; 764 } 765 766 if (FC1->GuardBranch && !isEmptyGuardBlock(*FC1)) { 767 LLVM_DEBUG(dbgs() << "Fusion candidate does not have empty guard " 768 "block. Not fusing.\n"); 769 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1, 770 NonEmptyGuardBlock); 771 continue; 772 } 773 774 // Check the dependencies across the loops and do not fuse if it would 775 // violate them. 776 if (!dependencesAllowFusion(*FC0, *FC1)) { 777 LLVM_DEBUG(dbgs() << "Memory dependencies do not allow fusion!\n"); 778 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1, 779 InvalidDependencies); 780 continue; 781 } 782 783 bool BeneficialToFuse = isBeneficialFusion(*FC0, *FC1); 784 LLVM_DEBUG(dbgs() 785 << "\tFusion appears to be " 786 << (BeneficialToFuse ? "" : "un") << "profitable!\n"); 787 if (!BeneficialToFuse) { 788 reportLoopFusion<OptimizationRemarkMissed>(*FC0, *FC1, 789 FusionNotBeneficial); 790 continue; 791 } 792 // All analysis has completed and has determined that fusion is legal 793 // and profitable. At this point, start transforming the code and 794 // perform fusion. 795 796 LLVM_DEBUG(dbgs() << "\tFusion is performed: " << *FC0 << " and " 797 << *FC1 << "\n"); 798 799 // Report fusion to the Optimization Remarks. 800 // Note this needs to be done *before* performFusion because 801 // performFusion will change the original loops, making it not 802 // possible to identify them after fusion is complete. 803 reportLoopFusion<OptimizationRemark>(*FC0, *FC1, FuseCounter); 804 805 FusionCandidate FusedCand(performFusion(*FC0, *FC1), &DT, &PDT, ORE); 806 FusedCand.verify(); 807 assert(FusedCand.isEligibleForFusion(SE) && 808 "Fused candidate should be eligible for fusion!"); 809 810 // Notify the loop-depth-tree that these loops are not valid objects 811 LDT.removeLoop(FC1->L); 812 813 CandidateSet.erase(FC0); 814 CandidateSet.erase(FC1); 815 816 auto InsertPos = CandidateSet.insert(FusedCand); 817 818 assert(InsertPos.second && 819 "Unable to insert TargetCandidate in CandidateSet!"); 820 821 // Reset FC0 and FC1 the new (fused) candidate. Subsequent iterations 822 // of the FC1 loop will attempt to fuse the new (fused) loop with the 823 // remaining candidates in the current candidate set. 824 FC0 = FC1 = InsertPos.first; 825 826 LLVM_DEBUG(dbgs() << "Candidate Set (after fusion): " << CandidateSet 827 << "\n"); 828 829 Fused = true; 830 } 831 } 832 } 833 return Fused; 834 } 835 836 /// Rewrite all additive recurrences in a SCEV to use a new loop. 837 class AddRecLoopReplacer : public SCEVRewriteVisitor<AddRecLoopReplacer> { 838 public: 839 AddRecLoopReplacer(ScalarEvolution &SE, const Loop &OldL, const Loop &NewL, 840 bool UseMax = true) 841 : SCEVRewriteVisitor(SE), Valid(true), UseMax(UseMax), OldL(OldL), 842 NewL(NewL) {} 843 844 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { 845 const Loop *ExprL = Expr->getLoop(); 846 SmallVector<const SCEV *, 2> Operands; 847 if (ExprL == &OldL) { 848 Operands.append(Expr->op_begin(), Expr->op_end()); 849 return SE.getAddRecExpr(Operands, &NewL, Expr->getNoWrapFlags()); 850 } 851 852 if (OldL.contains(ExprL)) { 853 bool Pos = SE.isKnownPositive(Expr->getStepRecurrence(SE)); 854 if (!UseMax || !Pos || !Expr->isAffine()) { 855 Valid = false; 856 return Expr; 857 } 858 return visit(Expr->getStart()); 859 } 860 861 for (const SCEV *Op : Expr->operands()) 862 Operands.push_back(visit(Op)); 863 return SE.getAddRecExpr(Operands, ExprL, Expr->getNoWrapFlags()); 864 } 865 866 bool wasValidSCEV() const { return Valid; } 867 868 private: 869 bool Valid, UseMax; 870 const Loop &OldL, &NewL; 871 }; 872 873 /// Return false if the access functions of \p I0 and \p I1 could cause 874 /// a negative dependence. 875 bool accessDiffIsPositive(const Loop &L0, const Loop &L1, Instruction &I0, 876 Instruction &I1, bool EqualIsInvalid) { 877 Value *Ptr0 = getLoadStorePointerOperand(&I0); 878 Value *Ptr1 = getLoadStorePointerOperand(&I1); 879 if (!Ptr0 || !Ptr1) 880 return false; 881 882 const SCEV *SCEVPtr0 = SE.getSCEVAtScope(Ptr0, &L0); 883 const SCEV *SCEVPtr1 = SE.getSCEVAtScope(Ptr1, &L1); 884 #ifndef NDEBUG 885 if (VerboseFusionDebugging) 886 LLVM_DEBUG(dbgs() << " Access function check: " << *SCEVPtr0 << " vs " 887 << *SCEVPtr1 << "\n"); 888 #endif 889 AddRecLoopReplacer Rewriter(SE, L0, L1); 890 SCEVPtr0 = Rewriter.visit(SCEVPtr0); 891 #ifndef NDEBUG 892 if (VerboseFusionDebugging) 893 LLVM_DEBUG(dbgs() << " Access function after rewrite: " << *SCEVPtr0 894 << " [Valid: " << Rewriter.wasValidSCEV() << "]\n"); 895 #endif 896 if (!Rewriter.wasValidSCEV()) 897 return false; 898 899 // TODO: isKnownPredicate doesnt work well when one SCEV is loop carried (by 900 // L0) and the other is not. We could check if it is monotone and test 901 // the beginning and end value instead. 902 903 BasicBlock *L0Header = L0.getHeader(); 904 auto HasNonLinearDominanceRelation = [&](const SCEV *S) { 905 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S); 906 if (!AddRec) 907 return false; 908 return !DT.dominates(L0Header, AddRec->getLoop()->getHeader()) && 909 !DT.dominates(AddRec->getLoop()->getHeader(), L0Header); 910 }; 911 if (SCEVExprContains(SCEVPtr1, HasNonLinearDominanceRelation)) 912 return false; 913 914 ICmpInst::Predicate Pred = 915 EqualIsInvalid ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_SGE; 916 bool IsAlwaysGE = SE.isKnownPredicate(Pred, SCEVPtr0, SCEVPtr1); 917 #ifndef NDEBUG 918 if (VerboseFusionDebugging) 919 LLVM_DEBUG(dbgs() << " Relation: " << *SCEVPtr0 920 << (IsAlwaysGE ? " >= " : " may < ") << *SCEVPtr1 921 << "\n"); 922 #endif 923 return IsAlwaysGE; 924 } 925 926 /// Return true if the dependences between @p I0 (in @p L0) and @p I1 (in 927 /// @p L1) allow loop fusion of @p L0 and @p L1. The dependence analyses 928 /// specified by @p DepChoice are used to determine this. 929 bool dependencesAllowFusion(const FusionCandidate &FC0, 930 const FusionCandidate &FC1, Instruction &I0, 931 Instruction &I1, bool AnyDep, 932 FusionDependenceAnalysisChoice DepChoice) { 933 #ifndef NDEBUG 934 if (VerboseFusionDebugging) { 935 LLVM_DEBUG(dbgs() << "Check dep: " << I0 << " vs " << I1 << " : " 936 << DepChoice << "\n"); 937 } 938 #endif 939 switch (DepChoice) { 940 case FUSION_DEPENDENCE_ANALYSIS_SCEV: 941 return accessDiffIsPositive(*FC0.L, *FC1.L, I0, I1, AnyDep); 942 case FUSION_DEPENDENCE_ANALYSIS_DA: { 943 auto DepResult = DI.depends(&I0, &I1, true); 944 if (!DepResult) 945 return true; 946 #ifndef NDEBUG 947 if (VerboseFusionDebugging) { 948 LLVM_DEBUG(dbgs() << "DA res: "; DepResult->dump(dbgs()); 949 dbgs() << " [#l: " << DepResult->getLevels() << "][Ordered: " 950 << (DepResult->isOrdered() ? "true" : "false") 951 << "]\n"); 952 LLVM_DEBUG(dbgs() << "DepResult Levels: " << DepResult->getLevels() 953 << "\n"); 954 } 955 #endif 956 957 if (DepResult->getNextPredecessor() || DepResult->getNextSuccessor()) 958 LLVM_DEBUG( 959 dbgs() << "TODO: Implement pred/succ dependence handling!\n"); 960 961 // TODO: Can we actually use the dependence info analysis here? 962 return false; 963 } 964 965 case FUSION_DEPENDENCE_ANALYSIS_ALL: 966 return dependencesAllowFusion(FC0, FC1, I0, I1, AnyDep, 967 FUSION_DEPENDENCE_ANALYSIS_SCEV) || 968 dependencesAllowFusion(FC0, FC1, I0, I1, AnyDep, 969 FUSION_DEPENDENCE_ANALYSIS_DA); 970 } 971 972 llvm_unreachable("Unknown fusion dependence analysis choice!"); 973 } 974 975 /// Perform a dependence check and return if @p FC0 and @p FC1 can be fused. 976 bool dependencesAllowFusion(const FusionCandidate &FC0, 977 const FusionCandidate &FC1) { 978 LLVM_DEBUG(dbgs() << "Check if " << FC0 << " can be fused with " << FC1 979 << "\n"); 980 assert(FC0.L->getLoopDepth() == FC1.L->getLoopDepth()); 981 assert(DT.dominates(FC0.getEntryBlock(), FC1.getEntryBlock())); 982 983 for (Instruction *WriteL0 : FC0.MemWrites) { 984 for (Instruction *WriteL1 : FC1.MemWrites) 985 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1, 986 /* AnyDep */ false, 987 FusionDependenceAnalysis)) { 988 InvalidDependencies++; 989 return false; 990 } 991 for (Instruction *ReadL1 : FC1.MemReads) 992 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *ReadL1, 993 /* AnyDep */ false, 994 FusionDependenceAnalysis)) { 995 InvalidDependencies++; 996 return false; 997 } 998 } 999 1000 for (Instruction *WriteL1 : FC1.MemWrites) { 1001 for (Instruction *WriteL0 : FC0.MemWrites) 1002 if (!dependencesAllowFusion(FC0, FC1, *WriteL0, *WriteL1, 1003 /* AnyDep */ false, 1004 FusionDependenceAnalysis)) { 1005 InvalidDependencies++; 1006 return false; 1007 } 1008 for (Instruction *ReadL0 : FC0.MemReads) 1009 if (!dependencesAllowFusion(FC0, FC1, *ReadL0, *WriteL1, 1010 /* AnyDep */ false, 1011 FusionDependenceAnalysis)) { 1012 InvalidDependencies++; 1013 return false; 1014 } 1015 } 1016 1017 // Walk through all uses in FC1. For each use, find the reaching def. If the 1018 // def is located in FC0 then it is is not safe to fuse. 1019 for (BasicBlock *BB : FC1.L->blocks()) 1020 for (Instruction &I : *BB) 1021 for (auto &Op : I.operands()) 1022 if (Instruction *Def = dyn_cast<Instruction>(Op)) 1023 if (FC0.L->contains(Def->getParent())) { 1024 InvalidDependencies++; 1025 return false; 1026 } 1027 1028 return true; 1029 } 1030 1031 /// Determine if two fusion candidates are adjacent in the CFG. 1032 /// 1033 /// This method will determine if there are additional basic blocks in the CFG 1034 /// between the exit of \p FC0 and the entry of \p FC1. 1035 /// If the two candidates are guarded loops, then it checks whether the 1036 /// non-loop successor of the \p FC0 guard branch is the entry block of \p 1037 /// FC1. If not, then the loops are not adjacent. If the two candidates are 1038 /// not guarded loops, then it checks whether the exit block of \p FC0 is the 1039 /// preheader of \p FC1. 1040 bool isAdjacent(const FusionCandidate &FC0, 1041 const FusionCandidate &FC1) const { 1042 // If the successor of the guard branch is FC1, then the loops are adjacent 1043 if (FC0.GuardBranch) 1044 return FC0.getNonLoopBlock() == FC1.getEntryBlock(); 1045 else 1046 return FC0.ExitBlock == FC1.getEntryBlock(); 1047 } 1048 1049 /// Determine if two fusion candidates have identical guards 1050 /// 1051 /// This method will determine if two fusion candidates have the same guards. 1052 /// The guards are considered the same if: 1053 /// 1. The instructions to compute the condition used in the compare are 1054 /// identical. 1055 /// 2. The successors of the guard have the same flow into/around the loop. 1056 /// If the compare instructions are identical, then the first successor of the 1057 /// guard must go to the same place (either the preheader of the loop or the 1058 /// NonLoopBlock). In other words, the the first successor of both loops must 1059 /// both go into the loop (i.e., the preheader) or go around the loop (i.e., 1060 /// the NonLoopBlock). The same must be true for the second successor. 1061 bool haveIdenticalGuards(const FusionCandidate &FC0, 1062 const FusionCandidate &FC1) const { 1063 assert(FC0.GuardBranch && FC1.GuardBranch && 1064 "Expecting FC0 and FC1 to be guarded loops."); 1065 1066 if (auto FC0CmpInst = 1067 dyn_cast<Instruction>(FC0.GuardBranch->getCondition())) 1068 if (auto FC1CmpInst = 1069 dyn_cast<Instruction>(FC1.GuardBranch->getCondition())) 1070 if (!FC0CmpInst->isIdenticalTo(FC1CmpInst)) 1071 return false; 1072 1073 // The compare instructions are identical. 1074 // Now make sure the successor of the guards have the same flow into/around 1075 // the loop 1076 if (FC0.GuardBranch->getSuccessor(0) == FC0.Preheader) 1077 return (FC1.GuardBranch->getSuccessor(0) == FC1.Preheader); 1078 else 1079 return (FC1.GuardBranch->getSuccessor(1) == FC1.Preheader); 1080 } 1081 1082 /// Check that the guard for \p FC *only* contains the cmp/branch for the 1083 /// guard. 1084 /// Once we are able to handle intervening code, any code in the guard block 1085 /// for FC1 will need to be treated as intervening code and checked whether 1086 /// it can safely move around the loops. 1087 bool isEmptyGuardBlock(const FusionCandidate &FC) const { 1088 assert(FC.GuardBranch && "Expecting a fusion candidate with guard branch."); 1089 if (auto *CmpInst = dyn_cast<Instruction>(FC.GuardBranch->getCondition())) { 1090 auto *GuardBlock = FC.GuardBranch->getParent(); 1091 // If the generation of the cmp value is in GuardBlock, then the size of 1092 // the guard block should be 2 (cmp + branch). If the generation of the 1093 // cmp value is in a different block, then the size of the guard block 1094 // should only be 1. 1095 if (CmpInst->getParent() == GuardBlock) 1096 return GuardBlock->size() == 2; 1097 else 1098 return GuardBlock->size() == 1; 1099 } 1100 1101 return false; 1102 } 1103 1104 bool isEmptyPreheader(const FusionCandidate &FC) const { 1105 assert(FC.Preheader && "Expecting a valid preheader"); 1106 return FC.Preheader->size() == 1; 1107 } 1108 1109 bool isEmptyExitBlock(const FusionCandidate &FC) const { 1110 assert(FC.ExitBlock && "Expecting a valid exit block"); 1111 return FC.ExitBlock->size() == 1; 1112 } 1113 1114 /// Simplify the condition of the latch branch of \p FC to true, when both of 1115 /// its successors are the same. 1116 void simplifyLatchBranch(const FusionCandidate &FC) const { 1117 BranchInst *FCLatchBranch = dyn_cast<BranchInst>(FC.Latch->getTerminator()); 1118 if (FCLatchBranch) { 1119 assert(FCLatchBranch->isConditional() && 1120 FCLatchBranch->getSuccessor(0) == FCLatchBranch->getSuccessor(1) && 1121 "Expecting the two successors of FCLatchBranch to be the same"); 1122 FCLatchBranch->setCondition( 1123 llvm::ConstantInt::getTrue(FCLatchBranch->getCondition()->getType())); 1124 } 1125 } 1126 1127 /// Move instructions from FC0.Latch to FC1.Latch. If FC0.Latch has an unique 1128 /// successor, then merge FC0.Latch with its unique successor. 1129 void mergeLatch(const FusionCandidate &FC0, const FusionCandidate &FC1) { 1130 moveInstructionsToTheBeginning(*FC0.Latch, *FC1.Latch, DT, PDT, DI); 1131 if (BasicBlock *Succ = FC0.Latch->getUniqueSuccessor()) { 1132 MergeBlockIntoPredecessor(Succ, &DTU, &LI); 1133 DTU.flush(); 1134 } 1135 } 1136 1137 /// Fuse two fusion candidates, creating a new fused loop. 1138 /// 1139 /// This method contains the mechanics of fusing two loops, represented by \p 1140 /// FC0 and \p FC1. It is assumed that \p FC0 dominates \p FC1 and \p FC1 1141 /// postdominates \p FC0 (making them control flow equivalent). It also 1142 /// assumes that the other conditions for fusion have been met: adjacent, 1143 /// identical trip counts, and no negative distance dependencies exist that 1144 /// would prevent fusion. Thus, there is no checking for these conditions in 1145 /// this method. 1146 /// 1147 /// Fusion is performed by rewiring the CFG to update successor blocks of the 1148 /// components of tho loop. Specifically, the following changes are done: 1149 /// 1150 /// 1. The preheader of \p FC1 is removed as it is no longer necessary 1151 /// (because it is currently only a single statement block). 1152 /// 2. The latch of \p FC0 is modified to jump to the header of \p FC1. 1153 /// 3. The latch of \p FC1 i modified to jump to the header of \p FC0. 1154 /// 4. All blocks from \p FC1 are removed from FC1 and added to FC0. 1155 /// 1156 /// All of these modifications are done with dominator tree updates, thus 1157 /// keeping the dominator (and post dominator) information up-to-date. 1158 /// 1159 /// This can be improved in the future by actually merging blocks during 1160 /// fusion. For example, the preheader of \p FC1 can be merged with the 1161 /// preheader of \p FC0. This would allow loops with more than a single 1162 /// statement in the preheader to be fused. Similarly, the latch blocks of the 1163 /// two loops could also be fused into a single block. This will require 1164 /// analysis to prove it is safe to move the contents of the block past 1165 /// existing code, which currently has not been implemented. 1166 Loop *performFusion(const FusionCandidate &FC0, const FusionCandidate &FC1) { 1167 assert(FC0.isValid() && FC1.isValid() && 1168 "Expecting valid fusion candidates"); 1169 1170 LLVM_DEBUG(dbgs() << "Fusion Candidate 0: \n"; FC0.dump(); 1171 dbgs() << "Fusion Candidate 1: \n"; FC1.dump();); 1172 1173 // Move instructions from the preheader of FC1 to the end of the preheader 1174 // of FC0. 1175 moveInstructionsToTheEnd(*FC1.Preheader, *FC0.Preheader, DT, PDT, DI); 1176 1177 // Fusing guarded loops is handled slightly differently than non-guarded 1178 // loops and has been broken out into a separate method instead of trying to 1179 // intersperse the logic within a single method. 1180 if (FC0.GuardBranch) 1181 return fuseGuardedLoops(FC0, FC1); 1182 1183 assert(FC1.Preheader == FC0.ExitBlock); 1184 assert(FC1.Preheader->size() == 1 && 1185 FC1.Preheader->getSingleSuccessor() == FC1.Header); 1186 1187 // Remember the phi nodes originally in the header of FC0 in order to rewire 1188 // them later. However, this is only necessary if the new loop carried 1189 // values might not dominate the exiting branch. While we do not generally 1190 // test if this is the case but simply insert intermediate phi nodes, we 1191 // need to make sure these intermediate phi nodes have different 1192 // predecessors. To this end, we filter the special case where the exiting 1193 // block is the latch block of the first loop. Nothing needs to be done 1194 // anyway as all loop carried values dominate the latch and thereby also the 1195 // exiting branch. 1196 SmallVector<PHINode *, 8> OriginalFC0PHIs; 1197 if (FC0.ExitingBlock != FC0.Latch) 1198 for (PHINode &PHI : FC0.Header->phis()) 1199 OriginalFC0PHIs.push_back(&PHI); 1200 1201 // Replace incoming blocks for header PHIs first. 1202 FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader); 1203 FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch); 1204 1205 // Then modify the control flow and update DT and PDT. 1206 SmallVector<DominatorTree::UpdateType, 8> TreeUpdates; 1207 1208 // The old exiting block of the first loop (FC0) has to jump to the header 1209 // of the second as we need to execute the code in the second header block 1210 // regardless of the trip count. That is, if the trip count is 0, so the 1211 // back edge is never taken, we still have to execute both loop headers, 1212 // especially (but not only!) if the second is a do-while style loop. 1213 // However, doing so might invalidate the phi nodes of the first loop as 1214 // the new values do only need to dominate their latch and not the exiting 1215 // predicate. To remedy this potential problem we always introduce phi 1216 // nodes in the header of the second loop later that select the loop carried 1217 // value, if the second header was reached through an old latch of the 1218 // first, or undef otherwise. This is sound as exiting the first implies the 1219 // second will exit too, __without__ taking the back-edge. [Their 1220 // trip-counts are equal after all. 1221 // KB: Would this sequence be simpler to just just make FC0.ExitingBlock go 1222 // to FC1.Header? I think this is basically what the three sequences are 1223 // trying to accomplish; however, doing this directly in the CFG may mean 1224 // the DT/PDT becomes invalid 1225 FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC1.Preheader, 1226 FC1.Header); 1227 TreeUpdates.emplace_back(DominatorTree::UpdateType( 1228 DominatorTree::Delete, FC0.ExitingBlock, FC1.Preheader)); 1229 TreeUpdates.emplace_back(DominatorTree::UpdateType( 1230 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header)); 1231 1232 // The pre-header of L1 is not necessary anymore. 1233 assert(pred_begin(FC1.Preheader) == pred_end(FC1.Preheader)); 1234 FC1.Preheader->getTerminator()->eraseFromParent(); 1235 new UnreachableInst(FC1.Preheader->getContext(), FC1.Preheader); 1236 TreeUpdates.emplace_back(DominatorTree::UpdateType( 1237 DominatorTree::Delete, FC1.Preheader, FC1.Header)); 1238 1239 // Moves the phi nodes from the second to the first loops header block. 1240 while (PHINode *PHI = dyn_cast<PHINode>(&FC1.Header->front())) { 1241 if (SE.isSCEVable(PHI->getType())) 1242 SE.forgetValue(PHI); 1243 if (PHI->hasNUsesOrMore(1)) 1244 PHI->moveBefore(&*FC0.Header->getFirstInsertionPt()); 1245 else 1246 PHI->eraseFromParent(); 1247 } 1248 1249 // Introduce new phi nodes in the second loop header to ensure 1250 // exiting the first and jumping to the header of the second does not break 1251 // the SSA property of the phis originally in the first loop. See also the 1252 // comment above. 1253 Instruction *L1HeaderIP = &FC1.Header->front(); 1254 for (PHINode *LCPHI : OriginalFC0PHIs) { 1255 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch); 1256 assert(L1LatchBBIdx >= 0 && 1257 "Expected loop carried value to be rewired at this point!"); 1258 1259 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx); 1260 1261 PHINode *L1HeaderPHI = PHINode::Create( 1262 LCV->getType(), 2, LCPHI->getName() + ".afterFC0", L1HeaderIP); 1263 L1HeaderPHI->addIncoming(LCV, FC0.Latch); 1264 L1HeaderPHI->addIncoming(UndefValue::get(LCV->getType()), 1265 FC0.ExitingBlock); 1266 1267 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI); 1268 } 1269 1270 // Replace latch terminator destinations. 1271 FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header); 1272 FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header); 1273 1274 // Change the condition of FC0 latch branch to true, as both successors of 1275 // the branch are the same. 1276 simplifyLatchBranch(FC0); 1277 1278 // If FC0.Latch and FC0.ExitingBlock are the same then we have already 1279 // performed the updates above. 1280 if (FC0.Latch != FC0.ExitingBlock) 1281 TreeUpdates.emplace_back(DominatorTree::UpdateType( 1282 DominatorTree::Insert, FC0.Latch, FC1.Header)); 1283 1284 TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete, 1285 FC0.Latch, FC0.Header)); 1286 TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Insert, 1287 FC1.Latch, FC0.Header)); 1288 TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete, 1289 FC1.Latch, FC1.Header)); 1290 1291 // Update DT/PDT 1292 DTU.applyUpdates(TreeUpdates); 1293 1294 LI.removeBlock(FC1.Preheader); 1295 DTU.deleteBB(FC1.Preheader); 1296 DTU.flush(); 1297 1298 // Is there a way to keep SE up-to-date so we don't need to forget the loops 1299 // and rebuild the information in subsequent passes of fusion? 1300 // Note: Need to forget the loops before merging the loop latches, as 1301 // mergeLatch may remove the only block in FC1. 1302 SE.forgetLoop(FC1.L); 1303 SE.forgetLoop(FC0.L); 1304 1305 // Move instructions from FC0.Latch to FC1.Latch. 1306 // Note: mergeLatch requires an updated DT. 1307 mergeLatch(FC0, FC1); 1308 1309 // Merge the loops. 1310 SmallVector<BasicBlock *, 8> Blocks(FC1.L->block_begin(), 1311 FC1.L->block_end()); 1312 for (BasicBlock *BB : Blocks) { 1313 FC0.L->addBlockEntry(BB); 1314 FC1.L->removeBlockFromLoop(BB); 1315 if (LI.getLoopFor(BB) != FC1.L) 1316 continue; 1317 LI.changeLoopFor(BB, FC0.L); 1318 } 1319 while (!FC1.L->empty()) { 1320 const auto &ChildLoopIt = FC1.L->begin(); 1321 Loop *ChildLoop = *ChildLoopIt; 1322 FC1.L->removeChildLoop(ChildLoopIt); 1323 FC0.L->addChildLoop(ChildLoop); 1324 } 1325 1326 // Delete the now empty loop L1. 1327 LI.erase(FC1.L); 1328 1329 #ifndef NDEBUG 1330 assert(!verifyFunction(*FC0.Header->getParent(), &errs())); 1331 assert(DT.verify(DominatorTree::VerificationLevel::Fast)); 1332 assert(PDT.verify()); 1333 LI.verify(DT); 1334 SE.verify(); 1335 #endif 1336 1337 LLVM_DEBUG(dbgs() << "Fusion done:\n"); 1338 1339 return FC0.L; 1340 } 1341 1342 /// Report details on loop fusion opportunities. 1343 /// 1344 /// This template function can be used to report both successful and missed 1345 /// loop fusion opportunities, based on the RemarkKind. The RemarkKind should 1346 /// be one of: 1347 /// - OptimizationRemarkMissed to report when loop fusion is unsuccessful 1348 /// given two valid fusion candidates. 1349 /// - OptimizationRemark to report successful fusion of two fusion 1350 /// candidates. 1351 /// The remarks will be printed using the form: 1352 /// <path/filename>:<line number>:<column number>: [<function name>]: 1353 /// <Cand1 Preheader> and <Cand2 Preheader>: <Stat Description> 1354 template <typename RemarkKind> 1355 void reportLoopFusion(const FusionCandidate &FC0, const FusionCandidate &FC1, 1356 llvm::Statistic &Stat) { 1357 assert(FC0.Preheader && FC1.Preheader && 1358 "Expecting valid fusion candidates"); 1359 using namespace ore; 1360 ++Stat; 1361 ORE.emit(RemarkKind(DEBUG_TYPE, Stat.getName(), FC0.L->getStartLoc(), 1362 FC0.Preheader) 1363 << "[" << FC0.Preheader->getParent()->getName() 1364 << "]: " << NV("Cand1", StringRef(FC0.Preheader->getName())) 1365 << " and " << NV("Cand2", StringRef(FC1.Preheader->getName())) 1366 << ": " << Stat.getDesc()); 1367 } 1368 1369 /// Fuse two guarded fusion candidates, creating a new fused loop. 1370 /// 1371 /// Fusing guarded loops is handled much the same way as fusing non-guarded 1372 /// loops. The rewiring of the CFG is slightly different though, because of 1373 /// the presence of the guards around the loops and the exit blocks after the 1374 /// loop body. As such, the new loop is rewired as follows: 1375 /// 1. Keep the guard branch from FC0 and use the non-loop block target 1376 /// from the FC1 guard branch. 1377 /// 2. Remove the exit block from FC0 (this exit block should be empty 1378 /// right now). 1379 /// 3. Remove the guard branch for FC1 1380 /// 4. Remove the preheader for FC1. 1381 /// The exit block successor for the latch of FC0 is updated to be the header 1382 /// of FC1 and the non-exit block successor of the latch of FC1 is updated to 1383 /// be the header of FC0, thus creating the fused loop. 1384 Loop *fuseGuardedLoops(const FusionCandidate &FC0, 1385 const FusionCandidate &FC1) { 1386 assert(FC0.GuardBranch && FC1.GuardBranch && "Expecting guarded loops"); 1387 1388 BasicBlock *FC0GuardBlock = FC0.GuardBranch->getParent(); 1389 BasicBlock *FC1GuardBlock = FC1.GuardBranch->getParent(); 1390 BasicBlock *FC0NonLoopBlock = FC0.getNonLoopBlock(); 1391 BasicBlock *FC1NonLoopBlock = FC1.getNonLoopBlock(); 1392 1393 assert(FC0NonLoopBlock == FC1GuardBlock && "Loops are not adjacent"); 1394 1395 SmallVector<DominatorTree::UpdateType, 8> TreeUpdates; 1396 1397 //////////////////////////////////////////////////////////////////////////// 1398 // Update the Loop Guard 1399 //////////////////////////////////////////////////////////////////////////// 1400 // The guard for FC0 is updated to guard both FC0 and FC1. This is done by 1401 // changing the NonLoopGuardBlock for FC0 to the NonLoopGuardBlock for FC1. 1402 // Thus, one path from the guard goes to the preheader for FC0 (and thus 1403 // executes the new fused loop) and the other path goes to the NonLoopBlock 1404 // for FC1 (where FC1 guard would have gone if FC1 was not executed). 1405 FC0.GuardBranch->replaceUsesOfWith(FC0NonLoopBlock, FC1NonLoopBlock); 1406 FC0.ExitBlock->getTerminator()->replaceUsesOfWith(FC1GuardBlock, 1407 FC1.Header); 1408 1409 // The guard of FC1 is not necessary anymore. 1410 FC1.GuardBranch->eraseFromParent(); 1411 new UnreachableInst(FC1GuardBlock->getContext(), FC1GuardBlock); 1412 1413 TreeUpdates.emplace_back(DominatorTree::UpdateType( 1414 DominatorTree::Delete, FC1GuardBlock, FC1.Preheader)); 1415 TreeUpdates.emplace_back(DominatorTree::UpdateType( 1416 DominatorTree::Delete, FC1GuardBlock, FC1NonLoopBlock)); 1417 TreeUpdates.emplace_back(DominatorTree::UpdateType( 1418 DominatorTree::Delete, FC0GuardBlock, FC1GuardBlock)); 1419 TreeUpdates.emplace_back(DominatorTree::UpdateType( 1420 DominatorTree::Insert, FC0GuardBlock, FC1NonLoopBlock)); 1421 1422 assert(pred_begin(FC1GuardBlock) == pred_end(FC1GuardBlock) && 1423 "Expecting guard block to have no predecessors"); 1424 assert(succ_begin(FC1GuardBlock) == succ_end(FC1GuardBlock) && 1425 "Expecting guard block to have no successors"); 1426 1427 // Remember the phi nodes originally in the header of FC0 in order to rewire 1428 // them later. However, this is only necessary if the new loop carried 1429 // values might not dominate the exiting branch. While we do not generally 1430 // test if this is the case but simply insert intermediate phi nodes, we 1431 // need to make sure these intermediate phi nodes have different 1432 // predecessors. To this end, we filter the special case where the exiting 1433 // block is the latch block of the first loop. Nothing needs to be done 1434 // anyway as all loop carried values dominate the latch and thereby also the 1435 // exiting branch. 1436 // KB: This is no longer necessary because FC0.ExitingBlock == FC0.Latch 1437 // (because the loops are rotated. Thus, nothing will ever be added to 1438 // OriginalFC0PHIs. 1439 SmallVector<PHINode *, 8> OriginalFC0PHIs; 1440 if (FC0.ExitingBlock != FC0.Latch) 1441 for (PHINode &PHI : FC0.Header->phis()) 1442 OriginalFC0PHIs.push_back(&PHI); 1443 1444 assert(OriginalFC0PHIs.empty() && "Expecting OriginalFC0PHIs to be empty!"); 1445 1446 // Replace incoming blocks for header PHIs first. 1447 FC1.Preheader->replaceSuccessorsPhiUsesWith(FC0.Preheader); 1448 FC0.Latch->replaceSuccessorsPhiUsesWith(FC1.Latch); 1449 1450 // The old exiting block of the first loop (FC0) has to jump to the header 1451 // of the second as we need to execute the code in the second header block 1452 // regardless of the trip count. That is, if the trip count is 0, so the 1453 // back edge is never taken, we still have to execute both loop headers, 1454 // especially (but not only!) if the second is a do-while style loop. 1455 // However, doing so might invalidate the phi nodes of the first loop as 1456 // the new values do only need to dominate their latch and not the exiting 1457 // predicate. To remedy this potential problem we always introduce phi 1458 // nodes in the header of the second loop later that select the loop carried 1459 // value, if the second header was reached through an old latch of the 1460 // first, or undef otherwise. This is sound as exiting the first implies the 1461 // second will exit too, __without__ taking the back-edge (their 1462 // trip-counts are equal after all). 1463 FC0.ExitingBlock->getTerminator()->replaceUsesOfWith(FC0.ExitBlock, 1464 FC1.Header); 1465 1466 TreeUpdates.emplace_back(DominatorTree::UpdateType( 1467 DominatorTree::Delete, FC0.ExitingBlock, FC0.ExitBlock)); 1468 TreeUpdates.emplace_back(DominatorTree::UpdateType( 1469 DominatorTree::Insert, FC0.ExitingBlock, FC1.Header)); 1470 1471 // Remove FC0 Exit Block 1472 // The exit block for FC0 is no longer needed since control will flow 1473 // directly to the header of FC1. Since it is an empty block, it can be 1474 // removed at this point. 1475 // TODO: In the future, we can handle non-empty exit blocks my merging any 1476 // instructions from FC0 exit block into FC1 exit block prior to removing 1477 // the block. 1478 assert(pred_begin(FC0.ExitBlock) == pred_end(FC0.ExitBlock) && 1479 "Expecting exit block to be empty"); 1480 FC0.ExitBlock->getTerminator()->eraseFromParent(); 1481 new UnreachableInst(FC0.ExitBlock->getContext(), FC0.ExitBlock); 1482 1483 // Remove FC1 Preheader 1484 // The pre-header of L1 is not necessary anymore. 1485 assert(pred_begin(FC1.Preheader) == pred_end(FC1.Preheader)); 1486 FC1.Preheader->getTerminator()->eraseFromParent(); 1487 new UnreachableInst(FC1.Preheader->getContext(), FC1.Preheader); 1488 TreeUpdates.emplace_back(DominatorTree::UpdateType( 1489 DominatorTree::Delete, FC1.Preheader, FC1.Header)); 1490 1491 // Moves the phi nodes from the second to the first loops header block. 1492 while (PHINode *PHI = dyn_cast<PHINode>(&FC1.Header->front())) { 1493 if (SE.isSCEVable(PHI->getType())) 1494 SE.forgetValue(PHI); 1495 if (PHI->hasNUsesOrMore(1)) 1496 PHI->moveBefore(&*FC0.Header->getFirstInsertionPt()); 1497 else 1498 PHI->eraseFromParent(); 1499 } 1500 1501 // Introduce new phi nodes in the second loop header to ensure 1502 // exiting the first and jumping to the header of the second does not break 1503 // the SSA property of the phis originally in the first loop. See also the 1504 // comment above. 1505 Instruction *L1HeaderIP = &FC1.Header->front(); 1506 for (PHINode *LCPHI : OriginalFC0PHIs) { 1507 int L1LatchBBIdx = LCPHI->getBasicBlockIndex(FC1.Latch); 1508 assert(L1LatchBBIdx >= 0 && 1509 "Expected loop carried value to be rewired at this point!"); 1510 1511 Value *LCV = LCPHI->getIncomingValue(L1LatchBBIdx); 1512 1513 PHINode *L1HeaderPHI = PHINode::Create( 1514 LCV->getType(), 2, LCPHI->getName() + ".afterFC0", L1HeaderIP); 1515 L1HeaderPHI->addIncoming(LCV, FC0.Latch); 1516 L1HeaderPHI->addIncoming(UndefValue::get(LCV->getType()), 1517 FC0.ExitingBlock); 1518 1519 LCPHI->setIncomingValue(L1LatchBBIdx, L1HeaderPHI); 1520 } 1521 1522 // Update the latches 1523 1524 // Replace latch terminator destinations. 1525 FC0.Latch->getTerminator()->replaceUsesOfWith(FC0.Header, FC1.Header); 1526 FC1.Latch->getTerminator()->replaceUsesOfWith(FC1.Header, FC0.Header); 1527 1528 // Change the condition of FC0 latch branch to true, as both successors of 1529 // the branch are the same. 1530 simplifyLatchBranch(FC0); 1531 1532 // If FC0.Latch and FC0.ExitingBlock are the same then we have already 1533 // performed the updates above. 1534 if (FC0.Latch != FC0.ExitingBlock) 1535 TreeUpdates.emplace_back(DominatorTree::UpdateType( 1536 DominatorTree::Insert, FC0.Latch, FC1.Header)); 1537 1538 TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete, 1539 FC0.Latch, FC0.Header)); 1540 TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Insert, 1541 FC1.Latch, FC0.Header)); 1542 TreeUpdates.emplace_back(DominatorTree::UpdateType(DominatorTree::Delete, 1543 FC1.Latch, FC1.Header)); 1544 1545 // All done 1546 // Apply the updates to the Dominator Tree and cleanup. 1547 1548 assert(succ_begin(FC1GuardBlock) == succ_end(FC1GuardBlock) && 1549 "FC1GuardBlock has successors!!"); 1550 assert(pred_begin(FC1GuardBlock) == pred_end(FC1GuardBlock) && 1551 "FC1GuardBlock has predecessors!!"); 1552 1553 // Update DT/PDT 1554 DTU.applyUpdates(TreeUpdates); 1555 1556 LI.removeBlock(FC1.Preheader); 1557 DTU.deleteBB(FC1.Preheader); 1558 DTU.deleteBB(FC0.ExitBlock); 1559 DTU.flush(); 1560 1561 // Is there a way to keep SE up-to-date so we don't need to forget the loops 1562 // and rebuild the information in subsequent passes of fusion? 1563 // Note: Need to forget the loops before merging the loop latches, as 1564 // mergeLatch may remove the only block in FC1. 1565 SE.forgetLoop(FC1.L); 1566 SE.forgetLoop(FC0.L); 1567 1568 // Move instructions from FC0.Latch to FC1.Latch. 1569 // Note: mergeLatch requires an updated DT. 1570 mergeLatch(FC0, FC1); 1571 1572 // Merge the loops. 1573 SmallVector<BasicBlock *, 8> Blocks(FC1.L->block_begin(), 1574 FC1.L->block_end()); 1575 for (BasicBlock *BB : Blocks) { 1576 FC0.L->addBlockEntry(BB); 1577 FC1.L->removeBlockFromLoop(BB); 1578 if (LI.getLoopFor(BB) != FC1.L) 1579 continue; 1580 LI.changeLoopFor(BB, FC0.L); 1581 } 1582 while (!FC1.L->empty()) { 1583 const auto &ChildLoopIt = FC1.L->begin(); 1584 Loop *ChildLoop = *ChildLoopIt; 1585 FC1.L->removeChildLoop(ChildLoopIt); 1586 FC0.L->addChildLoop(ChildLoop); 1587 } 1588 1589 // Delete the now empty loop L1. 1590 LI.erase(FC1.L); 1591 1592 #ifndef NDEBUG 1593 assert(!verifyFunction(*FC0.Header->getParent(), &errs())); 1594 assert(DT.verify(DominatorTree::VerificationLevel::Fast)); 1595 assert(PDT.verify()); 1596 LI.verify(DT); 1597 SE.verify(); 1598 #endif 1599 1600 LLVM_DEBUG(dbgs() << "Fusion done:\n"); 1601 1602 return FC0.L; 1603 } 1604 }; 1605 1606 struct LoopFuseLegacy : public FunctionPass { 1607 1608 static char ID; 1609 1610 LoopFuseLegacy() : FunctionPass(ID) { 1611 initializeLoopFuseLegacyPass(*PassRegistry::getPassRegistry()); 1612 } 1613 1614 void getAnalysisUsage(AnalysisUsage &AU) const override { 1615 AU.addRequiredID(LoopSimplifyID); 1616 AU.addRequired<ScalarEvolutionWrapperPass>(); 1617 AU.addRequired<LoopInfoWrapperPass>(); 1618 AU.addRequired<DominatorTreeWrapperPass>(); 1619 AU.addRequired<PostDominatorTreeWrapperPass>(); 1620 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 1621 AU.addRequired<DependenceAnalysisWrapperPass>(); 1622 1623 AU.addPreserved<ScalarEvolutionWrapperPass>(); 1624 AU.addPreserved<LoopInfoWrapperPass>(); 1625 AU.addPreserved<DominatorTreeWrapperPass>(); 1626 AU.addPreserved<PostDominatorTreeWrapperPass>(); 1627 } 1628 1629 bool runOnFunction(Function &F) override { 1630 if (skipFunction(F)) 1631 return false; 1632 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 1633 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1634 auto &DI = getAnalysis<DependenceAnalysisWrapperPass>().getDI(); 1635 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 1636 auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(); 1637 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 1638 1639 const DataLayout &DL = F.getParent()->getDataLayout(); 1640 LoopFuser LF(LI, DT, DI, SE, PDT, ORE, DL); 1641 return LF.fuseLoops(F); 1642 } 1643 }; 1644 } // namespace 1645 1646 PreservedAnalyses LoopFusePass::run(Function &F, FunctionAnalysisManager &AM) { 1647 auto &LI = AM.getResult<LoopAnalysis>(F); 1648 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 1649 auto &DI = AM.getResult<DependenceAnalysis>(F); 1650 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F); 1651 auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F); 1652 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 1653 1654 const DataLayout &DL = F.getParent()->getDataLayout(); 1655 LoopFuser LF(LI, DT, DI, SE, PDT, ORE, DL); 1656 bool Changed = LF.fuseLoops(F); 1657 if (!Changed) 1658 return PreservedAnalyses::all(); 1659 1660 PreservedAnalyses PA; 1661 PA.preserve<DominatorTreeAnalysis>(); 1662 PA.preserve<PostDominatorTreeAnalysis>(); 1663 PA.preserve<ScalarEvolutionAnalysis>(); 1664 PA.preserve<LoopAnalysis>(); 1665 return PA; 1666 } 1667 1668 char LoopFuseLegacy::ID = 0; 1669 1670 INITIALIZE_PASS_BEGIN(LoopFuseLegacy, "loop-fusion", "Loop Fusion", false, 1671 false) 1672 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass) 1673 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 1674 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1675 INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass) 1676 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 1677 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 1678 INITIALIZE_PASS_END(LoopFuseLegacy, "loop-fusion", "Loop Fusion", false, false) 1679 1680 FunctionPass *llvm::createLoopFusePass() { return new LoopFuseLegacy(); } 1681