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/SmallVector.h" 17 #include "llvm/Analysis/AliasAnalysis.h" 18 #include "llvm/Analysis/AssumptionCache.h" 19 #include "llvm/Analysis/BlockFrequencyInfo.h" 20 #include "llvm/Analysis/CodeMetrics.h" 21 #include "llvm/Analysis/DependenceAnalysis.h" 22 #include "llvm/Analysis/LoopInfo.h" 23 #include "llvm/Analysis/LoopIterator.h" 24 #include "llvm/Analysis/LoopPass.h" 25 #include "llvm/Analysis/ScalarEvolution.h" 26 #include "llvm/Analysis/ScalarEvolutionExpander.h" 27 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 28 #include "llvm/Analysis/TargetTransformInfo.h" 29 #include "llvm/Analysis/ValueTracking.h" 30 #include "llvm/IR/Dominators.h" 31 #include "llvm/IR/Function.h" 32 #include "llvm/IR/IRBuilder.h" 33 #include "llvm/IR/InstIterator.h" 34 #include "llvm/IR/IntrinsicInst.h" 35 #include "llvm/IR/Module.h" 36 #include "llvm/Pass.h" 37 #include "llvm/Support/Debug.h" 38 #include "llvm/Support/raw_ostream.h" 39 #include "llvm/Transforms/Scalar.h" 40 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 41 #include "llvm/Transforms/Utils/LoopUtils.h" 42 #include "llvm/Transforms/Utils/SSAUpdater.h" 43 using namespace llvm; 44 45 #define DEBUG_TYPE "loop-interchange" 46 47 namespace { 48 49 typedef SmallVector<Loop *, 8> LoopVector; 50 51 // TODO: Check if we can use a sparse matrix here. 52 typedef std::vector<std::vector<char>> CharMatrix; 53 54 // Maximum number of dependencies that can be handled in the dependency matrix. 55 static const unsigned MaxMemInstrCount = 100; 56 57 // Maximum loop depth supported. 58 static const unsigned MaxLoopNestDepth = 10; 59 60 struct LoopInterchange; 61 62 #ifdef DUMP_DEP_MATRICIES 63 void printDepMatrix(CharMatrix &DepMatrix) { 64 for (auto I = DepMatrix.begin(), E = DepMatrix.end(); I != E; ++I) { 65 std::vector<char> Vec = *I; 66 for (auto II = Vec.begin(), EE = Vec.end(); II != EE; ++II) 67 DEBUG(dbgs() << *II << " "); 68 DEBUG(dbgs() << "\n"); 69 } 70 } 71 #endif 72 73 static bool populateDependencyMatrix(CharMatrix &DepMatrix, unsigned Level, 74 Loop *L, DependenceInfo *DI) { 75 typedef SmallVector<Value *, 16> ValueVector; 76 ValueVector MemInstr; 77 78 // For each block. 79 for (Loop::block_iterator BB = L->block_begin(), BE = L->block_end(); 80 BB != BE; ++BB) { 81 // Scan the BB and collect legal loads and stores. 82 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; 83 ++I) { 84 if (!isa<Instruction>(I)) 85 return false; 86 if (LoadInst *Ld = dyn_cast<LoadInst>(I)) { 87 if (!Ld->isSimple()) 88 return false; 89 MemInstr.push_back(&*I); 90 } else if (StoreInst *St = dyn_cast<StoreInst>(I)) { 91 if (!St->isSimple()) 92 return false; 93 MemInstr.push_back(&*I); 94 } 95 } 96 } 97 98 DEBUG(dbgs() << "Found " << MemInstr.size() 99 << " Loads and Stores to analyze\n"); 100 101 ValueVector::iterator I, IE, J, JE; 102 103 for (I = MemInstr.begin(), IE = MemInstr.end(); I != IE; ++I) { 104 for (J = I, JE = MemInstr.end(); J != JE; ++J) { 105 std::vector<char> Dep; 106 Instruction *Src = cast<Instruction>(*I); 107 Instruction *Dst = cast<Instruction>(*J); 108 if (Src == Dst) 109 continue; 110 if (isa<LoadInst>(Src) && isa<LoadInst>(Dst)) 111 continue; 112 if (auto D = DI->depends(Src, Dst, true)) { 113 DEBUG(dbgs() << "Found Dependency between Src and Dst\n" 114 << " Src:" << *Src << "\n Dst:" << *Dst << '\n'); 115 if (D->isFlow()) { 116 // TODO: Handle Flow dependence.Check if it is sufficient to populate 117 // the Dependence Matrix with the direction reversed. 118 DEBUG(dbgs() << "Flow dependence not handled\n"); 119 return false; 120 } 121 if (D->isAnti()) { 122 DEBUG(dbgs() << "Found Anti dependence\n"); 123 unsigned Levels = D->getLevels(); 124 char Direction; 125 for (unsigned II = 1; II <= Levels; ++II) { 126 const SCEV *Distance = D->getDistance(II); 127 const SCEVConstant *SCEVConst = 128 dyn_cast_or_null<SCEVConstant>(Distance); 129 if (SCEVConst) { 130 const ConstantInt *CI = SCEVConst->getValue(); 131 if (CI->isNegative()) 132 Direction = '<'; 133 else if (CI->isZero()) 134 Direction = '='; 135 else 136 Direction = '>'; 137 Dep.push_back(Direction); 138 } else if (D->isScalar(II)) { 139 Direction = 'S'; 140 Dep.push_back(Direction); 141 } else { 142 unsigned Dir = D->getDirection(II); 143 if (Dir == Dependence::DVEntry::LT || 144 Dir == Dependence::DVEntry::LE) 145 Direction = '<'; 146 else if (Dir == Dependence::DVEntry::GT || 147 Dir == Dependence::DVEntry::GE) 148 Direction = '>'; 149 else if (Dir == Dependence::DVEntry::EQ) 150 Direction = '='; 151 else 152 Direction = '*'; 153 Dep.push_back(Direction); 154 } 155 } 156 while (Dep.size() != Level) { 157 Dep.push_back('I'); 158 } 159 160 DepMatrix.push_back(Dep); 161 if (DepMatrix.size() > MaxMemInstrCount) { 162 DEBUG(dbgs() << "Cannot handle more than " << MaxMemInstrCount 163 << " dependencies inside loop\n"); 164 return false; 165 } 166 } 167 } 168 } 169 } 170 171 // We don't have a DepMatrix to check legality return false. 172 if (DepMatrix.size() == 0) 173 return false; 174 return true; 175 } 176 177 // A loop is moved from index 'from' to an index 'to'. Update the Dependence 178 // matrix by exchanging the two columns. 179 static void interChangeDependencies(CharMatrix &DepMatrix, unsigned FromIndx, 180 unsigned ToIndx) { 181 unsigned numRows = DepMatrix.size(); 182 for (unsigned i = 0; i < numRows; ++i) { 183 char TmpVal = DepMatrix[i][ToIndx]; 184 DepMatrix[i][ToIndx] = DepMatrix[i][FromIndx]; 185 DepMatrix[i][FromIndx] = TmpVal; 186 } 187 } 188 189 // Checks if outermost non '=','S'or'I' dependence in the dependence matrix is 190 // '>' 191 static bool isOuterMostDepPositive(CharMatrix &DepMatrix, unsigned Row, 192 unsigned Column) { 193 for (unsigned i = 0; i <= Column; ++i) { 194 if (DepMatrix[Row][i] == '<') 195 return false; 196 if (DepMatrix[Row][i] == '>') 197 return true; 198 } 199 // All dependencies were '=','S' or 'I' 200 return false; 201 } 202 203 // Checks if no dependence exist in the dependency matrix in Row before Column. 204 static bool containsNoDependence(CharMatrix &DepMatrix, unsigned Row, 205 unsigned Column) { 206 for (unsigned i = 0; i < Column; ++i) { 207 if (DepMatrix[Row][i] != '=' || DepMatrix[Row][i] != 'S' || 208 DepMatrix[Row][i] != 'I') 209 return false; 210 } 211 return true; 212 } 213 214 static bool validDepInterchange(CharMatrix &DepMatrix, unsigned Row, 215 unsigned OuterLoopId, char InnerDep, 216 char OuterDep) { 217 218 if (isOuterMostDepPositive(DepMatrix, Row, OuterLoopId)) 219 return false; 220 221 if (InnerDep == OuterDep) 222 return true; 223 224 // It is legal to interchange if and only if after interchange no row has a 225 // '>' direction as the leftmost non-'='. 226 227 if (InnerDep == '=' || InnerDep == 'S' || InnerDep == 'I') 228 return true; 229 230 if (InnerDep == '<') 231 return true; 232 233 if (InnerDep == '>') { 234 // If OuterLoopId represents outermost loop then interchanging will make the 235 // 1st dependency as '>' 236 if (OuterLoopId == 0) 237 return false; 238 239 // If all dependencies before OuterloopId are '=','S'or 'I'. Then 240 // interchanging will result in this row having an outermost non '=' 241 // dependency of '>' 242 if (!containsNoDependence(DepMatrix, Row, OuterLoopId)) 243 return true; 244 } 245 246 return false; 247 } 248 249 // Checks if it is legal to interchange 2 loops. 250 // [Theorem] A permutation of the loops in a perfect nest is legal if and only 251 // if the direction matrix, after the same permutation is applied to its 252 // columns, has no ">" direction as the leftmost non-"=" direction in any row. 253 static bool isLegalToInterChangeLoops(CharMatrix &DepMatrix, 254 unsigned InnerLoopId, 255 unsigned OuterLoopId) { 256 257 unsigned NumRows = DepMatrix.size(); 258 // For each row check if it is valid to interchange. 259 for (unsigned Row = 0; Row < NumRows; ++Row) { 260 char InnerDep = DepMatrix[Row][InnerLoopId]; 261 char OuterDep = DepMatrix[Row][OuterLoopId]; 262 if (InnerDep == '*' || OuterDep == '*') 263 return false; 264 if (!validDepInterchange(DepMatrix, Row, OuterLoopId, InnerDep, OuterDep)) 265 return false; 266 } 267 return true; 268 } 269 270 static void populateWorklist(Loop &L, SmallVector<LoopVector, 8> &V) { 271 272 DEBUG(dbgs() << "Calling populateWorklist on Func: " 273 << L.getHeader()->getParent()->getName() << " Loop: %" 274 << L.getHeader()->getName() << '\n'); 275 LoopVector LoopList; 276 Loop *CurrentLoop = &L; 277 const std::vector<Loop *> *Vec = &CurrentLoop->getSubLoops(); 278 while (!Vec->empty()) { 279 // The current loop has multiple subloops in it hence it is not tightly 280 // nested. 281 // Discard all loops above it added into Worklist. 282 if (Vec->size() != 1) { 283 LoopList.clear(); 284 return; 285 } 286 LoopList.push_back(CurrentLoop); 287 CurrentLoop = Vec->front(); 288 Vec = &CurrentLoop->getSubLoops(); 289 } 290 LoopList.push_back(CurrentLoop); 291 V.push_back(std::move(LoopList)); 292 } 293 294 static PHINode *getInductionVariable(Loop *L, ScalarEvolution *SE) { 295 PHINode *InnerIndexVar = L->getCanonicalInductionVariable(); 296 if (InnerIndexVar) 297 return InnerIndexVar; 298 if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr) 299 return nullptr; 300 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 301 PHINode *PhiVar = cast<PHINode>(I); 302 Type *PhiTy = PhiVar->getType(); 303 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() && 304 !PhiTy->isPointerTy()) 305 return nullptr; 306 const SCEVAddRecExpr *AddRec = 307 dyn_cast<SCEVAddRecExpr>(SE->getSCEV(PhiVar)); 308 if (!AddRec || !AddRec->isAffine()) 309 continue; 310 const SCEV *Step = AddRec->getStepRecurrence(*SE); 311 const SCEVConstant *C = dyn_cast<SCEVConstant>(Step); 312 if (!C) 313 continue; 314 // Found the induction variable. 315 // FIXME: Handle loops with more than one induction variable. Note that, 316 // currently, legality makes sure we have only one induction variable. 317 return PhiVar; 318 } 319 return nullptr; 320 } 321 322 /// LoopInterchangeLegality checks if it is legal to interchange the loop. 323 class LoopInterchangeLegality { 324 public: 325 LoopInterchangeLegality(Loop *Outer, Loop *Inner, ScalarEvolution *SE, 326 LoopInfo *LI, DominatorTree *DT, bool PreserveLCSSA) 327 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), 328 PreserveLCSSA(PreserveLCSSA), InnerLoopHasReduction(false) {} 329 330 /// Check if the loops can be interchanged. 331 bool canInterchangeLoops(unsigned InnerLoopId, unsigned OuterLoopId, 332 CharMatrix &DepMatrix); 333 /// Check if the loop structure is understood. We do not handle triangular 334 /// loops for now. 335 bool isLoopStructureUnderstood(PHINode *InnerInductionVar); 336 337 bool currentLimitations(); 338 339 bool hasInnerLoopReduction() { return InnerLoopHasReduction; } 340 341 private: 342 bool tightlyNested(Loop *Outer, Loop *Inner); 343 bool containsUnsafeInstructionsInHeader(BasicBlock *BB); 344 bool areAllUsesReductions(Instruction *Ins, Loop *L); 345 bool containsUnsafeInstructionsInLatch(BasicBlock *BB); 346 bool findInductionAndReductions(Loop *L, 347 SmallVector<PHINode *, 8> &Inductions, 348 SmallVector<PHINode *, 8> &Reductions); 349 Loop *OuterLoop; 350 Loop *InnerLoop; 351 352 ScalarEvolution *SE; 353 LoopInfo *LI; 354 DominatorTree *DT; 355 bool PreserveLCSSA; 356 357 bool InnerLoopHasReduction; 358 }; 359 360 /// LoopInterchangeProfitability checks if it is profitable to interchange the 361 /// loop. 362 class LoopInterchangeProfitability { 363 public: 364 LoopInterchangeProfitability(Loop *Outer, Loop *Inner, ScalarEvolution *SE) 365 : OuterLoop(Outer), InnerLoop(Inner), SE(SE) {} 366 367 /// Check if the loop interchange is profitable. 368 bool isProfitable(unsigned InnerLoopId, unsigned OuterLoopId, 369 CharMatrix &DepMatrix); 370 371 private: 372 int getInstrOrderCost(); 373 374 Loop *OuterLoop; 375 Loop *InnerLoop; 376 377 /// Scev analysis. 378 ScalarEvolution *SE; 379 }; 380 381 /// LoopInterchangeTransform interchanges the loop. 382 class LoopInterchangeTransform { 383 public: 384 LoopInterchangeTransform(Loop *Outer, Loop *Inner, ScalarEvolution *SE, 385 LoopInfo *LI, DominatorTree *DT, 386 BasicBlock *LoopNestExit, 387 bool InnerLoopContainsReductions) 388 : OuterLoop(Outer), InnerLoop(Inner), SE(SE), LI(LI), DT(DT), 389 LoopExit(LoopNestExit), 390 InnerLoopHasReduction(InnerLoopContainsReductions) {} 391 392 /// Interchange OuterLoop and InnerLoop. 393 bool transform(); 394 void restructureLoops(Loop *InnerLoop, Loop *OuterLoop); 395 void removeChildLoop(Loop *OuterLoop, Loop *InnerLoop); 396 397 private: 398 void splitInnerLoopLatch(Instruction *); 399 void splitInnerLoopHeader(); 400 bool adjustLoopLinks(); 401 void adjustLoopPreheaders(); 402 bool adjustLoopBranches(); 403 void updateIncomingBlock(BasicBlock *CurrBlock, BasicBlock *OldPred, 404 BasicBlock *NewPred); 405 406 Loop *OuterLoop; 407 Loop *InnerLoop; 408 409 /// Scev analysis. 410 ScalarEvolution *SE; 411 LoopInfo *LI; 412 DominatorTree *DT; 413 BasicBlock *LoopExit; 414 bool InnerLoopHasReduction; 415 }; 416 417 // Main LoopInterchange Pass. 418 struct LoopInterchange : public FunctionPass { 419 static char ID; 420 ScalarEvolution *SE; 421 LoopInfo *LI; 422 DependenceInfo *DI; 423 DominatorTree *DT; 424 bool PreserveLCSSA; 425 LoopInterchange() 426 : FunctionPass(ID), SE(nullptr), LI(nullptr), DI(nullptr), DT(nullptr) { 427 initializeLoopInterchangePass(*PassRegistry::getPassRegistry()); 428 } 429 430 void getAnalysisUsage(AnalysisUsage &AU) const override { 431 AU.addRequired<ScalarEvolutionWrapperPass>(); 432 AU.addRequired<AAResultsWrapperPass>(); 433 AU.addRequired<DominatorTreeWrapperPass>(); 434 AU.addRequired<LoopInfoWrapperPass>(); 435 AU.addRequired<DependenceAnalysisWrapperPass>(); 436 AU.addRequiredID(LoopSimplifyID); 437 AU.addRequiredID(LCSSAID); 438 } 439 440 bool runOnFunction(Function &F) override { 441 if (skipFunction(F)) 442 return false; 443 444 SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 445 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 446 DI = &getAnalysis<DependenceAnalysisWrapperPass>().getDI(); 447 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 448 DT = DTWP ? &DTWP->getDomTree() : nullptr; 449 PreserveLCSSA = mustPreserveAnalysisID(LCSSAID); 450 451 // Build up a worklist of loop pairs to analyze. 452 SmallVector<LoopVector, 8> Worklist; 453 454 for (Loop *L : *LI) 455 populateWorklist(*L, Worklist); 456 457 DEBUG(dbgs() << "Worklist size = " << Worklist.size() << "\n"); 458 bool Changed = true; 459 while (!Worklist.empty()) { 460 LoopVector LoopList = Worklist.pop_back_val(); 461 Changed = processLoopList(LoopList, F); 462 } 463 return Changed; 464 } 465 466 bool isComputableLoopNest(LoopVector LoopList) { 467 for (Loop *L : LoopList) { 468 const SCEV *ExitCountOuter = SE->getBackedgeTakenCount(L); 469 if (ExitCountOuter == SE->getCouldNotCompute()) { 470 DEBUG(dbgs() << "Couldn't compute Backedge count\n"); 471 return false; 472 } 473 if (L->getNumBackEdges() != 1) { 474 DEBUG(dbgs() << "NumBackEdges is not equal to 1\n"); 475 return false; 476 } 477 if (!L->getExitingBlock()) { 478 DEBUG(dbgs() << "Loop Doesn't have unique exit block\n"); 479 return false; 480 } 481 } 482 return true; 483 } 484 485 unsigned selectLoopForInterchange(const LoopVector &LoopList) { 486 // TODO: Add a better heuristic to select the loop to be interchanged based 487 // on the dependence matrix. Currently we select the innermost loop. 488 return LoopList.size() - 1; 489 } 490 491 bool processLoopList(LoopVector LoopList, Function &F) { 492 493 bool Changed = false; 494 unsigned LoopNestDepth = LoopList.size(); 495 if (LoopNestDepth < 2) { 496 DEBUG(dbgs() << "Loop doesn't contain minimum nesting level.\n"); 497 return false; 498 } 499 if (LoopNestDepth > MaxLoopNestDepth) { 500 DEBUG(dbgs() << "Cannot handle loops of depth greater than " 501 << MaxLoopNestDepth << "\n"); 502 return false; 503 } 504 if (!isComputableLoopNest(LoopList)) { 505 DEBUG(dbgs() << "Not valid loop candidate for interchange\n"); 506 return false; 507 } 508 509 DEBUG(dbgs() << "Processing LoopList of size = " << LoopNestDepth << "\n"); 510 511 CharMatrix DependencyMatrix; 512 Loop *OuterMostLoop = *(LoopList.begin()); 513 if (!populateDependencyMatrix(DependencyMatrix, LoopNestDepth, 514 OuterMostLoop, DI)) { 515 DEBUG(dbgs() << "Populating Dependency matrix failed\n"); 516 return false; 517 } 518 #ifdef DUMP_DEP_MATRICIES 519 DEBUG(dbgs() << "Dependence before inter change \n"); 520 printDepMatrix(DependencyMatrix); 521 #endif 522 523 BasicBlock *OuterMostLoopLatch = OuterMostLoop->getLoopLatch(); 524 BranchInst *OuterMostLoopLatchBI = 525 dyn_cast<BranchInst>(OuterMostLoopLatch->getTerminator()); 526 if (!OuterMostLoopLatchBI) 527 return false; 528 529 // Since we currently do not handle LCSSA PHI's any failure in loop 530 // condition will now branch to LoopNestExit. 531 // TODO: This should be removed once we handle LCSSA PHI nodes. 532 533 // Get the Outermost loop exit. 534 BasicBlock *LoopNestExit; 535 if (OuterMostLoopLatchBI->getSuccessor(0) == OuterMostLoop->getHeader()) 536 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(1); 537 else 538 LoopNestExit = OuterMostLoopLatchBI->getSuccessor(0); 539 540 if (isa<PHINode>(LoopNestExit->begin())) { 541 DEBUG(dbgs() << "PHI Nodes in loop nest exit is not handled for now " 542 "since on failure all loops branch to loop nest exit.\n"); 543 return false; 544 } 545 546 unsigned SelecLoopId = selectLoopForInterchange(LoopList); 547 // Move the selected loop outwards to the best possible position. 548 for (unsigned i = SelecLoopId; i > 0; i--) { 549 bool Interchanged = 550 processLoop(LoopList, i, i - 1, LoopNestExit, DependencyMatrix); 551 if (!Interchanged) 552 return Changed; 553 // Loops interchanged reflect the same in LoopList 554 std::swap(LoopList[i - 1], LoopList[i]); 555 556 // Update the DependencyMatrix 557 interChangeDependencies(DependencyMatrix, i, i - 1); 558 DT->recalculate(F); 559 #ifdef DUMP_DEP_MATRICIES 560 DEBUG(dbgs() << "Dependence after inter change \n"); 561 printDepMatrix(DependencyMatrix); 562 #endif 563 Changed |= Interchanged; 564 } 565 return Changed; 566 } 567 568 bool processLoop(LoopVector LoopList, unsigned InnerLoopId, 569 unsigned OuterLoopId, BasicBlock *LoopNestExit, 570 std::vector<std::vector<char>> &DependencyMatrix) { 571 572 DEBUG(dbgs() << "Processing Inner Loop Id = " << InnerLoopId 573 << " and OuterLoopId = " << OuterLoopId << "\n"); 574 Loop *InnerLoop = LoopList[InnerLoopId]; 575 Loop *OuterLoop = LoopList[OuterLoopId]; 576 577 LoopInterchangeLegality LIL(OuterLoop, InnerLoop, SE, LI, DT, 578 PreserveLCSSA); 579 if (!LIL.canInterchangeLoops(InnerLoopId, OuterLoopId, DependencyMatrix)) { 580 DEBUG(dbgs() << "Not interchanging Loops. Cannot prove legality\n"); 581 return false; 582 } 583 DEBUG(dbgs() << "Loops are legal to interchange\n"); 584 LoopInterchangeProfitability LIP(OuterLoop, InnerLoop, SE); 585 if (!LIP.isProfitable(InnerLoopId, OuterLoopId, DependencyMatrix)) { 586 DEBUG(dbgs() << "Interchanging Loops not profitable\n"); 587 return false; 588 } 589 590 LoopInterchangeTransform LIT(OuterLoop, InnerLoop, SE, LI, DT, 591 LoopNestExit, LIL.hasInnerLoopReduction()); 592 LIT.transform(); 593 DEBUG(dbgs() << "Loops interchanged\n"); 594 return true; 595 } 596 }; 597 598 } // end of namespace 599 bool LoopInterchangeLegality::areAllUsesReductions(Instruction *Ins, Loop *L) { 600 return none_of(Ins->users(), [=](User *U) -> bool { 601 auto *UserIns = dyn_cast<PHINode>(U); 602 RecurrenceDescriptor RD; 603 return !UserIns || !RecurrenceDescriptor::isReductionPHI(UserIns, L, RD); 604 }); 605 } 606 607 bool LoopInterchangeLegality::containsUnsafeInstructionsInHeader( 608 BasicBlock *BB) { 609 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) { 610 // Load corresponding to reduction PHI's are safe while concluding if 611 // tightly nested. 612 if (LoadInst *L = dyn_cast<LoadInst>(I)) { 613 if (!areAllUsesReductions(L, InnerLoop)) 614 return true; 615 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory()) 616 return true; 617 } 618 return false; 619 } 620 621 bool LoopInterchangeLegality::containsUnsafeInstructionsInLatch( 622 BasicBlock *BB) { 623 for (auto I = BB->begin(), E = BB->end(); I != E; ++I) { 624 // Stores corresponding to reductions are safe while concluding if tightly 625 // nested. 626 if (StoreInst *L = dyn_cast<StoreInst>(I)) { 627 PHINode *PHI = dyn_cast<PHINode>(L->getOperand(0)); 628 if (!PHI) 629 return true; 630 } else if (I->mayHaveSideEffects() || I->mayReadFromMemory()) 631 return true; 632 } 633 return false; 634 } 635 636 bool LoopInterchangeLegality::tightlyNested(Loop *OuterLoop, Loop *InnerLoop) { 637 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 638 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 639 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); 640 641 DEBUG(dbgs() << "Checking if Loops are Tightly Nested\n"); 642 643 // A perfectly nested loop will not have any branch in between the outer and 644 // inner block i.e. outer header will branch to either inner preheader and 645 // outerloop latch. 646 BranchInst *outerLoopHeaderBI = 647 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); 648 if (!outerLoopHeaderBI) 649 return false; 650 unsigned num = outerLoopHeaderBI->getNumSuccessors(); 651 for (unsigned i = 0; i < num; i++) { 652 if (outerLoopHeaderBI->getSuccessor(i) != InnerLoopPreHeader && 653 outerLoopHeaderBI->getSuccessor(i) != OuterLoopLatch) 654 return false; 655 } 656 657 DEBUG(dbgs() << "Checking instructions in Loop header and Loop latch \n"); 658 // We do not have any basic block in between now make sure the outer header 659 // and outer loop latch doesn't contain any unsafe instructions. 660 if (containsUnsafeInstructionsInHeader(OuterLoopHeader) || 661 containsUnsafeInstructionsInLatch(OuterLoopLatch)) 662 return false; 663 664 DEBUG(dbgs() << "Loops are perfectly nested \n"); 665 // We have a perfect loop nest. 666 return true; 667 } 668 669 670 bool LoopInterchangeLegality::isLoopStructureUnderstood( 671 PHINode *InnerInduction) { 672 673 unsigned Num = InnerInduction->getNumOperands(); 674 BasicBlock *InnerLoopPreheader = InnerLoop->getLoopPreheader(); 675 for (unsigned i = 0; i < Num; ++i) { 676 Value *Val = InnerInduction->getOperand(i); 677 if (isa<Constant>(Val)) 678 continue; 679 Instruction *I = dyn_cast<Instruction>(Val); 680 if (!I) 681 return false; 682 // TODO: Handle triangular loops. 683 // e.g. for(int i=0;i<N;i++) 684 // for(int j=i;j<N;j++) 685 unsigned IncomBlockIndx = PHINode::getIncomingValueNumForOperand(i); 686 if (InnerInduction->getIncomingBlock(IncomBlockIndx) == 687 InnerLoopPreheader && 688 !OuterLoop->isLoopInvariant(I)) { 689 return false; 690 } 691 } 692 return true; 693 } 694 695 bool LoopInterchangeLegality::findInductionAndReductions( 696 Loop *L, SmallVector<PHINode *, 8> &Inductions, 697 SmallVector<PHINode *, 8> &Reductions) { 698 if (!L->getLoopLatch() || !L->getLoopPredecessor()) 699 return false; 700 for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) { 701 RecurrenceDescriptor RD; 702 InductionDescriptor ID; 703 PHINode *PHI = cast<PHINode>(I); 704 if (InductionDescriptor::isInductionPHI(PHI, L, SE, ID)) 705 Inductions.push_back(PHI); 706 else if (RecurrenceDescriptor::isReductionPHI(PHI, L, RD)) 707 Reductions.push_back(PHI); 708 else { 709 DEBUG( 710 dbgs() << "Failed to recognize PHI as an induction or reduction.\n"); 711 return false; 712 } 713 } 714 return true; 715 } 716 717 static bool containsSafePHI(BasicBlock *Block, bool isOuterLoopExitBlock) { 718 for (auto I = Block->begin(); isa<PHINode>(I); ++I) { 719 PHINode *PHI = cast<PHINode>(I); 720 // Reduction lcssa phi will have only 1 incoming block that from loop latch. 721 if (PHI->getNumIncomingValues() > 1) 722 return false; 723 Instruction *Ins = dyn_cast<Instruction>(PHI->getIncomingValue(0)); 724 if (!Ins) 725 return false; 726 // Incoming value for lcssa phi's in outer loop exit can only be inner loop 727 // exits lcssa phi else it would not be tightly nested. 728 if (!isa<PHINode>(Ins) && isOuterLoopExitBlock) 729 return false; 730 } 731 return true; 732 } 733 734 static BasicBlock *getLoopLatchExitBlock(BasicBlock *LatchBlock, 735 BasicBlock *LoopHeader) { 736 if (BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator())) { 737 unsigned Num = BI->getNumSuccessors(); 738 assert(Num == 2); 739 for (unsigned i = 0; i < Num; ++i) { 740 if (BI->getSuccessor(i) == LoopHeader) 741 continue; 742 return BI->getSuccessor(i); 743 } 744 } 745 return nullptr; 746 } 747 748 // This function indicates the current limitations in the transform as a result 749 // of which we do not proceed. 750 bool LoopInterchangeLegality::currentLimitations() { 751 752 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 753 BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); 754 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 755 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); 756 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 757 758 PHINode *InnerInductionVar; 759 SmallVector<PHINode *, 8> Inductions; 760 SmallVector<PHINode *, 8> Reductions; 761 if (!findInductionAndReductions(InnerLoop, Inductions, Reductions)) 762 return true; 763 764 // TODO: Currently we handle only loops with 1 induction variable. 765 if (Inductions.size() != 1) { 766 DEBUG(dbgs() << "We currently only support loops with 1 induction variable." 767 << "Failed to interchange due to current limitation\n"); 768 return true; 769 } 770 if (Reductions.size() > 0) 771 InnerLoopHasReduction = true; 772 773 InnerInductionVar = Inductions.pop_back_val(); 774 Reductions.clear(); 775 if (!findInductionAndReductions(OuterLoop, Inductions, Reductions)) 776 return true; 777 778 // Outer loop cannot have reduction because then loops will not be tightly 779 // nested. 780 if (!Reductions.empty()) 781 return true; 782 // TODO: Currently we handle only loops with 1 induction variable. 783 if (Inductions.size() != 1) 784 return true; 785 786 // TODO: Triangular loops are not handled for now. 787 if (!isLoopStructureUnderstood(InnerInductionVar)) { 788 DEBUG(dbgs() << "Loop structure not understood by pass\n"); 789 return true; 790 } 791 792 // TODO: We only handle LCSSA PHI's corresponding to reduction for now. 793 BasicBlock *LoopExitBlock = 794 getLoopLatchExitBlock(OuterLoopLatch, OuterLoopHeader); 795 if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, true)) 796 return true; 797 798 LoopExitBlock = getLoopLatchExitBlock(InnerLoopLatch, InnerLoopHeader); 799 if (!LoopExitBlock || !containsSafePHI(LoopExitBlock, false)) 800 return true; 801 802 // TODO: Current limitation: Since we split the inner loop latch at the point 803 // were induction variable is incremented (induction.next); We cannot have 804 // more than 1 user of induction.next since it would result in broken code 805 // after split. 806 // e.g. 807 // for(i=0;i<N;i++) { 808 // for(j = 0;j<M;j++) { 809 // A[j+1][i+2] = A[j][i]+k; 810 // } 811 // } 812 Instruction *InnerIndexVarInc = nullptr; 813 if (InnerInductionVar->getIncomingBlock(0) == InnerLoopPreHeader) 814 InnerIndexVarInc = 815 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(1)); 816 else 817 InnerIndexVarInc = 818 dyn_cast<Instruction>(InnerInductionVar->getIncomingValue(0)); 819 820 if (!InnerIndexVarInc) 821 return true; 822 823 // Since we split the inner loop latch on this induction variable. Make sure 824 // we do not have any instruction between the induction variable and branch 825 // instruction. 826 827 bool FoundInduction = false; 828 for (const Instruction &I : reverse(*InnerLoopLatch)) { 829 if (isa<BranchInst>(I) || isa<CmpInst>(I) || isa<TruncInst>(I)) 830 continue; 831 // We found an instruction. If this is not induction variable then it is not 832 // safe to split this loop latch. 833 if (!I.isIdenticalTo(InnerIndexVarInc)) 834 return true; 835 836 FoundInduction = true; 837 break; 838 } 839 // The loop latch ended and we didn't find the induction variable return as 840 // current limitation. 841 if (!FoundInduction) 842 return true; 843 844 return false; 845 } 846 847 bool LoopInterchangeLegality::canInterchangeLoops(unsigned InnerLoopId, 848 unsigned OuterLoopId, 849 CharMatrix &DepMatrix) { 850 851 if (!isLegalToInterChangeLoops(DepMatrix, InnerLoopId, OuterLoopId)) { 852 DEBUG(dbgs() << "Failed interchange InnerLoopId = " << InnerLoopId 853 << "and OuterLoopId = " << OuterLoopId 854 << "due to dependence\n"); 855 return false; 856 } 857 858 // Create unique Preheaders if we already do not have one. 859 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); 860 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 861 862 // Create a unique outer preheader - 863 // 1) If OuterLoop preheader is not present. 864 // 2) If OuterLoop Preheader is same as OuterLoop Header 865 // 3) If OuterLoop Preheader is same as Header of the previous loop. 866 // 4) If OuterLoop Preheader is Entry node. 867 if (!OuterLoopPreHeader || OuterLoopPreHeader == OuterLoop->getHeader() || 868 isa<PHINode>(OuterLoopPreHeader->begin()) || 869 !OuterLoopPreHeader->getUniquePredecessor()) { 870 OuterLoopPreHeader = 871 InsertPreheaderForLoop(OuterLoop, DT, LI, PreserveLCSSA); 872 } 873 874 if (!InnerLoopPreHeader || InnerLoopPreHeader == InnerLoop->getHeader() || 875 InnerLoopPreHeader == OuterLoop->getHeader()) { 876 InnerLoopPreHeader = 877 InsertPreheaderForLoop(InnerLoop, DT, LI, PreserveLCSSA); 878 } 879 880 // TODO: The loops could not be interchanged due to current limitations in the 881 // transform module. 882 if (currentLimitations()) { 883 DEBUG(dbgs() << "Not legal because of current transform limitation\n"); 884 return false; 885 } 886 887 // Check if the loops are tightly nested. 888 if (!tightlyNested(OuterLoop, InnerLoop)) { 889 DEBUG(dbgs() << "Loops not tightly nested\n"); 890 return false; 891 } 892 893 return true; 894 } 895 896 int LoopInterchangeProfitability::getInstrOrderCost() { 897 unsigned GoodOrder, BadOrder; 898 BadOrder = GoodOrder = 0; 899 for (auto BI = InnerLoop->block_begin(), BE = InnerLoop->block_end(); 900 BI != BE; ++BI) { 901 for (Instruction &Ins : **BI) { 902 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&Ins)) { 903 unsigned NumOp = GEP->getNumOperands(); 904 bool FoundInnerInduction = false; 905 bool FoundOuterInduction = false; 906 for (unsigned i = 0; i < NumOp; ++i) { 907 const SCEV *OperandVal = SE->getSCEV(GEP->getOperand(i)); 908 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OperandVal); 909 if (!AR) 910 continue; 911 912 // If we find the inner induction after an outer induction e.g. 913 // for(int i=0;i<N;i++) 914 // for(int j=0;j<N;j++) 915 // A[i][j] = A[i-1][j-1]+k; 916 // then it is a good order. 917 if (AR->getLoop() == InnerLoop) { 918 // We found an InnerLoop induction after OuterLoop induction. It is 919 // a good order. 920 FoundInnerInduction = true; 921 if (FoundOuterInduction) { 922 GoodOrder++; 923 break; 924 } 925 } 926 // If we find the outer induction after an inner induction e.g. 927 // for(int i=0;i<N;i++) 928 // for(int j=0;j<N;j++) 929 // A[j][i] = A[j-1][i-1]+k; 930 // then it is a bad order. 931 if (AR->getLoop() == OuterLoop) { 932 // We found an OuterLoop induction after InnerLoop induction. It is 933 // a bad order. 934 FoundOuterInduction = true; 935 if (FoundInnerInduction) { 936 BadOrder++; 937 break; 938 } 939 } 940 } 941 } 942 } 943 } 944 return GoodOrder - BadOrder; 945 } 946 947 static bool isProfitabileForVectorization(unsigned InnerLoopId, 948 unsigned OuterLoopId, 949 CharMatrix &DepMatrix) { 950 // TODO: Improve this heuristic to catch more cases. 951 // If the inner loop is loop independent or doesn't carry any dependency it is 952 // profitable to move this to outer position. 953 unsigned Row = DepMatrix.size(); 954 for (unsigned i = 0; i < Row; ++i) { 955 if (DepMatrix[i][InnerLoopId] != 'S' && DepMatrix[i][InnerLoopId] != 'I') 956 return false; 957 // TODO: We need to improve this heuristic. 958 if (DepMatrix[i][OuterLoopId] != '=') 959 return false; 960 } 961 // If outer loop has dependence and inner loop is loop independent then it is 962 // profitable to interchange to enable parallelism. 963 return true; 964 } 965 966 bool LoopInterchangeProfitability::isProfitable(unsigned InnerLoopId, 967 unsigned OuterLoopId, 968 CharMatrix &DepMatrix) { 969 970 // TODO: Add better profitability checks. 971 // e.g 972 // 1) Construct dependency matrix and move the one with no loop carried dep 973 // inside to enable vectorization. 974 975 // This is rough cost estimation algorithm. It counts the good and bad order 976 // of induction variables in the instruction and allows reordering if number 977 // of bad orders is more than good. 978 int Cost = 0; 979 Cost += getInstrOrderCost(); 980 DEBUG(dbgs() << "Cost = " << Cost << "\n"); 981 if (Cost < 0) 982 return true; 983 984 // It is not profitable as per current cache profitability model. But check if 985 // we can move this loop outside to improve parallelism. 986 bool ImprovesPar = 987 isProfitabileForVectorization(InnerLoopId, OuterLoopId, DepMatrix); 988 return ImprovesPar; 989 } 990 991 void LoopInterchangeTransform::removeChildLoop(Loop *OuterLoop, 992 Loop *InnerLoop) { 993 for (Loop::iterator I = OuterLoop->begin(), E = OuterLoop->end(); I != E; 994 ++I) { 995 if (*I == InnerLoop) { 996 OuterLoop->removeChildLoop(I); 997 return; 998 } 999 } 1000 llvm_unreachable("Couldn't find loop"); 1001 } 1002 1003 void LoopInterchangeTransform::restructureLoops(Loop *InnerLoop, 1004 Loop *OuterLoop) { 1005 Loop *OuterLoopParent = OuterLoop->getParentLoop(); 1006 if (OuterLoopParent) { 1007 // Remove the loop from its parent loop. 1008 removeChildLoop(OuterLoopParent, OuterLoop); 1009 removeChildLoop(OuterLoop, InnerLoop); 1010 OuterLoopParent->addChildLoop(InnerLoop); 1011 } else { 1012 removeChildLoop(OuterLoop, InnerLoop); 1013 LI->changeTopLevelLoop(OuterLoop, InnerLoop); 1014 } 1015 1016 while (!InnerLoop->empty()) 1017 OuterLoop->addChildLoop(InnerLoop->removeChildLoop(InnerLoop->begin())); 1018 1019 InnerLoop->addChildLoop(OuterLoop); 1020 } 1021 1022 bool LoopInterchangeTransform::transform() { 1023 1024 DEBUG(dbgs() << "transform\n"); 1025 bool Transformed = false; 1026 Instruction *InnerIndexVar; 1027 1028 if (InnerLoop->getSubLoops().size() == 0) { 1029 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1030 DEBUG(dbgs() << "Calling Split Inner Loop\n"); 1031 PHINode *InductionPHI = getInductionVariable(InnerLoop, SE); 1032 if (!InductionPHI) { 1033 DEBUG(dbgs() << "Failed to find the point to split loop latch \n"); 1034 return false; 1035 } 1036 1037 if (InductionPHI->getIncomingBlock(0) == InnerLoopPreHeader) 1038 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(1)); 1039 else 1040 InnerIndexVar = dyn_cast<Instruction>(InductionPHI->getIncomingValue(0)); 1041 1042 // 1043 // Split at the place were the induction variable is 1044 // incremented/decremented. 1045 // TODO: This splitting logic may not work always. Fix this. 1046 splitInnerLoopLatch(InnerIndexVar); 1047 DEBUG(dbgs() << "splitInnerLoopLatch Done\n"); 1048 1049 // Splits the inner loops phi nodes out into a separate basic block. 1050 splitInnerLoopHeader(); 1051 DEBUG(dbgs() << "splitInnerLoopHeader Done\n"); 1052 } 1053 1054 Transformed |= adjustLoopLinks(); 1055 if (!Transformed) { 1056 DEBUG(dbgs() << "adjustLoopLinks Failed\n"); 1057 return false; 1058 } 1059 1060 restructureLoops(InnerLoop, OuterLoop); 1061 return true; 1062 } 1063 1064 void LoopInterchangeTransform::splitInnerLoopLatch(Instruction *Inc) { 1065 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 1066 BasicBlock *InnerLoopLatchPred = InnerLoopLatch; 1067 InnerLoopLatch = SplitBlock(InnerLoopLatchPred, Inc, DT, LI); 1068 } 1069 1070 void LoopInterchangeTransform::splitInnerLoopHeader() { 1071 1072 // Split the inner loop header out. Here make sure that the reduction PHI's 1073 // stay in the innerloop body. 1074 BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); 1075 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1076 if (InnerLoopHasReduction) { 1077 // FIXME: Check if the induction PHI will always be the first PHI. 1078 BasicBlock *New = InnerLoopHeader->splitBasicBlock( 1079 ++(InnerLoopHeader->begin()), InnerLoopHeader->getName() + ".split"); 1080 if (LI) 1081 if (Loop *L = LI->getLoopFor(InnerLoopHeader)) 1082 L->addBasicBlockToLoop(New, *LI); 1083 1084 // Adjust Reduction PHI's in the block. 1085 SmallVector<PHINode *, 8> PHIVec; 1086 for (auto I = New->begin(); isa<PHINode>(I); ++I) { 1087 PHINode *PHI = dyn_cast<PHINode>(I); 1088 Value *V = PHI->getIncomingValueForBlock(InnerLoopPreHeader); 1089 PHI->replaceAllUsesWith(V); 1090 PHIVec.push_back((PHI)); 1091 } 1092 for (PHINode *P : PHIVec) { 1093 P->eraseFromParent(); 1094 } 1095 } else { 1096 SplitBlock(InnerLoopHeader, InnerLoopHeader->getFirstNonPHI(), DT, LI); 1097 } 1098 1099 DEBUG(dbgs() << "Output of splitInnerLoopHeader InnerLoopHeaderSucc & " 1100 "InnerLoopHeader \n"); 1101 } 1102 1103 /// \brief Move all instructions except the terminator from FromBB right before 1104 /// InsertBefore 1105 static void moveBBContents(BasicBlock *FromBB, Instruction *InsertBefore) { 1106 auto &ToList = InsertBefore->getParent()->getInstList(); 1107 auto &FromList = FromBB->getInstList(); 1108 1109 ToList.splice(InsertBefore->getIterator(), FromList, FromList.begin(), 1110 FromBB->getTerminator()->getIterator()); 1111 } 1112 1113 void LoopInterchangeTransform::updateIncomingBlock(BasicBlock *CurrBlock, 1114 BasicBlock *OldPred, 1115 BasicBlock *NewPred) { 1116 for (auto I = CurrBlock->begin(); isa<PHINode>(I); ++I) { 1117 PHINode *PHI = cast<PHINode>(I); 1118 unsigned Num = PHI->getNumIncomingValues(); 1119 for (unsigned i = 0; i < Num; ++i) { 1120 if (PHI->getIncomingBlock(i) == OldPred) 1121 PHI->setIncomingBlock(i, NewPred); 1122 } 1123 } 1124 } 1125 1126 bool LoopInterchangeTransform::adjustLoopBranches() { 1127 1128 DEBUG(dbgs() << "adjustLoopBranches called\n"); 1129 // Adjust the loop preheader 1130 BasicBlock *InnerLoopHeader = InnerLoop->getHeader(); 1131 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 1132 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch(); 1133 BasicBlock *OuterLoopLatch = OuterLoop->getLoopLatch(); 1134 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); 1135 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1136 BasicBlock *OuterLoopPredecessor = OuterLoopPreHeader->getUniquePredecessor(); 1137 BasicBlock *InnerLoopLatchPredecessor = 1138 InnerLoopLatch->getUniquePredecessor(); 1139 BasicBlock *InnerLoopLatchSuccessor; 1140 BasicBlock *OuterLoopLatchSuccessor; 1141 1142 BranchInst *OuterLoopLatchBI = 1143 dyn_cast<BranchInst>(OuterLoopLatch->getTerminator()); 1144 BranchInst *InnerLoopLatchBI = 1145 dyn_cast<BranchInst>(InnerLoopLatch->getTerminator()); 1146 BranchInst *OuterLoopHeaderBI = 1147 dyn_cast<BranchInst>(OuterLoopHeader->getTerminator()); 1148 BranchInst *InnerLoopHeaderBI = 1149 dyn_cast<BranchInst>(InnerLoopHeader->getTerminator()); 1150 1151 if (!OuterLoopPredecessor || !InnerLoopLatchPredecessor || 1152 !OuterLoopLatchBI || !InnerLoopLatchBI || !OuterLoopHeaderBI || 1153 !InnerLoopHeaderBI) 1154 return false; 1155 1156 BranchInst *InnerLoopLatchPredecessorBI = 1157 dyn_cast<BranchInst>(InnerLoopLatchPredecessor->getTerminator()); 1158 BranchInst *OuterLoopPredecessorBI = 1159 dyn_cast<BranchInst>(OuterLoopPredecessor->getTerminator()); 1160 1161 if (!OuterLoopPredecessorBI || !InnerLoopLatchPredecessorBI) 1162 return false; 1163 BasicBlock *InnerLoopHeaderSuccessor = InnerLoopHeader->getUniqueSuccessor(); 1164 if (!InnerLoopHeaderSuccessor) 1165 return false; 1166 1167 // Adjust Loop Preheader and headers 1168 1169 unsigned NumSucc = OuterLoopPredecessorBI->getNumSuccessors(); 1170 for (unsigned i = 0; i < NumSucc; ++i) { 1171 if (OuterLoopPredecessorBI->getSuccessor(i) == OuterLoopPreHeader) 1172 OuterLoopPredecessorBI->setSuccessor(i, InnerLoopPreHeader); 1173 } 1174 1175 NumSucc = OuterLoopHeaderBI->getNumSuccessors(); 1176 for (unsigned i = 0; i < NumSucc; ++i) { 1177 if (OuterLoopHeaderBI->getSuccessor(i) == OuterLoopLatch) 1178 OuterLoopHeaderBI->setSuccessor(i, LoopExit); 1179 else if (OuterLoopHeaderBI->getSuccessor(i) == InnerLoopPreHeader) 1180 OuterLoopHeaderBI->setSuccessor(i, InnerLoopHeaderSuccessor); 1181 } 1182 1183 // Adjust reduction PHI's now that the incoming block has changed. 1184 updateIncomingBlock(InnerLoopHeaderSuccessor, InnerLoopHeader, 1185 OuterLoopHeader); 1186 1187 BranchInst::Create(OuterLoopPreHeader, InnerLoopHeaderBI); 1188 InnerLoopHeaderBI->eraseFromParent(); 1189 1190 // -------------Adjust loop latches----------- 1191 if (InnerLoopLatchBI->getSuccessor(0) == InnerLoopHeader) 1192 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(1); 1193 else 1194 InnerLoopLatchSuccessor = InnerLoopLatchBI->getSuccessor(0); 1195 1196 NumSucc = InnerLoopLatchPredecessorBI->getNumSuccessors(); 1197 for (unsigned i = 0; i < NumSucc; ++i) { 1198 if (InnerLoopLatchPredecessorBI->getSuccessor(i) == InnerLoopLatch) 1199 InnerLoopLatchPredecessorBI->setSuccessor(i, InnerLoopLatchSuccessor); 1200 } 1201 1202 // Adjust PHI nodes in InnerLoopLatchSuccessor. Update all uses of PHI with 1203 // the value and remove this PHI node from inner loop. 1204 SmallVector<PHINode *, 8> LcssaVec; 1205 for (auto I = InnerLoopLatchSuccessor->begin(); isa<PHINode>(I); ++I) { 1206 PHINode *LcssaPhi = cast<PHINode>(I); 1207 LcssaVec.push_back(LcssaPhi); 1208 } 1209 for (PHINode *P : LcssaVec) { 1210 Value *Incoming = P->getIncomingValueForBlock(InnerLoopLatch); 1211 P->replaceAllUsesWith(Incoming); 1212 P->eraseFromParent(); 1213 } 1214 1215 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopHeader) 1216 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(1); 1217 else 1218 OuterLoopLatchSuccessor = OuterLoopLatchBI->getSuccessor(0); 1219 1220 if (InnerLoopLatchBI->getSuccessor(1) == InnerLoopLatchSuccessor) 1221 InnerLoopLatchBI->setSuccessor(1, OuterLoopLatchSuccessor); 1222 else 1223 InnerLoopLatchBI->setSuccessor(0, OuterLoopLatchSuccessor); 1224 1225 updateIncomingBlock(OuterLoopLatchSuccessor, OuterLoopLatch, InnerLoopLatch); 1226 1227 if (OuterLoopLatchBI->getSuccessor(0) == OuterLoopLatchSuccessor) { 1228 OuterLoopLatchBI->setSuccessor(0, InnerLoopLatch); 1229 } else { 1230 OuterLoopLatchBI->setSuccessor(1, InnerLoopLatch); 1231 } 1232 1233 return true; 1234 } 1235 void LoopInterchangeTransform::adjustLoopPreheaders() { 1236 1237 // We have interchanged the preheaders so we need to interchange the data in 1238 // the preheader as well. 1239 // This is because the content of inner preheader was previously executed 1240 // inside the outer loop. 1241 BasicBlock *OuterLoopPreHeader = OuterLoop->getLoopPreheader(); 1242 BasicBlock *InnerLoopPreHeader = InnerLoop->getLoopPreheader(); 1243 BasicBlock *OuterLoopHeader = OuterLoop->getHeader(); 1244 BranchInst *InnerTermBI = 1245 cast<BranchInst>(InnerLoopPreHeader->getTerminator()); 1246 1247 // These instructions should now be executed inside the loop. 1248 // Move instruction into a new block after outer header. 1249 moveBBContents(InnerLoopPreHeader, OuterLoopHeader->getTerminator()); 1250 // These instructions were not executed previously in the loop so move them to 1251 // the older inner loop preheader. 1252 moveBBContents(OuterLoopPreHeader, InnerTermBI); 1253 } 1254 1255 bool LoopInterchangeTransform::adjustLoopLinks() { 1256 1257 // Adjust all branches in the inner and outer loop. 1258 bool Changed = adjustLoopBranches(); 1259 if (Changed) 1260 adjustLoopPreheaders(); 1261 return Changed; 1262 } 1263 1264 char LoopInterchange::ID = 0; 1265 INITIALIZE_PASS_BEGIN(LoopInterchange, "loop-interchange", 1266 "Interchanges loops for cache reuse", false, false) 1267 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 1268 INITIALIZE_PASS_DEPENDENCY(DependenceAnalysisWrapperPass) 1269 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1270 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 1271 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 1272 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass) 1273 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 1274 1275 INITIALIZE_PASS_END(LoopInterchange, "loop-interchange", 1276 "Interchanges loops for cache reuse", false, false) 1277 1278 Pass *llvm::createLoopInterchangePass() { return new LoopInterchange(); } 1279