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