1 //===- LoopFlatten.cpp - Loop flattening pass------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This pass flattens pairs nested loops into a single loop. 10 // 11 // The intention is to optimise loop nests like this, which together access an 12 // array linearly: 13 // for (int i = 0; i < N; ++i) 14 // for (int j = 0; j < M; ++j) 15 // f(A[i*M+j]); 16 // into one loop: 17 // for (int i = 0; i < (N*M); ++i) 18 // f(A[i]); 19 // 20 // It can also flatten loops where the induction variables are not used in the 21 // loop. This is only worth doing if the induction variables are only used in an 22 // expression like i*M+j. If they had any other uses, we would have to insert a 23 // div/mod to reconstruct the original values, so this wouldn't be profitable. 24 // 25 // We also need to prove that N*M will not overflow. 26 // 27 //===----------------------------------------------------------------------===// 28 29 #include "llvm/Transforms/Scalar/LoopFlatten.h" 30 #include "llvm/Analysis/AssumptionCache.h" 31 #include "llvm/Analysis/LoopInfo.h" 32 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 33 #include "llvm/Analysis/ScalarEvolution.h" 34 #include "llvm/Analysis/TargetTransformInfo.h" 35 #include "llvm/Analysis/ValueTracking.h" 36 #include "llvm/IR/Dominators.h" 37 #include "llvm/IR/Function.h" 38 #include "llvm/IR/Module.h" 39 #include "llvm/IR/PatternMatch.h" 40 #include "llvm/IR/Verifier.h" 41 #include "llvm/InitializePasses.h" 42 #include "llvm/Pass.h" 43 #include "llvm/Support/Debug.h" 44 #include "llvm/Support/raw_ostream.h" 45 #include "llvm/Transforms/Scalar.h" 46 #include "llvm/Transforms/Utils/LoopUtils.h" 47 48 #define DEBUG_TYPE "loop-flatten" 49 50 using namespace llvm; 51 using namespace llvm::PatternMatch; 52 53 static cl::opt<unsigned> RepeatedInstructionThreshold( 54 "loop-flatten-cost-threshold", cl::Hidden, cl::init(2), 55 cl::desc("Limit on the cost of instructions that can be repeated due to " 56 "loop flattening")); 57 58 static cl::opt<bool> 59 AssumeNoOverflow("loop-flatten-assume-no-overflow", cl::Hidden, 60 cl::init(false), 61 cl::desc("Assume that the product of the two iteration " 62 "limits will never overflow")); 63 64 struct FlattenInfo { 65 Loop *OuterLoop = nullptr; 66 Loop *InnerLoop = nullptr; 67 PHINode *InnerInductionPHI = nullptr; 68 PHINode *OuterInductionPHI = nullptr; 69 Value *InnerLimit = nullptr; 70 Value *OuterLimit = nullptr; 71 BinaryOperator *InnerIncrement = nullptr; 72 BinaryOperator *OuterIncrement = nullptr; 73 BranchInst *InnerBranch = nullptr; 74 BranchInst *OuterBranch = nullptr; 75 SmallPtrSet<Value *, 4> LinearIVUses; 76 SmallPtrSet<PHINode *, 4> InnerPHIsToTransform; 77 78 FlattenInfo(Loop *OL, Loop *IL) : OuterLoop(OL), InnerLoop(IL) {}; 79 }; 80 81 // Finds the induction variable, increment and limit for a simple loop that we 82 // can flatten. 83 static bool findLoopComponents( 84 Loop *L, SmallPtrSetImpl<Instruction *> &IterationInstructions, 85 PHINode *&InductionPHI, Value *&Limit, BinaryOperator *&Increment, 86 BranchInst *&BackBranch, ScalarEvolution *SE) { 87 LLVM_DEBUG(dbgs() << "Finding components of loop: " << L->getName() << "\n"); 88 89 if (!L->isLoopSimplifyForm()) { 90 LLVM_DEBUG(dbgs() << "Loop is not in normal form\n"); 91 return false; 92 } 93 94 // There must be exactly one exiting block, and it must be the same at the 95 // latch. 96 BasicBlock *Latch = L->getLoopLatch(); 97 if (L->getExitingBlock() != Latch) { 98 LLVM_DEBUG(dbgs() << "Exiting and latch block are different\n"); 99 return false; 100 } 101 // Latch block must end in a conditional branch. 102 BackBranch = dyn_cast<BranchInst>(Latch->getTerminator()); 103 if (!BackBranch || !BackBranch->isConditional()) { 104 LLVM_DEBUG(dbgs() << "Could not find back-branch\n"); 105 return false; 106 } 107 IterationInstructions.insert(BackBranch); 108 LLVM_DEBUG(dbgs() << "Found back branch: "; BackBranch->dump()); 109 bool ContinueOnTrue = L->contains(BackBranch->getSuccessor(0)); 110 111 // Find the induction PHI. If there is no induction PHI, we can't do the 112 // transformation. TODO: could other variables trigger this? Do we have to 113 // search for the best one? 114 InductionPHI = nullptr; 115 for (PHINode &PHI : L->getHeader()->phis()) { 116 InductionDescriptor ID; 117 if (InductionDescriptor::isInductionPHI(&PHI, L, SE, ID)) { 118 InductionPHI = &PHI; 119 LLVM_DEBUG(dbgs() << "Found induction PHI: "; InductionPHI->dump()); 120 break; 121 } 122 } 123 if (!InductionPHI) { 124 LLVM_DEBUG(dbgs() << "Could not find induction PHI\n"); 125 return false; 126 } 127 128 auto IsValidPredicate = [&](ICmpInst::Predicate Pred) { 129 if (ContinueOnTrue) 130 return Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT; 131 else 132 return Pred == CmpInst::ICMP_EQ; 133 }; 134 135 // Find Compare and make sure it is valid 136 ICmpInst *Compare = dyn_cast<ICmpInst>(BackBranch->getCondition()); 137 if (!Compare || !IsValidPredicate(Compare->getUnsignedPredicate()) || 138 Compare->hasNUsesOrMore(2)) { 139 LLVM_DEBUG(dbgs() << "Could not find valid comparison\n"); 140 return false; 141 } 142 IterationInstructions.insert(Compare); 143 LLVM_DEBUG(dbgs() << "Found comparison: "; Compare->dump()); 144 145 // Find increment and limit from the compare 146 Increment = nullptr; 147 if (match(Compare->getOperand(0), 148 m_c_Add(m_Specific(InductionPHI), m_ConstantInt<1>()))) { 149 Increment = dyn_cast<BinaryOperator>(Compare->getOperand(0)); 150 Limit = Compare->getOperand(1); 151 } else if (Compare->getUnsignedPredicate() == CmpInst::ICMP_NE && 152 match(Compare->getOperand(1), 153 m_c_Add(m_Specific(InductionPHI), m_ConstantInt<1>()))) { 154 Increment = dyn_cast<BinaryOperator>(Compare->getOperand(1)); 155 Limit = Compare->getOperand(0); 156 } 157 if (!Increment || Increment->hasNUsesOrMore(3)) { 158 LLVM_DEBUG(dbgs() << "Cound not find valid increment\n"); 159 return false; 160 } 161 IterationInstructions.insert(Increment); 162 LLVM_DEBUG(dbgs() << "Found increment: "; Increment->dump()); 163 LLVM_DEBUG(dbgs() << "Found limit: "; Limit->dump()); 164 165 assert(InductionPHI->getNumIncomingValues() == 2); 166 assert(InductionPHI->getIncomingValueForBlock(Latch) == Increment && 167 "PHI value is not increment inst"); 168 169 auto *CI = dyn_cast<ConstantInt>( 170 InductionPHI->getIncomingValueForBlock(L->getLoopPreheader())); 171 if (!CI || !CI->isZero()) { 172 LLVM_DEBUG(dbgs() << "PHI value is not zero: "; CI->dump()); 173 return false; 174 } 175 176 LLVM_DEBUG(dbgs() << "Successfully found all loop components\n"); 177 return true; 178 } 179 180 static bool checkPHIs(struct FlattenInfo &FI, 181 const TargetTransformInfo *TTI) { 182 // All PHIs in the inner and outer headers must either be: 183 // - The induction PHI, which we are going to rewrite as one induction in 184 // the new loop. This is already checked by findLoopComponents. 185 // - An outer header PHI with all incoming values from outside the loop. 186 // LoopSimplify guarantees we have a pre-header, so we don't need to 187 // worry about that here. 188 // - Pairs of PHIs in the inner and outer headers, which implement a 189 // loop-carried dependency that will still be valid in the new loop. To 190 // be valid, this variable must be modified only in the inner loop. 191 192 // The set of PHI nodes in the outer loop header that we know will still be 193 // valid after the transformation. These will not need to be modified (with 194 // the exception of the induction variable), but we do need to check that 195 // there are no unsafe PHI nodes. 196 SmallPtrSet<PHINode *, 4> SafeOuterPHIs; 197 SafeOuterPHIs.insert(FI.OuterInductionPHI); 198 199 // Check that all PHI nodes in the inner loop header match one of the valid 200 // patterns. 201 for (PHINode &InnerPHI : FI.InnerLoop->getHeader()->phis()) { 202 // The induction PHIs break these rules, and that's OK because we treat 203 // them specially when doing the transformation. 204 if (&InnerPHI == FI.InnerInductionPHI) 205 continue; 206 207 // Each inner loop PHI node must have two incoming values/blocks - one 208 // from the pre-header, and one from the latch. 209 assert(InnerPHI.getNumIncomingValues() == 2); 210 Value *PreHeaderValue = 211 InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopPreheader()); 212 Value *LatchValue = 213 InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopLatch()); 214 215 // The incoming value from the outer loop must be the PHI node in the 216 // outer loop header, with no modifications made in the top of the outer 217 // loop. 218 PHINode *OuterPHI = dyn_cast<PHINode>(PreHeaderValue); 219 if (!OuterPHI || OuterPHI->getParent() != FI.OuterLoop->getHeader()) { 220 LLVM_DEBUG(dbgs() << "value modified in top of outer loop\n"); 221 return false; 222 } 223 224 // The other incoming value must come from the inner loop, without any 225 // modifications in the tail end of the outer loop. We are in LCSSA form, 226 // so this will actually be a PHI in the inner loop's exit block, which 227 // only uses values from inside the inner loop. 228 PHINode *LCSSAPHI = dyn_cast<PHINode>( 229 OuterPHI->getIncomingValueForBlock(FI.OuterLoop->getLoopLatch())); 230 if (!LCSSAPHI) { 231 LLVM_DEBUG(dbgs() << "could not find LCSSA PHI\n"); 232 return false; 233 } 234 235 // The value used by the LCSSA PHI must be the same one that the inner 236 // loop's PHI uses. 237 if (LCSSAPHI->hasConstantValue() != LatchValue) { 238 LLVM_DEBUG( 239 dbgs() << "LCSSA PHI incoming value does not match latch value\n"); 240 return false; 241 } 242 243 LLVM_DEBUG(dbgs() << "PHI pair is safe:\n"); 244 LLVM_DEBUG(dbgs() << " Inner: "; InnerPHI.dump()); 245 LLVM_DEBUG(dbgs() << " Outer: "; OuterPHI->dump()); 246 SafeOuterPHIs.insert(OuterPHI); 247 FI.InnerPHIsToTransform.insert(&InnerPHI); 248 } 249 250 for (PHINode &OuterPHI : FI.OuterLoop->getHeader()->phis()) { 251 if (!SafeOuterPHIs.count(&OuterPHI)) { 252 LLVM_DEBUG(dbgs() << "found unsafe PHI in outer loop: "; OuterPHI.dump()); 253 return false; 254 } 255 } 256 257 return true; 258 } 259 260 static bool 261 checkOuterLoopInsts(struct FlattenInfo &FI, 262 SmallPtrSetImpl<Instruction *> &IterationInstructions, 263 const TargetTransformInfo *TTI) { 264 // Check for instructions in the outer but not inner loop. If any of these 265 // have side-effects then this transformation is not legal, and if there is 266 // a significant amount of code here which can't be optimised out that it's 267 // not profitable (as these instructions would get executed for each 268 // iteration of the inner loop). 269 unsigned RepeatedInstrCost = 0; 270 for (auto *B : FI.OuterLoop->getBlocks()) { 271 if (FI.InnerLoop->contains(B)) 272 continue; 273 274 for (auto &I : *B) { 275 if (!isa<PHINode>(&I) && !I.isTerminator() && 276 !isSafeToSpeculativelyExecute(&I)) { 277 LLVM_DEBUG(dbgs() << "Cannot flatten because instruction may have " 278 "side effects: "; 279 I.dump()); 280 return false; 281 } 282 // The execution count of the outer loop's iteration instructions 283 // (increment, compare and branch) will be increased, but the 284 // equivalent instructions will be removed from the inner loop, so 285 // they make a net difference of zero. 286 if (IterationInstructions.count(&I)) 287 continue; 288 // The uncoditional branch to the inner loop's header will turn into 289 // a fall-through, so adds no cost. 290 BranchInst *Br = dyn_cast<BranchInst>(&I); 291 if (Br && Br->isUnconditional() && 292 Br->getSuccessor(0) == FI.InnerLoop->getHeader()) 293 continue; 294 // Multiplies of the outer iteration variable and inner iteration 295 // count will be optimised out. 296 if (match(&I, m_c_Mul(m_Specific(FI.OuterInductionPHI), 297 m_Specific(FI.InnerLimit)))) 298 continue; 299 int Cost = TTI->getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency); 300 LLVM_DEBUG(dbgs() << "Cost " << Cost << ": "; I.dump()); 301 RepeatedInstrCost += Cost; 302 } 303 } 304 305 LLVM_DEBUG(dbgs() << "Cost of instructions that will be repeated: " 306 << RepeatedInstrCost << "\n"); 307 // Bail out if flattening the loops would cause instructions in the outer 308 // loop but not in the inner loop to be executed extra times. 309 if (RepeatedInstrCost > RepeatedInstructionThreshold) 310 return false; 311 312 return true; 313 } 314 315 static bool checkIVUsers(struct FlattenInfo &FI) { 316 // We require all uses of both induction variables to match this pattern: 317 // 318 // (OuterPHI * InnerLimit) + InnerPHI 319 // 320 // Any uses of the induction variables not matching that pattern would 321 // require a div/mod to reconstruct in the flattened loop, so the 322 // transformation wouldn't be profitable. 323 324 // Check that all uses of the inner loop's induction variable match the 325 // expected pattern, recording the uses of the outer IV. 326 SmallPtrSet<Value *, 4> ValidOuterPHIUses; 327 for (User *U : FI.InnerInductionPHI->users()) { 328 if (U == FI.InnerIncrement) 329 continue; 330 331 LLVM_DEBUG(dbgs() << "Found use of inner induction variable: "; U->dump()); 332 333 Value *MatchedMul, *MatchedItCount; 334 if (match(U, m_c_Add(m_Specific(FI.InnerInductionPHI), 335 m_Value(MatchedMul))) && 336 match(MatchedMul, 337 m_c_Mul(m_Specific(FI.OuterInductionPHI), 338 m_Value(MatchedItCount))) && 339 MatchedItCount == FI.InnerLimit) { 340 LLVM_DEBUG(dbgs() << "Use is optimisable\n"); 341 ValidOuterPHIUses.insert(MatchedMul); 342 FI.LinearIVUses.insert(U); 343 } else { 344 LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n"); 345 return false; 346 } 347 } 348 349 // Check that there are no uses of the outer IV other than the ones found 350 // as part of the pattern above. 351 for (User *U : FI.OuterInductionPHI->users()) { 352 if (U == FI.OuterIncrement) 353 continue; 354 355 LLVM_DEBUG(dbgs() << "Found use of outer induction variable: "; U->dump()); 356 357 if (!ValidOuterPHIUses.count(U)) { 358 LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n"); 359 return false; 360 } else { 361 LLVM_DEBUG(dbgs() << "Use is optimisable\n"); 362 } 363 } 364 365 LLVM_DEBUG(dbgs() << "Found " << FI.LinearIVUses.size() 366 << " value(s) that can be replaced:\n"; 367 for (Value *V : FI.LinearIVUses) { 368 dbgs() << " "; 369 V->dump(); 370 }); 371 372 return true; 373 } 374 375 // Return an OverflowResult dependant on if overflow of the multiplication of 376 // InnerLimit and OuterLimit can be assumed not to happen. 377 static OverflowResult checkOverflow(struct FlattenInfo &FI, 378 DominatorTree *DT, AssumptionCache *AC) { 379 Function *F = FI.OuterLoop->getHeader()->getParent(); 380 const DataLayout &DL = F->getParent()->getDataLayout(); 381 382 // For debugging/testing. 383 if (AssumeNoOverflow) 384 return OverflowResult::NeverOverflows; 385 386 // Check if the multiply could not overflow due to known ranges of the 387 // input values. 388 OverflowResult OR = computeOverflowForUnsignedMul( 389 FI.InnerLimit, FI.OuterLimit, DL, AC, 390 FI.OuterLoop->getLoopPreheader()->getTerminator(), DT); 391 if (OR != OverflowResult::MayOverflow) 392 return OR; 393 394 for (Value *V : FI.LinearIVUses) { 395 for (Value *U : V->users()) { 396 if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) { 397 // The IV is used as the operand of a GEP, and the IV is at least as 398 // wide as the address space of the GEP. In this case, the GEP would 399 // wrap around the address space before the IV increment wraps, which 400 // would be UB. 401 if (GEP->isInBounds() && 402 V->getType()->getIntegerBitWidth() >= 403 DL.getPointerTypeSizeInBits(GEP->getType())) { 404 LLVM_DEBUG( 405 dbgs() << "use of linear IV would be UB if overflow occurred: "; 406 GEP->dump()); 407 return OverflowResult::NeverOverflows; 408 } 409 } 410 } 411 } 412 413 return OverflowResult::MayOverflow; 414 } 415 416 static bool FlattenLoopPair(struct FlattenInfo &FI, DominatorTree *DT, 417 LoopInfo *LI, ScalarEvolution *SE, 418 AssumptionCache *AC, TargetTransformInfo *TTI) { 419 Function *F = FI.OuterLoop->getHeader()->getParent(); 420 LLVM_DEBUG(dbgs() << "Loop flattening running on outer loop " 421 << FI.OuterLoop->getHeader()->getName() << " and inner loop " 422 << FI.InnerLoop->getHeader()->getName() << " in " 423 << F->getName() << "\n"); 424 425 SmallPtrSet<Instruction *, 8> IterationInstructions; 426 if (!findLoopComponents(FI.InnerLoop, IterationInstructions, FI.InnerInductionPHI, 427 FI.InnerLimit, FI.InnerIncrement, FI.InnerBranch, SE)) 428 return false; 429 if (!findLoopComponents(FI.OuterLoop, IterationInstructions, FI.OuterInductionPHI, 430 FI.OuterLimit, FI.OuterIncrement, FI.OuterBranch, SE)) 431 return false; 432 433 // Both of the loop limit values must be invariant in the outer loop 434 // (non-instructions are all inherently invariant). 435 if (!FI.OuterLoop->isLoopInvariant(FI.InnerLimit)) { 436 LLVM_DEBUG(dbgs() << "inner loop limit not invariant\n"); 437 return false; 438 } 439 if (!FI.OuterLoop->isLoopInvariant(FI.OuterLimit)) { 440 LLVM_DEBUG(dbgs() << "outer loop limit not invariant\n"); 441 return false; 442 } 443 444 if (!checkPHIs(FI, TTI)) 445 return false; 446 447 // FIXME: it should be possible to handle different types correctly. 448 if (FI.InnerInductionPHI->getType() != FI.OuterInductionPHI->getType()) 449 return false; 450 451 if (!checkOuterLoopInsts(FI, IterationInstructions, TTI)) 452 return false; 453 454 // Find the values in the loop that can be replaced with the linearized 455 // induction variable, and check that there are no other uses of the inner 456 // or outer induction variable. If there were, we could still do this 457 // transformation, but we'd have to insert a div/mod to calculate the 458 // original IVs, so it wouldn't be profitable. 459 if (!checkIVUsers(FI)) 460 return false; 461 462 // Check if the new iteration variable might overflow. In this case, we 463 // need to version the loop, and select the original version at runtime if 464 // the iteration space is too large. 465 // TODO: We currently don't version the loop. 466 // TODO: it might be worth using a wider iteration variable rather than 467 // versioning the loop, if a wide enough type is legal. 468 bool MustVersionLoop = true; 469 OverflowResult OR = checkOverflow(FI, DT, AC); 470 if (OR == OverflowResult::AlwaysOverflowsHigh || 471 OR == OverflowResult::AlwaysOverflowsLow) { 472 LLVM_DEBUG(dbgs() << "Multiply would always overflow, so not profitable\n"); 473 return false; 474 } else if (OR == OverflowResult::MayOverflow) { 475 LLVM_DEBUG(dbgs() << "Multiply might overflow, not flattening\n"); 476 } else { 477 LLVM_DEBUG(dbgs() << "Multiply cannot overflow, modifying loop in-place\n"); 478 MustVersionLoop = false; 479 } 480 481 // We cannot safely flatten the loop. Exit now. 482 if (MustVersionLoop) 483 return false; 484 485 // Do the actual transformation. 486 LLVM_DEBUG(dbgs() << "Checks all passed, doing the transformation\n"); 487 488 { 489 using namespace ore; 490 OptimizationRemark Remark(DEBUG_TYPE, "Flattened", FI.InnerLoop->getStartLoc(), 491 FI.InnerLoop->getHeader()); 492 OptimizationRemarkEmitter ORE(F); 493 Remark << "Flattened into outer loop"; 494 ORE.emit(Remark); 495 } 496 497 Value *NewTripCount = 498 BinaryOperator::CreateMul(FI.InnerLimit, FI.OuterLimit, "flatten.tripcount", 499 FI.OuterLoop->getLoopPreheader()->getTerminator()); 500 LLVM_DEBUG(dbgs() << "Created new trip count in preheader: "; 501 NewTripCount->dump()); 502 503 // Fix up PHI nodes that take values from the inner loop back-edge, which 504 // we are about to remove. 505 FI.InnerInductionPHI->removeIncomingValue(FI.InnerLoop->getLoopLatch()); 506 for (PHINode *PHI : FI.InnerPHIsToTransform) 507 PHI->removeIncomingValue(FI.InnerLoop->getLoopLatch()); 508 509 // Modify the trip count of the outer loop to be the product of the two 510 // trip counts. 511 cast<User>(FI.OuterBranch->getCondition())->setOperand(1, NewTripCount); 512 513 // Replace the inner loop backedge with an unconditional branch to the exit. 514 BasicBlock *InnerExitBlock = FI.InnerLoop->getExitBlock(); 515 BasicBlock *InnerExitingBlock = FI.InnerLoop->getExitingBlock(); 516 InnerExitingBlock->getTerminator()->eraseFromParent(); 517 BranchInst::Create(InnerExitBlock, InnerExitingBlock); 518 DT->deleteEdge(InnerExitingBlock, FI.InnerLoop->getHeader()); 519 520 // Replace all uses of the polynomial calculated from the two induction 521 // variables with the one new one. 522 for (Value *V : FI.LinearIVUses) 523 V->replaceAllUsesWith(FI.OuterInductionPHI); 524 525 // Tell LoopInfo, SCEV and the pass manager that the inner loop has been 526 // deleted, and any information that have about the outer loop invalidated. 527 SE->forgetLoop(FI.OuterLoop); 528 SE->forgetLoop(FI.InnerLoop); 529 LI->erase(FI.InnerLoop); 530 return true; 531 } 532 533 bool Flatten(DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, 534 AssumptionCache *AC, TargetTransformInfo *TTI) { 535 bool Changed = false; 536 for (auto *InnerLoop : LI->getLoopsInPreorder()) { 537 auto *OuterLoop = InnerLoop->getParentLoop(); 538 if (!OuterLoop) 539 continue; 540 struct FlattenInfo FI(OuterLoop, InnerLoop); 541 Changed |= FlattenLoopPair(FI, DT, LI, SE, AC, TTI); 542 } 543 return Changed; 544 } 545 546 PreservedAnalyses LoopFlattenPass::run(Function &F, 547 FunctionAnalysisManager &AM) { 548 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); 549 auto *LI = &AM.getResult<LoopAnalysis>(F); 550 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F); 551 auto *AC = &AM.getResult<AssumptionAnalysis>(F); 552 auto *TTI = &AM.getResult<TargetIRAnalysis>(F); 553 554 if (!Flatten(DT, LI, SE, AC, TTI)) 555 return PreservedAnalyses::all(); 556 557 PreservedAnalyses PA; 558 PA.preserveSet<CFGAnalyses>(); 559 return PA; 560 } 561 562 namespace { 563 class LoopFlattenLegacyPass : public FunctionPass { 564 public: 565 static char ID; // Pass ID, replacement for typeid 566 LoopFlattenLegacyPass() : FunctionPass(ID) { 567 initializeLoopFlattenLegacyPassPass(*PassRegistry::getPassRegistry()); 568 } 569 570 // Possibly flatten loop L into its child. 571 bool runOnFunction(Function &F) override; 572 573 void getAnalysisUsage(AnalysisUsage &AU) const override { 574 getLoopAnalysisUsage(AU); 575 AU.addRequired<TargetTransformInfoWrapperPass>(); 576 AU.addPreserved<TargetTransformInfoWrapperPass>(); 577 AU.addRequired<AssumptionCacheTracker>(); 578 AU.addPreserved<AssumptionCacheTracker>(); 579 } 580 }; 581 } // namespace 582 583 char LoopFlattenLegacyPass::ID = 0; 584 INITIALIZE_PASS_BEGIN(LoopFlattenLegacyPass, "loop-flatten", "Flattens loops", 585 false, false) 586 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 587 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 588 INITIALIZE_PASS_END(LoopFlattenLegacyPass, "loop-flatten", "Flattens loops", 589 false, false) 590 591 FunctionPass *llvm::createLoopFlattenPass() { return new LoopFlattenLegacyPass(); } 592 593 bool LoopFlattenLegacyPass::runOnFunction(Function &F) { 594 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 595 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 596 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 597 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr; 598 auto &TTIP = getAnalysis<TargetTransformInfoWrapperPass>(); 599 auto *TTI = &TTIP.getTTI(F); 600 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 601 return Flatten(DT, LI, SE, AC, TTI); 602 } 603