1 //===- LoopInterchange.cpp - Loop interchange pass-------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This Pass handles loop interchange transform. 11 // This pass interchanges loops to provide a more cache-friendly memory access 12 // patterns. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/ADT/Statistic.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/Analysis/AliasAnalysis.h" 21 #include "llvm/Analysis/DependenceAnalysis.h" 22 #include "llvm/Analysis/LoopInfo.h" 23 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 24 #include "llvm/Analysis/ScalarEvolution.h" 25 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 26 #include "llvm/IR/BasicBlock.h" 27 #include "llvm/IR/Constants.h" 28 #include "llvm/IR/DiagnosticInfo.h" 29 #include "llvm/IR/Dominators.h" 30 #include "llvm/IR/Function.h" 31 #include "llvm/IR/InstrTypes.h" 32 #include "llvm/IR/Instruction.h" 33 #include "llvm/IR/Instructions.h" 34 #include "llvm/IR/Type.h" 35 #include "llvm/IR/User.h" 36 #include "llvm/IR/Value.h" 37 #include "llvm/Pass.h" 38 #include "llvm/Support/Casting.h" 39 #include "llvm/Support/CommandLine.h" 40 #include "llvm/Support/Debug.h" 41 #include "llvm/Support/ErrorHandling.h" 42 #include "llvm/Support/raw_ostream.h" 43 #include "llvm/Transforms/Scalar.h" 44 #include "llvm/Transforms/Utils.h" 45 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 46 #include "llvm/Transforms/Utils/LoopUtils.h" 47 #include <cassert> 48 #include <utility> 49 #include <vector> 50 51 using namespace llvm; 52 53 #define DEBUG_TYPE "loop-interchange" 54 55 STATISTIC(LoopsInterchanged, "Number of loops interchanged"); 56 57 static cl::opt<int> LoopInterchangeCostThreshold( 58 "loop-interchange-threshold", cl::init(0), cl::Hidden, 59 cl::desc("Interchange if you gain more than this number")); 60 61 namespace { 62 63 using LoopVector = SmallVector<Loop *, 8>; 64 65 // TODO: Check if we can use a sparse matrix here. 66 using CharMatrix = std::vector<std::vector<char>>; 67 68 } // end anonymous namespace 69 70 // Maximum number of dependencies that can be handled in the dependency matrix. 71 static const unsigned MaxMemInstrCount = 100; 72 73 // Maximum loop depth supported. 74 static const unsigned MaxLoopNestDepth = 10; 75 76 #ifdef DUMP_DEP_MATRICIES 77 static void printDepMatrix(CharMatrix &DepMatrix) { 78 for (auto &Row : DepMatrix) { 79 for (auto D : Row) 80 DEBUG(dbgs() << D << " "); 81 DEBUG(dbgs() << "\n"); 82 } 83 } 84 #endif 85 86 static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level, 87 Loop *L, DependenceInfo *DI) { 88 using ValueVector = SmallVector<Value *, 16>; 89 90 ValueVector MemInstr; 91 92 // For each block. 93 for (BasicBlock *BB : L->blocks()) { 94 // Scan the BB and collect legal loads and stores. 95 for (Instruction &I : *BB) { 96 if (!isa<Instruction>(I)) 97 return false; 98 if (auto *Ld = dyn_cast<LoadInst>(&I)) { 99 if (!Ld->isSimple()) 100 return false; 101 MemInstr.push_back(&I); 102 } else if (auto *St = dyn_cast<StoreInst>(&I)) { 103 if (!St->isSimple()) 104 return false; 105 MemInstr.push_back(&I); 106 } 107 } 108 } 109 110 DEBUG(dbgs() << "Found " << MemInstr.size() 111 << " Loads and Stores to analyze\n"); 112 113 ValueVector::iterator I, IE, J, JE; 114 115 for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) { 116 for (J = I, JE = MemInstr.end(); J != JE; ++J) { 117 std::vector<char> Dep; 118 Instruction *Src = cast<Instruction>(*I); 119 Instruction *Dst = cast<Instruction>(*J); 120 if (Src == Dst) 121 continue; 122 // Ignore Input dependencies. 123 if (isa<LoadInst>(Src) && isa<LoadInst>(Dst)) 124 continue; 125 // Track Output, Flow, and Anti dependencies. 126 if (auto D = DI->depends(Src, Dst, true)) { 127 assert(D->isOrdered() && "Expected an output, flow or anti dep."); 128 DEBUG(StringRef DepType = 129 D->isFlow() ? "flow" : D->isAnti() ? "anti" : "output"; 130 dbgs() << "Found " << DepType 131 << " dependency between Src and Dst\n" 132 << " Src:" << *Src << "\n Dst:" << *Dst << '\n'); 133 unsigned Levels = D->getLevels(); 134 char Direction; 135 for (unsigned II = 1; II <= Levels; ++II) { 136 const SCEV *Distance = D->getDistance(II); 137 const SCEVConstant *SCEVConst = 138 dyn_cast_or_null<SCEVConstant>(Distance); 139 if (SCEVConst) { 140 const ConstantInt *CI = SCEVConst->getValue(); 141 if (CI->isNegative()) 142 Direction = '<'; 143 else if (CI->isZero()) 144 Direction = '='; 145 else 146 Direction = '>'; 147 Dep.push_back(Direction); 148 } else if (D->isScalar(II)) { 149 Direction = 'S'; 150 Dep.push_back(Direction); 151 } else { 152 unsigned Dir = D->getDirection(II); 153 if (Dir == Dependence::DVEntry::LT || 154 Dir == Dependence::DVEntry::LE) 155 Direction = '<'; 156 else if (Dir == Dependence::DVEntry::GT || 157 Dir == Dependence::DVEntry::GE) 158 Direction = '>'; 159 else if (Dir == Dependence::DVEntry::EQ) 160 Direction = '='; 161 else 162 Direction = '*'; 163 Dep.push_back(Direction); 164 } 165 } 166 while (Dep.size() != Level) { 167 Dep.push_back('I'); 168 } 169 170 DepMatrix.push_back(Dep); 171 if (DepMatrix.size() > MaxMemInstrCount) { 172 DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount 173 << " dependencies inside loop\n"); 174 return false; 175 } 176 } 177 } 178 } 179 180 return true; 181 } 182 183 // A loop is moved from index 'from' to an index 'to'. Update the Dependence 184 // matrix by exchanging the two columns. 185 static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx, 186 unsigned ToIndx) { 187 unsigned numRows = DepMatrix.size(); 188 for (unsigned i = 0; i < numRows; ++i) { 189 char TmpVal = DepMatrix[i][ToIndx]; 190 DepMatrix[i][ToIndx] = DepMatrix[i][FromIndx]; 191 DepMatrix[i][FromIndx] = TmpVal; 192 } 193 } 194 195 // Checks if outermost non '=','S'or'I' dependence in the dependence matrix is 196 // '>' 197 static bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row, 198 unsigned Column) { 199 for (unsigned i = 0; i <= Column; ++i) { 200 if (DepMatrix[Row][i] == '<') 201 return false; 202 if (DepMatrix[Row][i] == '>') 203 return true; 204 } 205 // All dependencies were '=','S' or 'I' 206 return false; 207 } 208 209 // Checks if no dependence exist in the dependency matrix in Row before Column. 210 static bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row, 211 unsigned Column) { 212 for (unsigned i = 0; i < Column; ++i) { 213 if (DepMatrix[Row][i] != '=' && DepMatrix[Row][i] != 'S' && 214 DepMatrix[Row][i] != 'I') 215 return false; 216 } 217 return true; 218 } 219 220 static bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row, 221 unsigned OuterLoopId, char InnerDep, 222 char OuterDep) { 223 if (isOuterMostDepPositive(DepMatrix, Row, OuterLoopId)) 224 return false; 225 226 if (InnerDep == OuterDep) 227 return true; 228 229 // It is legal to interchange if and only if after interchange no row has a 230 // '>' direction as the leftmost non-'='. 231 232 if (InnerDep == '=' || InnerDep == 'S' || InnerDep == 'I') 233 return true; 234 235 if (InnerDep == '<') 236 return true; 237 238 if (InnerDep == '>') { 239 // If OuterLoopId represents outermost loop then interchanging will make the 240 // 1st dependency as '>' 241 if (OuterLoopId == 0) 242 return false; 243 244 // If all dependencies before OuterloopId are '=','S'or 'I'. Then 245 // interchanging will result in this row having an outermost non '=' 246 // dependency of '>' 247 if (!containsNoDependence(DepMatrix, Row, OuterLoopId)) 248 return true; 249 } 250 251 return false; 252 } 253 254 // Checks if it is legal to interchange 2 loops. 255 // [Theorem] A permutation of the loops in a perfect nest is legal if and only 256 // if the direction matrix, after the same permutation is applied to its 257 // columns, has no ">" direction as the leftmost non-"=" direction in any row. 258 static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix, 259 unsigned InnerLoopId, 260 unsigned OuterLoopId) { 261 unsigned NumRows = DepMatrix.size(); 262 // For each row check if it is valid to interchange. 263 for (unsigned Row = 0; Row < NumRows; ++Row) { 264 char InnerDep = DepMatrix[Row][InnerLoopId]; 265 char OuterDep = DepMatrix[Row][OuterLoopId]; 266 if (InnerDep == '*' || OuterDep == '*') 267 return false; 268 if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, OuterDep)) 269 return false; 270 } 271 return true; 272 } 273 274 static void populateWorklist(Loop &L, SmallVector<LoopVector, 8> &V) { 275 DEBUG(dbgs() << "Calling populateWorklist on Func: " 276 << L.getHeader()->getParent()->getName() << " Loop: %" 277 << L.getHeader()->getName() << '\n'); 278 LoopVector LoopList; 279 Loop *CurrentLoop = &L; 280 const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops(); 281 while (!Vec->empty()) { 282 // The current loop has multiple subloops in it hence it is not tightly 283 // nested. 284 // Discard all loops above it added into Worklist. 285 if (Vec->size() != 1) { 286 LoopList.clear(); 287 return; 288 } 289 LoopList.push_back(CurrentLoop); 290 CurrentLoop = Vec->front(); 291 Vec = &CurrentLoop->getSubLoops(); 292 } 293 LoopList.push_back(CurrentLoop); 294 V.push_back(std::move(LoopList)); 295 } 296 297 static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) { 298 PHINode *InnerIndexVar = L->getCanonicalInductionVariable(); 299 if (InnerIndexVar) 300 return InnerIndexVar; 301 if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr) 302 return nullptr; 303 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 304 PHINode *PhiVar = cast<PHINode>(I); 305 Type *PhiTy = PhiVar->getType(); 306 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() && 307 !PhiTy->isPointerTy()) 308 return nullptr; 309 const SCEVAddRecExpr *AddRec = 310 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar)); 311 if (!AddRec || !AddRec->isAffine()) 312 continue; 313 const SCEV *Step = AddRec->getStepRecurrence(*SE); 314 if (!isa<SCEVConstant>(Step)) 315 continue; 316 // Found the induction variable. 317 // FIXME: Handle loops with more than one induction variable. Note that, 318 // currently, legality makes sure we have only one induction variable. 319 return PhiVar; 320 } 321 return nullptr; 322 } 323 324 namespace { 325 326 /// LoopInterchangeLegality checks if it is legal to interchange the loop. 327 class LoopInterchangeLegality { 328 public: 329 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE, 330 LoopInfo *LI, DominatorTree *DT, bool PreserveLCSSA, 331 OptimizationRemarkEmitter *ORE) 332 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), 333 PreserveLCSSA(PreserveLCSSA), ORE(ORE) {} 334 335 /// Check if the loops can be interchanged. 336 bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId, 337 CharMatrix &DepMatrix); 338 339 /// Check if the loop structure is understood. We do not handle triangular 340 /// loops for now. 341 bool isLoopStructureUnderstood(PHINode *InnerInductionVar); 342 343 bool currentLimitations(); 344 345 bool hasInnerLoopReduction() { return InnerLoopHasReduction; } 346 347 private: 348 bool tightlyNested(Loop *Outer, Loop *Inner); 349 bool containsUnsafeInstructionsInHeader(BasicBlock *BB); 350 bool areAllUsesReductions(Instruction *Ins, Loop *L); 351 bool containsUnsafeInstructionsInLatch(BasicBlock *BB); 352 bool findInductionAndReductions(Loop *L, 353 SmallVector<PHINode *, 8> &Inductions, 354 SmallVector<PHINode *, 8> &Reductions); 355 356 Loop *OuterLoop; 357 Loop *InnerLoop; 358 359 ScalarEvolution *SE; 360 LoopInfo *LI; 361 DominatorTree *DT; 362 bool PreserveLCSSA; 363 364 /// Interface to emit optimization remarks. 365 OptimizationRemarkEmitter *ORE; 366 367 bool InnerLoopHasReduction = false; 368 }; 369 370 /// LoopInterchangeProfitability checks if it is profitable to interchange the 371 /// loop. 372 class LoopInterchangeProfitability { 373 public: 374 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE, 375 OptimizationRemarkEmitter *ORE) 376 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), ORE(ORE) {} 377 378 /// Check if the loop interchange is profitable. 379 bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId, 380 CharMatrix &DepMatrix); 381 382 private: 383 int getInstrOrderCost(); 384 385 Loop *OuterLoop; 386 Loop *InnerLoop; 387 388 /// Scev analysis. 389 ScalarEvolution *SE; 390 391 /// Interface to emit optimization remarks. 392 OptimizationRemarkEmitter *ORE; 393 }; 394 395 /// LoopInterchangeTransform interchanges the loop. 396 class LoopInterchangeTransform { 397 public: 398 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE, 399 LoopInfo *LI, DominatorTree *DT, 400 BasicBlock *LoopNestExit, 401 bool InnerLoopContainsReductions) 402 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), 403 LoopExit(LoopNestExit), 404 InnerLoopHasReduction(InnerLoopContainsReductions) {} 405 406 /// Interchange OuterLoop and InnerLoop. 407 bool transform(); 408 void restructureLoops(Loop *NewInner, Loop *NewOuter, 409 BasicBlock *OrigInnerPreHeader, 410 BasicBlock *OrigOuterPreHeader); 411 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop); 412 413 private: 414 void splitInnerLoopLatch(Instruction *); 415 void splitInnerLoopHeader(); 416 bool adjustLoopLinks(); 417 void adjustLoopPreheaders(); 418 bool adjustLoopBranches(); 419 void updateIncomingBlock(BasicBlock *CurrBlock, BasicBlock *OldPred, 420 BasicBlock *NewPred); 421 422 Loop *OuterLoop; 423 Loop *InnerLoop; 424 425 /// Scev analysis. 426 ScalarEvolution *SE; 427 428 LoopInfo *LI; 429 DominatorTree *DT; 430 BasicBlock *LoopExit; 431 bool InnerLoopHasReduction; 432 }; 433 434 // Main LoopInterchange Pass. 435 struct LoopInterchange : public FunctionPass { 436 static char ID; 437 ScalarEvolution *SE = nullptr; 438 LoopInfo *LI = nullptr; 439 DependenceInfo *DI = nullptr; 440 DominatorTree *DT = nullptr; 441 bool PreserveLCSSA; 442 443 /// Interface to emit optimization remarks. 444 OptimizationRemarkEmitter *ORE; 445 446 LoopInterchange() : FunctionPass(ID) { 447 initializeLoopInterchangePass(*PassRegistry::getPassRegistry()); 448 } 449 450 void getAnalysisUsage(AnalysisUsage &AU) const override { 451 AU.addRequired<ScalarEvolutionWrapperPass>(); 452 AU.addRequired<AAResultsWrapperPass>(); 453 AU.addRequired<DominatorTreeWrapperPass>(); 454 AU.addRequired<LoopInfoWrapperPass>(); 455 AU.addRequired<DependenceAnalysisWrapperPass>(); 456 AU.addRequiredID(LoopSimplifyID); 457 AU.addRequiredID(LCSSAID); 458 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 459 460 AU.addPreserved<DominatorTreeWrapperPass>(); 461 AU.addPreserved<LoopInfoWrapperPass>(); 462 } 463 464 bool runOnFunction(Function &F) override { 465 if (skipFunction(F)) 466 return false; 467 468 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 469 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 470 DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI(); 471 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 472 ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 473 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID); 474 475 // Build up a worklist of loop pairs to analyze. 476 SmallVector<LoopVector, 8> Worklist; 477 478 for (Loop *L : *LI) 479 populateWorklist(*L, Worklist); 480 481 DEBUG(dbgs() << "Worklist size = " << Worklist.size() << "\n"); 482 bool Changed = true; 483 while (!Worklist.empty()) { 484 LoopVector LoopList = Worklist.pop_back_val(); 485 Changed = processLoopList(LoopList, F); 486 } 487 return Changed; 488 } 489 490 bool isComputableLoopNest(LoopVector LoopList) { 491 for (Loop *L : LoopList) { 492 const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L); 493 if (ExitCountOuter == SE->getCouldNotCompute()) { 494 DEBUG(dbgs() << "Couldn't compute backedge count\n"); 495 return false; 496 } 497 if (L->getNumBackEdges() != 1) { 498 DEBUG(dbgs() << "NumBackEdges is not equal to 1\n"); 499 return false; 500 } 501 if (!L->getExitingBlock()) { 502 DEBUG(dbgs() << "Loop doesn't have unique exit block\n"); 503 return false; 504 } 505 } 506 return true; 507 } 508 509 unsigned selectLoopForInterchange(const LoopVector &LoopList) { 510 // TODO: Add a better heuristic to select the loop to be interchanged based 511 // on the dependence matrix. Currently we select the innermost loop. 512 return LoopList.size() - 1; 513 } 514 515 bool processLoopList(LoopVector LoopList, Function &F) { 516 bool Changed = false; 517 unsigned LoopNestDepth = LoopList.size(); 518 if (LoopNestDepth < 2) { 519 DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n"); 520 return false; 521 } 522 if (LoopNestDepth > MaxLoopNestDepth) { 523 DEBUG(dbgs() << "Cannot handle loops of depth greater than " 524 << MaxLoopNestDepth << "\n"); 525 return false; 526 } 527 if (!isComputableLoopNest(LoopList)) { 528 DEBUG(dbgs() << "Not valid loop candidate for interchange\n"); 529 return false; 530 } 531 532 DEBUG(dbgs() << "Processing LoopList of size = " << LoopNestDepth << "\n"); 533 534 CharMatrix DependencyMatrix; 535 Loop *OuterMostLoop = *(LoopList.begin()); 536 if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth, 537 OuterMostLoop, DI)) { 538 DEBUG(dbgs() << "Populating dependency matrix failed\n"); 539 return false; 540 } 541 #ifdef DUMP_DEP_MATRICIES 542 DEBUG(dbgs() << "Dependence before interchange\n"); 543 printDepMatrix(DependencyMatrix); 544 #endif 545 546 // Get the Outermost loop exit. 547 BasicBlock *LoopNestExit = OuterMostLoop->getExitBlock(); 548 if (!LoopNestExit) { 549 DEBUG(dbgs() << "OuterMostLoop needs an unique exit block"); 550 return false; 551 } 552 553 unsigned SelecLoopId = selectLoopForInterchange(LoopList); 554 // Move the selected loop outwards to the best possible position. 555 for (unsigned i = SelecLoopId; i > 0; i--) { 556 bool Interchanged = 557 processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix); 558 if (!Interchanged) 559 return Changed; 560 // Loops interchanged reflect the same in LoopList 561 std::swap(LoopList[i - 1], LoopList[i]); 562 563 // Update the DependencyMatrix 564 interChangeDependencies(DependencyMatrix, i, i - 1); 565 #ifdef DUMP_DEP_MATRICIES 566 DEBUG(dbgs() << "Dependence after interchange\n"); 567 printDepMatrix(DependencyMatrix); 568 #endif 569 Changed |= Interchanged; 570 } 571 return Changed; 572 } 573 574 bool processLoop(LoopVector LoopList, unsigned InnerLoopId, 575 unsigned OuterLoopId, BasicBlock *LoopNestExit, 576 std::vector<std::vector<char>> &DependencyMatrix) { 577 DEBUG(dbgs() << "Processing Inner Loop Id = " << InnerLoopId 578 << " and OuterLoopId = " << OuterLoopId << "\n"); 579 Loop *InnerLoop = LoopList[InnerLoopId]; 580 Loop *OuterLoop = LoopList[OuterLoopId]; 581 582 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, LI, DT, 583 PreserveLCSSA, ORE); 584 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) { 585 DEBUG(dbgs() << "Not interchanging loops. Cannot prove legality.\n"); 586 return false; 587 } 588 DEBUG(dbgs() << "Loops are legal to interchange\n"); 589 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE, ORE); 590 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) { 591 DEBUG(dbgs() << "Interchanging loops not profitable.\n"); 592 return false; 593 } 594 595 ORE->emit([&]() { 596 return OptimizationRemark(DEBUG_TYPE, "Interchanged", 597 InnerLoop->getStartLoc(), 598 InnerLoop->getHeader()) 599 << "Loop interchanged with enclosing loop."; 600 }); 601 602 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, 603 LoopNestExit, LIL.hasInnerLoopReduction()); 604 LIT.transform(); 605 DEBUG(dbgs() << "Loops interchanged.\n"); 606 LoopsInterchanged++; 607 return true; 608 } 609 }; 610 611 } // end anonymous namespace 612 613 bool LoopInterchangeLegality::areAllUsesReductions(Instruction *Ins, Loop *L) { 614 return llvm::none_of(Ins->users(), [=](User *U) -> bool { 615 auto *UserIns = dyn_cast<PHINode>(U); 616 RecurrenceDescriptor RD; 617 return !UserIns || !RecurrenceDescriptor::isReductionPHI(UserIns, L, RD); 618 }); 619 } 620 621 bool LoopInterchangeLegality::containsUnsafeInstructionsInHeader( 622 BasicBlock *BB) { 623 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) { 624 // Load corresponding to reduction PHI's are safe while concluding if 625 // tightly nested. 626 if (LoadInst *L = dyn_cast<LoadInst>(I)) { 627 if (!areAllUsesReductions(L, InnerLoop)) 628 return true; 629 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory()) 630 return true; 631 } 632 return false; 633 } 634 635 bool LoopInterchangeLegality::containsUnsafeInstructionsInLatch( 636 BasicBlock *BB) { 637 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) { 638 // Stores corresponding to reductions are safe while concluding if tightly 639 // nested. 640 if (StoreInst *L = dyn_cast<StoreInst>(I)) { 641 if (!isa<PHINode>(L->getOperand(0))) 642 return true; 643 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory()) 644 return true; 645 } 646 return false; 647 } 648 649 bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) { 650 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 651 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 652 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); 653 654 DEBUG(dbgs() << "Checking if loops are tightly nested\n"); 655 656 // A perfectly nested loop will not have any branch in between the outer and 657 // inner block i.e. outer header will branch to either inner preheader and 658 // outerloop latch. 659 BranchInst *OuterLoopHeaderBI = 660 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); 661 if (!OuterLoopHeaderBI) 662 return false; 663 664 for (BasicBlock *Succ : OuterLoopHeaderBI->successors()) 665 if (Succ != InnerLoopPreHeader && Succ != OuterLoopLatch) 666 return false; 667 668 DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch\n"); 669 // We do not have any basic block in between now make sure the outer header 670 // and outer loop latch doesn't contain any unsafe instructions. 671 if (containsUnsafeInstructionsInHeader(OuterLoopHeader) || 672 containsUnsafeInstructionsInLatch(OuterLoopLatch)) 673 return false; 674 675 DEBUG(dbgs() << "Loops are perfectly nested\n"); 676 // We have a perfect loop nest. 677 return true; 678 } 679 680 bool LoopInterchangeLegality::isLoopStructureUnderstood( 681 PHINode *InnerInduction) { 682 unsigned Num = InnerInduction->getNumOperands(); 683 BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader(); 684 for (unsigned i = 0; i < Num; ++i) { 685 Value *Val = InnerInduction->getOperand(i); 686 if (isa<Constant>(Val)) 687 continue; 688 Instruction *I = dyn_cast<Instruction>(Val); 689 if (!I) 690 return false; 691 // TODO: Handle triangular loops. 692 // e.g. for(int i=0;i<N;i++) 693 // for(int j=i;j<N;j++) 694 unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i); 695 if (InnerInduction->getIncomingBlock(IncomBlockIndx) == 696 InnerLoopPreheader && 697 !OuterLoop->isLoopInvariant(I)) { 698 return false; 699 } 700 } 701 return true; 702 } 703 704 bool LoopInterchangeLegality::findInductionAndReductions( 705 Loop *L, SmallVector<PHINode *, 8> &Inductions, 706 SmallVector<PHINode *, 8> &Reductions) { 707 if (!L->getLoopLatch() || !L->getLoopPredecessor()) 708 return false; 709 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 710 RecurrenceDescriptor RD; 711 InductionDescriptor ID; 712 PHINode *PHI = cast<PHINode>(I); 713 if (InductionDescriptor::isInductionPHI(PHI, L, SE, ID)) 714 Inductions.push_back(PHI); 715 else if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD)) 716 Reductions.push_back(PHI); 717 else { 718 DEBUG( 719 dbgs() << "Failed to recognize PHI as an induction or reduction.\n"); 720 return false; 721 } 722 } 723 return true; 724 } 725 726 static bool containsSafePHI(BasicBlock *Block, bool isOuterLoopExitBlock) { 727 for (auto I = Block->begin(); isa<PHINode>(I); ++I) { 728 PHINode *PHI = cast<PHINode>(I); 729 // Reduction lcssa phi will have only 1 incoming block that from loop latch. 730 if (PHI->getNumIncomingValues() > 1) 731 return false; 732 Instruction *Ins = dyn_cast<Instruction>(PHI->getIncomingValue(0)); 733 if (!Ins) 734 return false; 735 // Incoming value for lcssa phi's in outer loop exit can only be inner loop 736 // exits lcssa phi else it would not be tightly nested. 737 if (!isa<PHINode>(Ins) && isOuterLoopExitBlock) 738 return false; 739 } 740 return true; 741 } 742 743 // This function indicates the current limitations in the transform as a result 744 // of which we do not proceed. 745 bool LoopInterchangeLegality::currentLimitations() { 746 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 747 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 748 749 // transform currently expects the loop latches to also be the exiting 750 // blocks. 751 if (InnerLoop->getExitingBlock() != InnerLoopLatch || 752 OuterLoop->getExitingBlock() != OuterLoop->getLoopLatch() || 753 !isa<BranchInst>(InnerLoopLatch->getTerminator()) || 754 !isa<BranchInst>(OuterLoop->getLoopLatch()->getTerminator())) { 755 DEBUG(dbgs() << "Loops where the latch is not the exiting block are not" 756 << " supported currently.\n"); 757 ORE->emit([&]() { 758 return OptimizationRemarkMissed(DEBUG_TYPE, "ExitingNotLatch", 759 OuterLoop->getStartLoc(), 760 OuterLoop->getHeader()) 761 << "Loops where the latch is not the exiting block cannot be" 762 " interchange currently."; 763 }); 764 return true; 765 } 766 767 PHINode *InnerInductionVar; 768 SmallVector<PHINode *, 8> Inductions; 769 SmallVector<PHINode *, 8> Reductions; 770 if (!findInductionAndReductions(InnerLoop, Inductions, Reductions)) { 771 DEBUG(dbgs() << "Only inner loops with induction or reduction PHI nodes " 772 << "are supported currently.\n"); 773 ORE->emit([&]() { 774 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIInner", 775 InnerLoop->getStartLoc(), 776 InnerLoop->getHeader()) 777 << "Only inner loops with induction or reduction PHI nodes can be" 778 " interchange currently."; 779 }); 780 return true; 781 } 782 783 // TODO: Currently we handle only loops with 1 induction variable. 784 if (Inductions.size() != 1) { 785 DEBUG(dbgs() << "We currently only support loops with 1 induction variable." 786 << "Failed to interchange due to current limitation\n"); 787 ORE->emit([&]() { 788 return OptimizationRemarkMissed(DEBUG_TYPE, "MultiInductionInner", 789 InnerLoop->getStartLoc(), 790 InnerLoop->getHeader()) 791 << "Only inner loops with 1 induction variable can be " 792 "interchanged currently."; 793 }); 794 return true; 795 } 796 if (Reductions.size() > 0) 797 InnerLoopHasReduction = true; 798 799 InnerInductionVar = Inductions.pop_back_val(); 800 Reductions.clear(); 801 if (!findInductionAndReductions(OuterLoop, Inductions, Reductions)) { 802 DEBUG(dbgs() << "Only outer loops with induction or reduction PHI nodes " 803 << "are supported currently.\n"); 804 ORE->emit([&]() { 805 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedPHIOuter", 806 OuterLoop->getStartLoc(), 807 OuterLoop->getHeader()) 808 << "Only outer loops with induction or reduction PHI nodes can be" 809 " interchanged currently."; 810 }); 811 return true; 812 } 813 814 // Outer loop cannot have reduction because then loops will not be tightly 815 // nested. 816 if (!Reductions.empty()) { 817 DEBUG(dbgs() << "Outer loops with reductions are not supported " 818 << "currently.\n"); 819 ORE->emit([&]() { 820 return OptimizationRemarkMissed(DEBUG_TYPE, "ReductionsOuter", 821 OuterLoop->getStartLoc(), 822 OuterLoop->getHeader()) 823 << "Outer loops with reductions cannot be interchangeed " 824 "currently."; 825 }); 826 return true; 827 } 828 // TODO: Currently we handle only loops with 1 induction variable. 829 if (Inductions.size() != 1) { 830 DEBUG(dbgs() << "Loops with more than 1 induction variables are not " 831 << "supported currently.\n"); 832 ORE->emit([&]() { 833 return OptimizationRemarkMissed(DEBUG_TYPE, "MultiIndutionOuter", 834 OuterLoop->getStartLoc(), 835 OuterLoop->getHeader()) 836 << "Only outer loops with 1 induction variable can be " 837 "interchanged currently."; 838 }); 839 return true; 840 } 841 842 // TODO: Triangular loops are not handled for now. 843 if (!isLoopStructureUnderstood(InnerInductionVar)) { 844 DEBUG(dbgs() << "Loop structure not understood by pass\n"); 845 ORE->emit([&]() { 846 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedStructureInner", 847 InnerLoop->getStartLoc(), 848 InnerLoop->getHeader()) 849 << "Inner loop structure not understood currently."; 850 }); 851 return true; 852 } 853 854 // TODO: We only handle LCSSA PHI's corresponding to reduction for now. 855 BasicBlock *InnerExit = InnerLoop->getExitBlock(); 856 if (!containsSafePHI(InnerExit, false)) { 857 DEBUG(dbgs() << "Can only handle LCSSA PHIs in inner loops currently.\n"); 858 ORE->emit([&]() { 859 return OptimizationRemarkMissed(DEBUG_TYPE, "NoLCSSAPHIOuterInner", 860 InnerLoop->getStartLoc(), 861 InnerLoop->getHeader()) 862 << "Only inner loops with LCSSA PHIs can be interchange " 863 "currently."; 864 }); 865 return true; 866 } 867 868 // TODO: Current limitation: Since we split the inner loop latch at the point 869 // were induction variable is incremented (induction.next); We cannot have 870 // more than 1 user of induction.next since it would result in broken code 871 // after split. 872 // e.g. 873 // for(i=0;i<N;i++) { 874 // for(j = 0;j<M;j++) { 875 // A[j+1][i+2] = A[j][i]+k; 876 // } 877 // } 878 Instruction *InnerIndexVarInc = nullptr; 879 if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader) 880 InnerIndexVarInc = 881 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1)); 882 else 883 InnerIndexVarInc = 884 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0)); 885 886 if (!InnerIndexVarInc) { 887 DEBUG(dbgs() << "Did not find an instruction to increment the induction " 888 << "variable.\n"); 889 ORE->emit([&]() { 890 return OptimizationRemarkMissed(DEBUG_TYPE, "NoIncrementInInner", 891 InnerLoop->getStartLoc(), 892 InnerLoop->getHeader()) 893 << "The inner loop does not increment the induction variable."; 894 }); 895 return true; 896 } 897 898 // Since we split the inner loop latch on this induction variable. Make sure 899 // we do not have any instruction between the induction variable and branch 900 // instruction. 901 902 bool FoundInduction = false; 903 for (const Instruction &I : 904 llvm::reverse(InnerLoopLatch->instructionsWithoutDebug())) { 905 if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I) || 906 isa<ZExtInst>(I)) 907 continue; 908 909 // We found an instruction. If this is not induction variable then it is not 910 // safe to split this loop latch. 911 if (!I.isIdenticalTo(InnerIndexVarInc)) { 912 DEBUG(dbgs() << "Found unsupported instructions between induction " 913 << "variable increment and branch.\n"); 914 ORE->emit([&]() { 915 return OptimizationRemarkMissed( 916 DEBUG_TYPE, "UnsupportedInsBetweenInduction", 917 InnerLoop->getStartLoc(), InnerLoop->getHeader()) 918 << "Found unsupported instruction between induction variable " 919 "increment and branch."; 920 }); 921 return true; 922 } 923 924 FoundInduction = true; 925 break; 926 } 927 // The loop latch ended and we didn't find the induction variable return as 928 // current limitation. 929 if (!FoundInduction) { 930 DEBUG(dbgs() << "Did not find the induction variable.\n"); 931 ORE->emit([&]() { 932 return OptimizationRemarkMissed(DEBUG_TYPE, "NoIndutionVariable", 933 InnerLoop->getStartLoc(), 934 InnerLoop->getHeader()) 935 << "Did not find the induction variable."; 936 }); 937 return true; 938 } 939 return false; 940 } 941 942 // We currently support LCSSA PHI nodes in the outer loop exit, if their 943 // incoming values do not come from the outer loop latch or if the 944 // outer loop latch has a single predecessor. In that case, the value will 945 // be available if both the inner and outer loop conditions are true, which 946 // will still be true after interchanging. If we have multiple predecessor, 947 // that may not be the case, e.g. because the outer loop latch may be executed 948 // if the inner loop is not executed. 949 static bool areLoopExitPHIsSupported(Loop *OuterLoop, Loop *InnerLoop) { 950 BasicBlock *LoopNestExit = OuterLoop->getUniqueExitBlock(); 951 for (PHINode &PHI : LoopNestExit->phis()) { 952 // FIXME: We currently are not able to detect floating point reductions 953 // and have to use floating point PHIs as a proxy to prevent 954 // interchanging in the presence of floating point reductions. 955 if (PHI.getType()->isFloatingPointTy()) 956 return false; 957 for (unsigned i = 0; i < PHI.getNumIncomingValues(); i++) { 958 Instruction *IncomingI = dyn_cast<Instruction>(PHI.getIncomingValue(i)); 959 if (!IncomingI || IncomingI->getParent() != OuterLoop->getLoopLatch()) 960 continue; 961 962 // The incoming value is defined in the outer loop latch. Currently we 963 // only support that in case the outer loop latch has a single predecessor. 964 // This guarantees that the outer loop latch is executed if and only if 965 // the inner loop is executed (because tightlyNested() guarantees that the 966 // outer loop header only branches to the inner loop or the outer loop 967 // latch). 968 // FIXME: We could weaken this logic and allow multiple predecessors, 969 // if the values are produced outside the loop latch. We would need 970 // additional logic to update the PHI nodes in the exit block as 971 // well. 972 if (OuterLoop->getLoopLatch()->getUniquePredecessor() == nullptr) 973 return false; 974 } 975 } 976 return true; 977 } 978 979 bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId, 980 unsigned OuterLoopId, 981 CharMatrix &DepMatrix) { 982 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) { 983 DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId 984 << " and OuterLoopId = " << OuterLoopId 985 << " due to dependence\n"); 986 ORE->emit([&]() { 987 return OptimizationRemarkMissed(DEBUG_TYPE, "Dependence", 988 InnerLoop->getStartLoc(), 989 InnerLoop->getHeader()) 990 << "Cannot interchange loops due to dependences."; 991 }); 992 return false; 993 } 994 // Check if outer and inner loop contain legal instructions only. 995 for (auto *BB : OuterLoop->blocks()) 996 for (Instruction &I : BB->instructionsWithoutDebug()) 997 if (CallInst *CI = dyn_cast<CallInst>(&I)) { 998 // readnone functions do not prevent interchanging. 999 if (CI->doesNotReadMemory()) 1000 continue; 1001 DEBUG(dbgs() << "Loops with call instructions cannot be interchanged " 1002 << "safely."); 1003 ORE->emit([&]() { 1004 return OptimizationRemarkMissed(DEBUG_TYPE, "CallInst", 1005 CI->getDebugLoc(), 1006 CI->getParent()) 1007 << "Cannot interchange loops due to call instruction."; 1008 }); 1009 1010 return false; 1011 } 1012 1013 // Create unique Preheaders if we already do not have one. 1014 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); 1015 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1016 1017 // Create a unique outer preheader - 1018 // 1) If OuterLoop preheader is not present. 1019 // 2) If OuterLoop Preheader is same as OuterLoop Header 1020 // 3) If OuterLoop Preheader is same as Header of the previous loop. 1021 // 4) If OuterLoop Preheader is Entry node. 1022 if (!OuterLoopPreHeader || OuterLoopPreHeader == OuterLoop->getHeader() || 1023 isa<PHINode>(OuterLoopPreHeader->begin()) || 1024 !OuterLoopPreHeader->getUniquePredecessor()) { 1025 OuterLoopPreHeader = 1026 InsertPreheaderForLoop(OuterLoop, DT, LI, PreserveLCSSA); 1027 } 1028 1029 if (!InnerLoopPreHeader || InnerLoopPreHeader == InnerLoop->getHeader() || 1030 InnerLoopPreHeader == OuterLoop->getHeader()) { 1031 InnerLoopPreHeader = 1032 InsertPreheaderForLoop(InnerLoop, DT, LI, PreserveLCSSA); 1033 } 1034 1035 // TODO: The loops could not be interchanged due to current limitations in the 1036 // transform module. 1037 if (currentLimitations()) { 1038 DEBUG(dbgs() << "Not legal because of current transform limitation\n"); 1039 return false; 1040 } 1041 1042 // Check if the loops are tightly nested. 1043 if (!tightlyNested(OuterLoop, InnerLoop)) { 1044 DEBUG(dbgs() << "Loops not tightly nested\n"); 1045 ORE->emit([&]() { 1046 return OptimizationRemarkMissed(DEBUG_TYPE, "NotTightlyNested", 1047 InnerLoop->getStartLoc(), 1048 InnerLoop->getHeader()) 1049 << "Cannot interchange loops because they are not tightly " 1050 "nested."; 1051 }); 1052 return false; 1053 } 1054 1055 if (!areLoopExitPHIsSupported(OuterLoop, InnerLoop)) { 1056 DEBUG(dbgs() << "Found unsupported PHI nodes in outer loop exit.\n"); 1057 ORE->emit([&]() { 1058 return OptimizationRemarkMissed(DEBUG_TYPE, "UnsupportedExitPHI", 1059 OuterLoop->getStartLoc(), 1060 OuterLoop->getHeader()) 1061 << "Found unsupported PHI node in loop exit."; 1062 }); 1063 return false; 1064 } 1065 1066 return true; 1067 } 1068 1069 int LoopInterchangeProfitability::getInstrOrderCost() { 1070 unsigned GoodOrder, BadOrder; 1071 BadOrder = GoodOrder = 0; 1072 for (BasicBlock *BB : InnerLoop->blocks()) { 1073 for (Instruction &Ins : *BB) { 1074 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) { 1075 unsigned NumOp = GEP->getNumOperands(); 1076 bool FoundInnerInduction = false; 1077 bool FoundOuterInduction = false; 1078 for (unsigned i = 0; i < NumOp; ++i) { 1079 const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i)); 1080 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal); 1081 if (!AR) 1082 continue; 1083 1084 // If we find the inner induction after an outer induction e.g. 1085 // for(int i=0;i<N;i++) 1086 // for(int j=0;j<N;j++) 1087 // A[i][j] = A[i-1][j-1]+k; 1088 // then it is a good order. 1089 if (AR->getLoop() == InnerLoop) { 1090 // We found an InnerLoop induction after OuterLoop induction. It is 1091 // a good order. 1092 FoundInnerInduction = true; 1093 if (FoundOuterInduction) { 1094 GoodOrder++; 1095 break; 1096 } 1097 } 1098 // If we find the outer induction after an inner induction e.g. 1099 // for(int i=0;i<N;i++) 1100 // for(int j=0;j<N;j++) 1101 // A[j][i] = A[j-1][i-1]+k; 1102 // then it is a bad order. 1103 if (AR->getLoop() == OuterLoop) { 1104 // We found an OuterLoop induction after InnerLoop induction. It is 1105 // a bad order. 1106 FoundOuterInduction = true; 1107 if (FoundInnerInduction) { 1108 BadOrder++; 1109 break; 1110 } 1111 } 1112 } 1113 } 1114 } 1115 } 1116 return GoodOrder - BadOrder; 1117 } 1118 1119 static bool isProfitableForVectorization(unsigned InnerLoopId, 1120 unsigned OuterLoopId, 1121 CharMatrix &DepMatrix) { 1122 // TODO: Improve this heuristic to catch more cases. 1123 // If the inner loop is loop independent or doesn't carry any dependency it is 1124 // profitable to move this to outer position. 1125 for (auto &Row : DepMatrix) { 1126 if (Row[InnerLoopId] != 'S' && Row[InnerLoopId] != 'I') 1127 return false; 1128 // TODO: We need to improve this heuristic. 1129 if (Row[OuterLoopId] != '=') 1130 return false; 1131 } 1132 // If outer loop has dependence and inner loop is loop independent then it is 1133 // profitable to interchange to enable parallelism. 1134 // If there are no dependences, interchanging will not improve anything. 1135 return !DepMatrix.empty(); 1136 } 1137 1138 bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId, 1139 unsigned OuterLoopId, 1140 CharMatrix &DepMatrix) { 1141 // TODO: Add better profitability checks. 1142 // e.g 1143 // 1) Construct dependency matrix and move the one with no loop carried dep 1144 // inside to enable vectorization. 1145 1146 // This is rough cost estimation algorithm. It counts the good and bad order 1147 // of induction variables in the instruction and allows reordering if number 1148 // of bad orders is more than good. 1149 int Cost = getInstrOrderCost(); 1150 DEBUG(dbgs() << "Cost = " << Cost << "\n"); 1151 if (Cost < -LoopInterchangeCostThreshold) 1152 return true; 1153 1154 // It is not profitable as per current cache profitability model. But check if 1155 // we can move this loop outside to improve parallelism. 1156 if (isProfitableForVectorization(InnerLoopId, OuterLoopId, DepMatrix)) 1157 return true; 1158 1159 ORE->emit([&]() { 1160 return OptimizationRemarkMissed(DEBUG_TYPE, "InterchangeNotProfitable", 1161 InnerLoop->getStartLoc(), 1162 InnerLoop->getHeader()) 1163 << "Interchanging loops is too costly (cost=" 1164 << ore::NV("Cost", Cost) << ", threshold=" 1165 << ore::NV("Threshold", LoopInterchangeCostThreshold) 1166 << ") and it does not improve parallelism."; 1167 }); 1168 return false; 1169 } 1170 1171 void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop, 1172 Loop *InnerLoop) { 1173 for (Loop::iterator I = OuterLoop->begin(), E = OuterLoop->end(); I != E; 1174 ++I) { 1175 if (*I == InnerLoop) { 1176 OuterLoop->removeChildLoop(I); 1177 return; 1178 } 1179 } 1180 llvm_unreachable("Couldn't find loop"); 1181 } 1182 1183 /// Update LoopInfo, after interchanging. NewInner and NewOuter refer to the 1184 /// new inner and outer loop after interchanging: NewInner is the original 1185 /// outer loop and NewOuter is the original inner loop. 1186 /// 1187 /// Before interchanging, we have the following structure 1188 /// Outer preheader 1189 // Outer header 1190 // Inner preheader 1191 // Inner header 1192 // Inner body 1193 // Inner latch 1194 // outer bbs 1195 // Outer latch 1196 // 1197 // After interchanging: 1198 // Inner preheader 1199 // Inner header 1200 // Outer preheader 1201 // Outer header 1202 // Inner body 1203 // outer bbs 1204 // Outer latch 1205 // Inner latch 1206 void LoopInterchangeTransform::restructureLoops( 1207 Loop *NewInner, Loop *NewOuter, BasicBlock *OrigInnerPreHeader, 1208 BasicBlock *OrigOuterPreHeader) { 1209 Loop *OuterLoopParent = OuterLoop->getParentLoop(); 1210 // The original inner loop preheader moves from the new inner loop to 1211 // the parent loop, if there is one. 1212 NewInner->removeBlockFromLoop(OrigInnerPreHeader); 1213 LI->changeLoopFor(OrigInnerPreHeader, OuterLoopParent); 1214 1215 // Switch the loop levels. 1216 if (OuterLoopParent) { 1217 // Remove the loop from its parent loop. 1218 removeChildLoop(OuterLoopParent, NewInner); 1219 removeChildLoop(NewInner, NewOuter); 1220 OuterLoopParent->addChildLoop(NewOuter); 1221 } else { 1222 removeChildLoop(NewInner, NewOuter); 1223 LI->changeTopLevelLoop(NewInner, NewOuter); 1224 } 1225 while (!NewOuter->empty()) 1226 NewInner->addChildLoop(NewOuter->removeChildLoop(NewOuter->begin())); 1227 NewOuter->addChildLoop(NewInner); 1228 1229 // BBs from the original inner loop. 1230 SmallVector<BasicBlock *, 8> OrigInnerBBs(NewOuter->blocks()); 1231 1232 // Add BBs from the original outer loop to the original inner loop (excluding 1233 // BBs already in inner loop) 1234 for (BasicBlock *BB : NewInner->blocks()) 1235 if (LI->getLoopFor(BB) == NewInner) 1236 NewOuter->addBlockEntry(BB); 1237 1238 // Now remove inner loop header and latch from the new inner loop and move 1239 // other BBs (the loop body) to the new inner loop. 1240 BasicBlock *OuterHeader = NewOuter->getHeader(); 1241 BasicBlock *OuterLatch = NewOuter->getLoopLatch(); 1242 for (BasicBlock *BB : OrigInnerBBs) { 1243 // Nothing will change for BBs in child loops. 1244 if (LI->getLoopFor(BB) != NewOuter) 1245 continue; 1246 // Remove the new outer loop header and latch from the new inner loop. 1247 if (BB == OuterHeader || BB == OuterLatch) 1248 NewInner->removeBlockFromLoop(BB); 1249 else 1250 LI->changeLoopFor(BB, NewInner); 1251 } 1252 1253 // The preheader of the original outer loop becomes part of the new 1254 // outer loop. 1255 NewOuter->addBlockEntry(OrigOuterPreHeader); 1256 LI->changeLoopFor(OrigOuterPreHeader, NewOuter); 1257 } 1258 1259 bool LoopInterchangeTransform::transform() { 1260 bool Transformed = false; 1261 Instruction *InnerIndexVar; 1262 1263 if (InnerLoop->getSubLoops().empty()) { 1264 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1265 DEBUG(dbgs() << "Calling Split Inner Loop\n"); 1266 PHINode *InductionPHI = getInductionVariable(InnerLoop, SE); 1267 if (!InductionPHI) { 1268 DEBUG(dbgs() << "Failed to find the point to split loop latch \n"); 1269 return false; 1270 } 1271 1272 if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader) 1273 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1)); 1274 else 1275 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0)); 1276 1277 // Ensure that InductionPHI is the first Phi node as required by 1278 // splitInnerLoopHeader 1279 if (&InductionPHI->getParent()->front() != InductionPHI) 1280 InductionPHI->moveBefore(&InductionPHI->getParent()->front()); 1281 1282 // Split at the place were the induction variable is 1283 // incremented/decremented. 1284 // TODO: This splitting logic may not work always. Fix this. 1285 splitInnerLoopLatch(InnerIndexVar); 1286 DEBUG(dbgs() << "splitInnerLoopLatch done\n"); 1287 1288 // Splits the inner loops phi nodes out into a separate basic block. 1289 splitInnerLoopHeader(); 1290 DEBUG(dbgs() << "splitInnerLoopHeader done\n"); 1291 } 1292 1293 Transformed |= adjustLoopLinks(); 1294 if (!Transformed) { 1295 DEBUG(dbgs() << "adjustLoopLinks failed\n"); 1296 return false; 1297 } 1298 1299 return true; 1300 } 1301 1302 void LoopInterchangeTransform::splitInnerLoopLatch(Instruction *Inc) { 1303 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 1304 BasicBlock *InnerLoopLatchPred = InnerLoopLatch; 1305 InnerLoopLatch = SplitBlock(InnerLoopLatchPred, Inc, DT, LI); 1306 } 1307 1308 void LoopInterchangeTransform::splitInnerLoopHeader() { 1309 // Split the inner loop header out. Here make sure that the reduction PHI's 1310 // stay in the innerloop body. 1311 BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); 1312 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1313 SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI); 1314 if (InnerLoopHasReduction) { 1315 // Adjust Reduction PHI's in the block. The induction PHI must be the first 1316 // PHI in InnerLoopHeader for this to work. 1317 SmallVector<PHINode *, 8> PHIVec; 1318 for (auto I = std::next(InnerLoopHeader->begin()); isa<PHINode>(I); ++I) { 1319 PHINode *PHI = dyn_cast<PHINode>(I); 1320 Value *V = PHI->getIncomingValueForBlock(InnerLoopPreHeader); 1321 PHI->replaceAllUsesWith(V); 1322 PHIVec.push_back((PHI)); 1323 } 1324 for (PHINode *P : PHIVec) { 1325 P->eraseFromParent(); 1326 } 1327 } 1328 1329 DEBUG(dbgs() << "Output of splitInnerLoopHeader InnerLoopHeaderSucc & " 1330 "InnerLoopHeader\n"); 1331 } 1332 1333 /// \brief Move all instructions except the terminator from FromBB right before 1334 /// InsertBefore 1335 static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) { 1336 auto &ToList = InsertBefore->getParent()->getInstList(); 1337 auto &FromList = FromBB->getInstList(); 1338 1339 ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(), 1340 FromBB->getTerminator()->getIterator()); 1341 } 1342 1343 void LoopInterchangeTransform::updateIncomingBlock(BasicBlock *CurrBlock, 1344 BasicBlock *OldPred, 1345 BasicBlock *NewPred) { 1346 for (auto I = CurrBlock->begin(); isa<PHINode>(I); ++I) { 1347 PHINode *PHI = cast<PHINode>(I); 1348 unsigned Num = PHI->getNumIncomingValues(); 1349 for (unsigned i = 0; i < Num; ++i) { 1350 if (PHI->getIncomingBlock(i) == OldPred) 1351 PHI->setIncomingBlock(i, NewPred); 1352 } 1353 } 1354 } 1355 1356 /// \brief Update BI to jump to NewBB instead of OldBB. Records updates to 1357 /// the dominator tree in DTUpdates, if DT should be preserved. 1358 static void updateSuccessor(BranchInst *BI, BasicBlock *OldBB, 1359 BasicBlock *NewBB, 1360 std::vector<DominatorTree::UpdateType> &DTUpdates) { 1361 assert(llvm::count_if(BI->successors(), 1362 [OldBB](BasicBlock *BB) { return BB == OldBB; }) < 2 && 1363 "BI must jump to OldBB at most once."); 1364 for (unsigned i = 0, e = BI->getNumSuccessors(); i < e; ++i) { 1365 if (BI->getSuccessor(i) == OldBB) { 1366 BI->setSuccessor(i, NewBB); 1367 1368 DTUpdates.push_back( 1369 {DominatorTree::UpdateKind::Insert, BI->getParent(), NewBB}); 1370 DTUpdates.push_back( 1371 {DominatorTree::UpdateKind::Delete, BI->getParent(), OldBB}); 1372 break; 1373 } 1374 } 1375 } 1376 1377 bool LoopInterchangeTransform::adjustLoopBranches() { 1378 DEBUG(dbgs() << "adjustLoopBranches called\n"); 1379 std::vector<DominatorTree::UpdateType> DTUpdates; 1380 1381 // Adjust the loop preheader 1382 BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); 1383 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 1384 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 1385 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); 1386 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); 1387 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1388 BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor(); 1389 BasicBlock *InnerLoopLatchPredecessor = 1390 InnerLoopLatch->getUniquePredecessor(); 1391 BasicBlock *InnerLoopLatchSuccessor; 1392 BasicBlock *OuterLoopLatchSuccessor; 1393 1394 BranchInst *OuterLoopLatchBI = 1395 dyn_cast<BranchInst>(OuterLoopLatch->getTerminator()); 1396 BranchInst *InnerLoopLatchBI = 1397 dyn_cast<BranchInst>(InnerLoopLatch->getTerminator()); 1398 BranchInst *OuterLoopHeaderBI = 1399 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); 1400 BranchInst *InnerLoopHeaderBI = 1401 dyn_cast<BranchInst>(InnerLoopHeader->getTerminator()); 1402 1403 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor || 1404 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI || 1405 !InnerLoopHeaderBI) 1406 return false; 1407 1408 BranchInst *InnerLoopLatchPredecessorBI = 1409 dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator()); 1410 BranchInst *OuterLoopPredecessorBI = 1411 dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator()); 1412 1413 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI) 1414 return false; 1415 BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor(); 1416 if (!InnerLoopHeaderSuccessor) 1417 return false; 1418 1419 // Adjust Loop Preheader and headers 1420 updateSuccessor(OuterLoopPredecessorBI, OuterLoopPreHeader, 1421 InnerLoopPreHeader, DTUpdates); 1422 updateSuccessor(OuterLoopHeaderBI, OuterLoopLatch, LoopExit, DTUpdates); 1423 updateSuccessor(OuterLoopHeaderBI, InnerLoopPreHeader, 1424 InnerLoopHeaderSuccessor, DTUpdates); 1425 1426 // Adjust reduction PHI's now that the incoming block has changed. 1427 updateIncomingBlock(InnerLoopHeaderSuccessor, InnerLoopHeader, 1428 OuterLoopHeader); 1429 1430 updateSuccessor(InnerLoopHeaderBI, InnerLoopHeaderSuccessor, 1431 OuterLoopPreHeader, DTUpdates); 1432 1433 // -------------Adjust loop latches----------- 1434 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader) 1435 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1); 1436 else 1437 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0); 1438 1439 updateSuccessor(InnerLoopLatchPredecessorBI, InnerLoopLatch, 1440 InnerLoopLatchSuccessor, DTUpdates); 1441 1442 // Adjust PHI nodes in InnerLoopLatchSuccessor. Update all uses of PHI with 1443 // the value and remove this PHI node from inner loop. 1444 SmallVector<PHINode *, 8> LcssaVec; 1445 for (auto I = InnerLoopLatchSuccessor->begin(); isa<PHINode>(I); ++I) { 1446 PHINode *LcssaPhi = cast<PHINode>(I); 1447 LcssaVec.push_back(LcssaPhi); 1448 } 1449 for (PHINode *P : LcssaVec) { 1450 Value *Incoming = P->getIncomingValueForBlock(InnerLoopLatch); 1451 P->replaceAllUsesWith(Incoming); 1452 P->eraseFromParent(); 1453 } 1454 1455 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader) 1456 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1); 1457 else 1458 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0); 1459 1460 updateSuccessor(InnerLoopLatchBI, InnerLoopLatchSuccessor, 1461 OuterLoopLatchSuccessor, DTUpdates); 1462 updateSuccessor(OuterLoopLatchBI, OuterLoopLatchSuccessor, InnerLoopLatch, 1463 DTUpdates); 1464 1465 updateIncomingBlock(OuterLoopLatchSuccessor, OuterLoopLatch, InnerLoopLatch); 1466 1467 DT->applyUpdates(DTUpdates); 1468 restructureLoops(OuterLoop, InnerLoop, InnerLoopPreHeader, 1469 OuterLoopPreHeader); 1470 1471 return true; 1472 } 1473 1474 void LoopInterchangeTransform::adjustLoopPreheaders() { 1475 // We have interchanged the preheaders so we need to interchange the data in 1476 // the preheader as well. 1477 // This is because the content of inner preheader was previously executed 1478 // inside the outer loop. 1479 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); 1480 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1481 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 1482 BranchInst *InnerTermBI = 1483 cast<BranchInst>(InnerLoopPreHeader->getTerminator()); 1484 1485 // These instructions should now be executed inside the loop. 1486 // Move instruction into a new block after outer header. 1487 moveBBContents(InnerLoopPreHeader, OuterLoopHeader->getTerminator()); 1488 // These instructions were not executed previously in the loop so move them to 1489 // the older inner loop preheader. 1490 moveBBContents(OuterLoopPreHeader, InnerTermBI); 1491 } 1492 1493 bool LoopInterchangeTransform::adjustLoopLinks() { 1494 // Adjust all branches in the inner and outer loop. 1495 bool Changed = adjustLoopBranches(); 1496 if (Changed) 1497 adjustLoopPreheaders(); 1498 return Changed; 1499 } 1500 1501 char LoopInterchange::ID = 0; 1502 1503 INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange", 1504 "Interchanges loops for cache reuse", false, false) 1505 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 1506 INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass) 1507 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1508 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 1509 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 1510 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass) 1511 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 1512 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 1513 1514 INITIALIZE_PASS_END(LoopInterchange, "loop-interchange", 1515 "Interchanges loops for cache reuse", false, false) 1516 1517 Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); } 1518