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/IRBuilder.h" 39 #include "llvm/IR/Module.h" 40 #include "llvm/IR/PatternMatch.h" 41 #include "llvm/IR/Verifier.h" 42 #include "llvm/InitializePasses.h" 43 #include "llvm/Pass.h" 44 #include "llvm/Support/Debug.h" 45 #include "llvm/Support/raw_ostream.h" 46 #include "llvm/Transforms/Scalar.h" 47 #include "llvm/Transforms/Utils/Local.h" 48 #include "llvm/Transforms/Utils/LoopUtils.h" 49 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 50 #include "llvm/Transforms/Utils/SimplifyIndVar.h" 51 52 #define DEBUG_TYPE "loop-flatten" 53 54 using namespace llvm; 55 using namespace llvm::PatternMatch; 56 57 static cl::opt<unsigned> RepeatedInstructionThreshold( 58 "loop-flatten-cost-threshold", cl::Hidden, cl::init(2), 59 cl::desc("Limit on the cost of instructions that can be repeated due to " 60 "loop flattening")); 61 62 static cl::opt<bool> 63 AssumeNoOverflow("loop-flatten-assume-no-overflow", cl::Hidden, 64 cl::init(false), 65 cl::desc("Assume that the product of the two iteration " 66 "limits will never overflow")); 67 68 static cl::opt<bool> 69 WidenIV("loop-flatten-widen-iv", cl::Hidden, 70 cl::init(true), 71 cl::desc("Widen the loop induction variables, if possible, so " 72 "overflow checks won't reject flattening")); 73 74 struct FlattenInfo { 75 Loop *OuterLoop = nullptr; 76 Loop *InnerLoop = nullptr; 77 PHINode *InnerInductionPHI = nullptr; 78 PHINode *OuterInductionPHI = nullptr; 79 Value *InnerLimit = nullptr; 80 Value *OuterLimit = nullptr; 81 BinaryOperator *InnerIncrement = nullptr; 82 BinaryOperator *OuterIncrement = nullptr; 83 BranchInst *InnerBranch = nullptr; 84 BranchInst *OuterBranch = nullptr; 85 SmallPtrSet<Value *, 4> LinearIVUses; 86 SmallPtrSet<PHINode *, 4> InnerPHIsToTransform; 87 88 // Whether this holds the flatten info before or after widening. 89 bool Widened = false; 90 91 FlattenInfo(Loop *OL, Loop *IL) : OuterLoop(OL), InnerLoop(IL) {}; 92 }; 93 94 // Finds the induction variable, increment and limit for a simple loop that we 95 // can flatten. 96 static bool findLoopComponents( 97 Loop *L, SmallPtrSetImpl<Instruction *> &IterationInstructions, 98 PHINode *&InductionPHI, Value *&Limit, BinaryOperator *&Increment, 99 BranchInst *&BackBranch, ScalarEvolution *SE) { 100 LLVM_DEBUG(dbgs() << "Finding components of loop: " << L->getName() << "\n"); 101 102 if (!L->isLoopSimplifyForm()) { 103 LLVM_DEBUG(dbgs() << "Loop is not in normal form\n"); 104 return false; 105 } 106 107 // There must be exactly one exiting block, and it must be the same at the 108 // latch. 109 BasicBlock *Latch = L->getLoopLatch(); 110 if (L->getExitingBlock() != Latch) { 111 LLVM_DEBUG(dbgs() << "Exiting and latch block are different\n"); 112 return false; 113 } 114 // Latch block must end in a conditional branch. 115 BackBranch = dyn_cast<BranchInst>(Latch->getTerminator()); 116 if (!BackBranch || !BackBranch->isConditional()) { 117 LLVM_DEBUG(dbgs() << "Could not find back-branch\n"); 118 return false; 119 } 120 IterationInstructions.insert(BackBranch); 121 LLVM_DEBUG(dbgs() << "Found back branch: "; BackBranch->dump()); 122 bool ContinueOnTrue = L->contains(BackBranch->getSuccessor(0)); 123 124 // Find the induction PHI. If there is no induction PHI, we can't do the 125 // transformation. TODO: could other variables trigger this? Do we have to 126 // search for the best one? 127 InductionPHI = nullptr; 128 for (PHINode &PHI : L->getHeader()->phis()) { 129 InductionDescriptor ID; 130 if (InductionDescriptor::isInductionPHI(&PHI, L, SE, ID)) { 131 InductionPHI = &PHI; 132 LLVM_DEBUG(dbgs() << "Found induction PHI: "; InductionPHI->dump()); 133 break; 134 } 135 } 136 if (!InductionPHI) { 137 LLVM_DEBUG(dbgs() << "Could not find induction PHI\n"); 138 return false; 139 } 140 141 auto IsValidPredicate = [&](ICmpInst::Predicate Pred) { 142 if (ContinueOnTrue) 143 return Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT; 144 else 145 return Pred == CmpInst::ICMP_EQ; 146 }; 147 148 // Find Compare and make sure it is valid 149 ICmpInst *Compare = dyn_cast<ICmpInst>(BackBranch->getCondition()); 150 if (!Compare || !IsValidPredicate(Compare->getUnsignedPredicate()) || 151 Compare->hasNUsesOrMore(2)) { 152 LLVM_DEBUG(dbgs() << "Could not find valid comparison\n"); 153 return false; 154 } 155 IterationInstructions.insert(Compare); 156 LLVM_DEBUG(dbgs() << "Found comparison: "; Compare->dump()); 157 158 // Find increment and limit from the compare 159 Increment = nullptr; 160 if (match(Compare->getOperand(0), 161 m_c_Add(m_Specific(InductionPHI), m_ConstantInt<1>()))) { 162 Increment = dyn_cast<BinaryOperator>(Compare->getOperand(0)); 163 Limit = Compare->getOperand(1); 164 } else if (Compare->getUnsignedPredicate() == CmpInst::ICMP_NE && 165 match(Compare->getOperand(1), 166 m_c_Add(m_Specific(InductionPHI), m_ConstantInt<1>()))) { 167 Increment = dyn_cast<BinaryOperator>(Compare->getOperand(1)); 168 Limit = Compare->getOperand(0); 169 } 170 if (!Increment || Increment->hasNUsesOrMore(3)) { 171 LLVM_DEBUG(dbgs() << "Cound not find valid increment\n"); 172 return false; 173 } 174 IterationInstructions.insert(Increment); 175 LLVM_DEBUG(dbgs() << "Found increment: "; Increment->dump()); 176 LLVM_DEBUG(dbgs() << "Found limit: "; Limit->dump()); 177 178 assert(InductionPHI->getNumIncomingValues() == 2); 179 assert(InductionPHI->getIncomingValueForBlock(Latch) == Increment && 180 "PHI value is not increment inst"); 181 182 auto *CI = dyn_cast<ConstantInt>( 183 InductionPHI->getIncomingValueForBlock(L->getLoopPreheader())); 184 if (!CI || !CI->isZero()) { 185 LLVM_DEBUG(dbgs() << "PHI value is not zero: "; CI->dump()); 186 return false; 187 } 188 189 LLVM_DEBUG(dbgs() << "Successfully found all loop components\n"); 190 return true; 191 } 192 193 static bool checkPHIs(FlattenInfo &FI, const TargetTransformInfo *TTI) { 194 // All PHIs in the inner and outer headers must either be: 195 // - The induction PHI, which we are going to rewrite as one induction in 196 // the new loop. This is already checked by findLoopComponents. 197 // - An outer header PHI with all incoming values from outside the loop. 198 // LoopSimplify guarantees we have a pre-header, so we don't need to 199 // worry about that here. 200 // - Pairs of PHIs in the inner and outer headers, which implement a 201 // loop-carried dependency that will still be valid in the new loop. To 202 // be valid, this variable must be modified only in the inner loop. 203 204 // The set of PHI nodes in the outer loop header that we know will still be 205 // valid after the transformation. These will not need to be modified (with 206 // the exception of the induction variable), but we do need to check that 207 // there are no unsafe PHI nodes. 208 SmallPtrSet<PHINode *, 4> SafeOuterPHIs; 209 SafeOuterPHIs.insert(FI.OuterInductionPHI); 210 211 // Check that all PHI nodes in the inner loop header match one of the valid 212 // patterns. 213 for (PHINode &InnerPHI : FI.InnerLoop->getHeader()->phis()) { 214 // The induction PHIs break these rules, and that's OK because we treat 215 // them specially when doing the transformation. 216 if (&InnerPHI == FI.InnerInductionPHI) 217 continue; 218 219 // Each inner loop PHI node must have two incoming values/blocks - one 220 // from the pre-header, and one from the latch. 221 assert(InnerPHI.getNumIncomingValues() == 2); 222 Value *PreHeaderValue = 223 InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopPreheader()); 224 Value *LatchValue = 225 InnerPHI.getIncomingValueForBlock(FI.InnerLoop->getLoopLatch()); 226 227 // The incoming value from the outer loop must be the PHI node in the 228 // outer loop header, with no modifications made in the top of the outer 229 // loop. 230 PHINode *OuterPHI = dyn_cast<PHINode>(PreHeaderValue); 231 if (!OuterPHI || OuterPHI->getParent() != FI.OuterLoop->getHeader()) { 232 LLVM_DEBUG(dbgs() << "value modified in top of outer loop\n"); 233 return false; 234 } 235 236 // The other incoming value must come from the inner loop, without any 237 // modifications in the tail end of the outer loop. We are in LCSSA form, 238 // so this will actually be a PHI in the inner loop's exit block, which 239 // only uses values from inside the inner loop. 240 PHINode *LCSSAPHI = dyn_cast<PHINode>( 241 OuterPHI->getIncomingValueForBlock(FI.OuterLoop->getLoopLatch())); 242 if (!LCSSAPHI) { 243 LLVM_DEBUG(dbgs() << "could not find LCSSA PHI\n"); 244 return false; 245 } 246 247 // The value used by the LCSSA PHI must be the same one that the inner 248 // loop's PHI uses. 249 if (LCSSAPHI->hasConstantValue() != LatchValue) { 250 LLVM_DEBUG( 251 dbgs() << "LCSSA PHI incoming value does not match latch value\n"); 252 return false; 253 } 254 255 LLVM_DEBUG(dbgs() << "PHI pair is safe:\n"); 256 LLVM_DEBUG(dbgs() << " Inner: "; InnerPHI.dump()); 257 LLVM_DEBUG(dbgs() << " Outer: "; OuterPHI->dump()); 258 SafeOuterPHIs.insert(OuterPHI); 259 FI.InnerPHIsToTransform.insert(&InnerPHI); 260 } 261 262 for (PHINode &OuterPHI : FI.OuterLoop->getHeader()->phis()) { 263 if (!SafeOuterPHIs.count(&OuterPHI)) { 264 LLVM_DEBUG(dbgs() << "found unsafe PHI in outer loop: "; OuterPHI.dump()); 265 return false; 266 } 267 } 268 269 LLVM_DEBUG(dbgs() << "checkPHIs: OK\n"); 270 return true; 271 } 272 273 static bool 274 checkOuterLoopInsts(FlattenInfo &FI, 275 SmallPtrSetImpl<Instruction *> &IterationInstructions, 276 const TargetTransformInfo *TTI) { 277 // Check for instructions in the outer but not inner loop. If any of these 278 // have side-effects then this transformation is not legal, and if there is 279 // a significant amount of code here which can't be optimised out that it's 280 // not profitable (as these instructions would get executed for each 281 // iteration of the inner loop). 282 InstructionCost RepeatedInstrCost = 0; 283 for (auto *B : FI.OuterLoop->getBlocks()) { 284 if (FI.InnerLoop->contains(B)) 285 continue; 286 287 for (auto &I : *B) { 288 if (!isa<PHINode>(&I) && !I.isTerminator() && 289 !isSafeToSpeculativelyExecute(&I)) { 290 LLVM_DEBUG(dbgs() << "Cannot flatten because instruction may have " 291 "side effects: "; 292 I.dump()); 293 return false; 294 } 295 // The execution count of the outer loop's iteration instructions 296 // (increment, compare and branch) will be increased, but the 297 // equivalent instructions will be removed from the inner loop, so 298 // they make a net difference of zero. 299 if (IterationInstructions.count(&I)) 300 continue; 301 // The uncoditional branch to the inner loop's header will turn into 302 // a fall-through, so adds no cost. 303 BranchInst *Br = dyn_cast<BranchInst>(&I); 304 if (Br && Br->isUnconditional() && 305 Br->getSuccessor(0) == FI.InnerLoop->getHeader()) 306 continue; 307 // Multiplies of the outer iteration variable and inner iteration 308 // count will be optimised out. 309 if (match(&I, m_c_Mul(m_Specific(FI.OuterInductionPHI), 310 m_Specific(FI.InnerLimit)))) 311 continue; 312 InstructionCost Cost = 313 TTI->getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency); 314 LLVM_DEBUG(dbgs() << "Cost " << Cost << ": "; I.dump()); 315 RepeatedInstrCost += Cost; 316 } 317 } 318 319 LLVM_DEBUG(dbgs() << "Cost of instructions that will be repeated: " 320 << RepeatedInstrCost << "\n"); 321 // Bail out if flattening the loops would cause instructions in the outer 322 // loop but not in the inner loop to be executed extra times. 323 if (RepeatedInstrCost > RepeatedInstructionThreshold) { 324 LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: not profitable, bailing.\n"); 325 return false; 326 } 327 328 LLVM_DEBUG(dbgs() << "checkOuterLoopInsts: OK\n"); 329 return true; 330 } 331 332 static bool checkIVUsers(FlattenInfo &FI) { 333 // We require all uses of both induction variables to match this pattern: 334 // 335 // (OuterPHI * InnerLimit) + InnerPHI 336 // 337 // Any uses of the induction variables not matching that pattern would 338 // require a div/mod to reconstruct in the flattened loop, so the 339 // transformation wouldn't be profitable. 340 341 Value *InnerLimit = FI.InnerLimit; 342 if (FI.Widened && 343 (isa<SExtInst>(InnerLimit) || isa<ZExtInst>(InnerLimit))) 344 InnerLimit = cast<Instruction>(InnerLimit)->getOperand(0); 345 346 // Check that all uses of the inner loop's induction variable match the 347 // expected pattern, recording the uses of the outer IV. 348 SmallPtrSet<Value *, 4> ValidOuterPHIUses; 349 for (User *U : FI.InnerInductionPHI->users()) { 350 if (U == FI.InnerIncrement) 351 continue; 352 353 // After widening the IVs, a trunc instruction might have been introduced, so 354 // look through truncs. 355 if (isa<TruncInst>(U)) { 356 if (!U->hasOneUse()) 357 return false; 358 U = *U->user_begin(); 359 } 360 361 LLVM_DEBUG(dbgs() << "Found use of inner induction variable: "; U->dump()); 362 363 Value *MatchedMul; 364 Value *MatchedItCount; 365 bool IsAdd = match(U, m_c_Add(m_Specific(FI.InnerInductionPHI), 366 m_Value(MatchedMul))) && 367 match(MatchedMul, m_c_Mul(m_Specific(FI.OuterInductionPHI), 368 m_Value(MatchedItCount))); 369 370 // Matches the same pattern as above, except it also looks for truncs 371 // on the phi, which can be the result of widening the induction variables. 372 bool IsAddTrunc = match(U, m_c_Add(m_Trunc(m_Specific(FI.InnerInductionPHI)), 373 m_Value(MatchedMul))) && 374 match(MatchedMul, 375 m_c_Mul(m_Trunc(m_Specific(FI.OuterInductionPHI)), 376 m_Value(MatchedItCount))); 377 378 if ((IsAdd || IsAddTrunc) && MatchedItCount == InnerLimit) { 379 LLVM_DEBUG(dbgs() << "Use is optimisable\n"); 380 ValidOuterPHIUses.insert(MatchedMul); 381 FI.LinearIVUses.insert(U); 382 } else { 383 LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n"); 384 return false; 385 } 386 } 387 388 // Check that there are no uses of the outer IV other than the ones found 389 // as part of the pattern above. 390 for (User *U : FI.OuterInductionPHI->users()) { 391 if (U == FI.OuterIncrement) 392 continue; 393 394 auto IsValidOuterPHIUses = [&] (User *U) -> bool { 395 LLVM_DEBUG(dbgs() << "Found use of outer induction variable: "; U->dump()); 396 if (!ValidOuterPHIUses.count(U)) { 397 LLVM_DEBUG(dbgs() << "Did not match expected pattern, bailing\n"); 398 return false; 399 } 400 LLVM_DEBUG(dbgs() << "Use is optimisable\n"); 401 return true; 402 }; 403 404 if (auto *V = dyn_cast<TruncInst>(U)) { 405 for (auto *K : V->users()) { 406 if (!IsValidOuterPHIUses(K)) 407 return false; 408 } 409 continue; 410 } 411 412 if (!IsValidOuterPHIUses(U)) 413 return false; 414 } 415 416 LLVM_DEBUG(dbgs() << "checkIVUsers: OK\n"; 417 dbgs() << "Found " << FI.LinearIVUses.size() 418 << " value(s) that can be replaced:\n"; 419 for (Value *V : FI.LinearIVUses) { 420 dbgs() << " "; 421 V->dump(); 422 }); 423 return true; 424 } 425 426 // Return an OverflowResult dependant on if overflow of the multiplication of 427 // InnerLimit and OuterLimit can be assumed not to happen. 428 static OverflowResult checkOverflow(FlattenInfo &FI, DominatorTree *DT, 429 AssumptionCache *AC) { 430 Function *F = FI.OuterLoop->getHeader()->getParent(); 431 const DataLayout &DL = F->getParent()->getDataLayout(); 432 433 // For debugging/testing. 434 if (AssumeNoOverflow) 435 return OverflowResult::NeverOverflows; 436 437 // Check if the multiply could not overflow due to known ranges of the 438 // input values. 439 OverflowResult OR = computeOverflowForUnsignedMul( 440 FI.InnerLimit, FI.OuterLimit, DL, AC, 441 FI.OuterLoop->getLoopPreheader()->getTerminator(), DT); 442 if (OR != OverflowResult::MayOverflow) 443 return OR; 444 445 for (Value *V : FI.LinearIVUses) { 446 for (Value *U : V->users()) { 447 if (auto *GEP = dyn_cast<GetElementPtrInst>(U)) { 448 // The IV is used as the operand of a GEP, and the IV is at least as 449 // wide as the address space of the GEP. In this case, the GEP would 450 // wrap around the address space before the IV increment wraps, which 451 // would be UB. 452 if (GEP->isInBounds() && 453 V->getType()->getIntegerBitWidth() >= 454 DL.getPointerTypeSizeInBits(GEP->getType())) { 455 LLVM_DEBUG( 456 dbgs() << "use of linear IV would be UB if overflow occurred: "; 457 GEP->dump()); 458 return OverflowResult::NeverOverflows; 459 } 460 } 461 } 462 } 463 464 return OverflowResult::MayOverflow; 465 } 466 467 static bool CanFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, 468 ScalarEvolution *SE, AssumptionCache *AC, 469 const TargetTransformInfo *TTI) { 470 SmallPtrSet<Instruction *, 8> IterationInstructions; 471 if (!findLoopComponents(FI.InnerLoop, IterationInstructions, FI.InnerInductionPHI, 472 FI.InnerLimit, FI.InnerIncrement, FI.InnerBranch, SE)) 473 return false; 474 if (!findLoopComponents(FI.OuterLoop, IterationInstructions, FI.OuterInductionPHI, 475 FI.OuterLimit, FI.OuterIncrement, FI.OuterBranch, SE)) 476 return false; 477 478 // Both of the loop limit values must be invariant in the outer loop 479 // (non-instructions are all inherently invariant). 480 if (!FI.OuterLoop->isLoopInvariant(FI.InnerLimit)) { 481 LLVM_DEBUG(dbgs() << "inner loop limit not invariant\n"); 482 return false; 483 } 484 if (!FI.OuterLoop->isLoopInvariant(FI.OuterLimit)) { 485 LLVM_DEBUG(dbgs() << "outer loop limit not invariant\n"); 486 return false; 487 } 488 489 if (!checkPHIs(FI, TTI)) 490 return false; 491 492 // FIXME: it should be possible to handle different types correctly. 493 if (FI.InnerInductionPHI->getType() != FI.OuterInductionPHI->getType()) 494 return false; 495 496 if (!checkOuterLoopInsts(FI, IterationInstructions, TTI)) 497 return false; 498 499 // Find the values in the loop that can be replaced with the linearized 500 // induction variable, and check that there are no other uses of the inner 501 // or outer induction variable. If there were, we could still do this 502 // transformation, but we'd have to insert a div/mod to calculate the 503 // original IVs, so it wouldn't be profitable. 504 if (!checkIVUsers(FI)) 505 return false; 506 507 LLVM_DEBUG(dbgs() << "CanFlattenLoopPair: OK\n"); 508 return true; 509 } 510 511 static bool DoFlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, 512 ScalarEvolution *SE, AssumptionCache *AC, 513 const TargetTransformInfo *TTI) { 514 Function *F = FI.OuterLoop->getHeader()->getParent(); 515 LLVM_DEBUG(dbgs() << "Checks all passed, doing the transformation\n"); 516 { 517 using namespace ore; 518 OptimizationRemark Remark(DEBUG_TYPE, "Flattened", FI.InnerLoop->getStartLoc(), 519 FI.InnerLoop->getHeader()); 520 OptimizationRemarkEmitter ORE(F); 521 Remark << "Flattened into outer loop"; 522 ORE.emit(Remark); 523 } 524 525 Value *NewTripCount = 526 BinaryOperator::CreateMul(FI.InnerLimit, FI.OuterLimit, "flatten.tripcount", 527 FI.OuterLoop->getLoopPreheader()->getTerminator()); 528 LLVM_DEBUG(dbgs() << "Created new trip count in preheader: "; 529 NewTripCount->dump()); 530 531 // Fix up PHI nodes that take values from the inner loop back-edge, which 532 // we are about to remove. 533 FI.InnerInductionPHI->removeIncomingValue(FI.InnerLoop->getLoopLatch()); 534 535 // The old Phi will be optimised away later, but for now we can't leave 536 // leave it in an invalid state, so are updating them too. 537 for (PHINode *PHI : FI.InnerPHIsToTransform) 538 PHI->removeIncomingValue(FI.InnerLoop->getLoopLatch()); 539 540 // Modify the trip count of the outer loop to be the product of the two 541 // trip counts. 542 cast<User>(FI.OuterBranch->getCondition())->setOperand(1, NewTripCount); 543 544 // Replace the inner loop backedge with an unconditional branch to the exit. 545 BasicBlock *InnerExitBlock = FI.InnerLoop->getExitBlock(); 546 BasicBlock *InnerExitingBlock = FI.InnerLoop->getExitingBlock(); 547 InnerExitingBlock->getTerminator()->eraseFromParent(); 548 BranchInst::Create(InnerExitBlock, InnerExitingBlock); 549 DT->deleteEdge(InnerExitingBlock, FI.InnerLoop->getHeader()); 550 551 // Replace all uses of the polynomial calculated from the two induction 552 // variables with the one new one. 553 IRBuilder<> Builder(FI.OuterInductionPHI->getParent()->getTerminator()); 554 for (Value *V : FI.LinearIVUses) { 555 Value *OuterValue = FI.OuterInductionPHI; 556 if (FI.Widened) 557 OuterValue = Builder.CreateTrunc(FI.OuterInductionPHI, V->getType(), 558 "flatten.trunciv"); 559 560 LLVM_DEBUG(dbgs() << "Replacing: "; V->dump(); 561 dbgs() << "with: "; OuterValue->dump()); 562 V->replaceAllUsesWith(OuterValue); 563 } 564 565 // Tell LoopInfo, SCEV and the pass manager that the inner loop has been 566 // deleted, and any information that have about the outer loop invalidated. 567 SE->forgetLoop(FI.OuterLoop); 568 SE->forgetLoop(FI.InnerLoop); 569 LI->erase(FI.InnerLoop); 570 return true; 571 } 572 573 static bool CanWidenIV(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, 574 ScalarEvolution *SE, AssumptionCache *AC, 575 const TargetTransformInfo *TTI) { 576 if (!WidenIV) { 577 LLVM_DEBUG(dbgs() << "Widening the IVs is disabled\n"); 578 return false; 579 } 580 581 LLVM_DEBUG(dbgs() << "Try widening the IVs\n"); 582 Module *M = FI.InnerLoop->getHeader()->getParent()->getParent(); 583 auto &DL = M->getDataLayout(); 584 auto *InnerType = FI.InnerInductionPHI->getType(); 585 auto *OuterType = FI.OuterInductionPHI->getType(); 586 unsigned MaxLegalSize = DL.getLargestLegalIntTypeSizeInBits(); 587 auto *MaxLegalType = DL.getLargestLegalIntType(M->getContext()); 588 589 // If both induction types are less than the maximum legal integer width, 590 // promote both to the widest type available so we know calculating 591 // (OuterLimit * InnerLimit) as the new trip count is safe. 592 if (InnerType != OuterType || 593 InnerType->getScalarSizeInBits() >= MaxLegalSize || 594 MaxLegalType->getScalarSizeInBits() < InnerType->getScalarSizeInBits() * 2) { 595 LLVM_DEBUG(dbgs() << "Can't widen the IV\n"); 596 return false; 597 } 598 599 SCEVExpander Rewriter(*SE, DL, "loopflatten"); 600 SmallVector<WideIVInfo, 2> WideIVs; 601 SmallVector<WeakTrackingVH, 4> DeadInsts; 602 WideIVs.push_back( {FI.InnerInductionPHI, MaxLegalType, false }); 603 WideIVs.push_back( {FI.OuterInductionPHI, MaxLegalType, false }); 604 unsigned ElimExt; 605 unsigned Widened; 606 607 for (unsigned i = 0; i < WideIVs.size(); i++) { 608 PHINode *WidePhi = createWideIV(WideIVs[i], LI, SE, Rewriter, DT, DeadInsts, 609 ElimExt, Widened, true /* HasGuards */, 610 true /* UsePostIncrementRanges */); 611 if (!WidePhi) 612 return false; 613 LLVM_DEBUG(dbgs() << "Created wide phi: "; WidePhi->dump()); 614 LLVM_DEBUG(dbgs() << "Deleting old phi: "; WideIVs[i].NarrowIV->dump()); 615 RecursivelyDeleteDeadPHINode(WideIVs[i].NarrowIV); 616 } 617 // After widening, rediscover all the loop components. 618 assert(Widened && "Widenend IV expected"); 619 FI.Widened = true; 620 return CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI); 621 } 622 623 static bool FlattenLoopPair(FlattenInfo &FI, DominatorTree *DT, LoopInfo *LI, 624 ScalarEvolution *SE, AssumptionCache *AC, 625 const TargetTransformInfo *TTI) { 626 LLVM_DEBUG( 627 dbgs() << "Loop flattening running on outer loop " 628 << FI.OuterLoop->getHeader()->getName() << " and inner loop " 629 << FI.InnerLoop->getHeader()->getName() << " in " 630 << FI.OuterLoop->getHeader()->getParent()->getName() << "\n"); 631 632 if (!CanFlattenLoopPair(FI, DT, LI, SE, AC, TTI)) 633 return false; 634 635 // Check if we can widen the induction variables to avoid overflow checks. 636 if (CanWidenIV(FI, DT, LI, SE, AC, TTI)) 637 return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI); 638 639 // Check if the new iteration variable might overflow. In this case, we 640 // need to version the loop, and select the original version at runtime if 641 // the iteration space is too large. 642 // TODO: We currently don't version the loop. 643 OverflowResult OR = checkOverflow(FI, DT, AC); 644 if (OR == OverflowResult::AlwaysOverflowsHigh || 645 OR == OverflowResult::AlwaysOverflowsLow) { 646 LLVM_DEBUG(dbgs() << "Multiply would always overflow, so not profitable\n"); 647 return false; 648 } else if (OR == OverflowResult::MayOverflow) { 649 LLVM_DEBUG(dbgs() << "Multiply might overflow, not flattening\n"); 650 return false; 651 } 652 653 LLVM_DEBUG(dbgs() << "Multiply cannot overflow, modifying loop in-place\n"); 654 return DoFlattenLoopPair(FI, DT, LI, SE, AC, TTI); 655 } 656 657 bool Flatten(DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, 658 AssumptionCache *AC, TargetTransformInfo *TTI) { 659 bool Changed = false; 660 for (auto *InnerLoop : LI->getLoopsInPreorder()) { 661 auto *OuterLoop = InnerLoop->getParentLoop(); 662 if (!OuterLoop) 663 continue; 664 FlattenInfo FI(OuterLoop, InnerLoop); 665 Changed |= FlattenLoopPair(FI, DT, LI, SE, AC, TTI); 666 } 667 return Changed; 668 } 669 670 PreservedAnalyses LoopFlattenPass::run(Function &F, 671 FunctionAnalysisManager &AM) { 672 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); 673 auto *LI = &AM.getResult<LoopAnalysis>(F); 674 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F); 675 auto *AC = &AM.getResult<AssumptionAnalysis>(F); 676 auto *TTI = &AM.getResult<TargetIRAnalysis>(F); 677 678 if (!Flatten(DT, LI, SE, AC, TTI)) 679 return PreservedAnalyses::all(); 680 681 PreservedAnalyses PA; 682 PA.preserveSet<CFGAnalyses>(); 683 return PA; 684 } 685 686 namespace { 687 class LoopFlattenLegacyPass : public FunctionPass { 688 public: 689 static char ID; // Pass ID, replacement for typeid 690 LoopFlattenLegacyPass() : FunctionPass(ID) { 691 initializeLoopFlattenLegacyPassPass(*PassRegistry::getPassRegistry()); 692 } 693 694 // Possibly flatten loop L into its child. 695 bool runOnFunction(Function &F) override; 696 697 void getAnalysisUsage(AnalysisUsage &AU) const override { 698 getLoopAnalysisUsage(AU); 699 AU.addRequired<TargetTransformInfoWrapperPass>(); 700 AU.addPreserved<TargetTransformInfoWrapperPass>(); 701 AU.addRequired<AssumptionCacheTracker>(); 702 AU.addPreserved<AssumptionCacheTracker>(); 703 } 704 }; 705 } // namespace 706 707 char LoopFlattenLegacyPass::ID = 0; 708 INITIALIZE_PASS_BEGIN(LoopFlattenLegacyPass, "loop-flatten", "Flattens loops", 709 false, false) 710 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 711 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 712 INITIALIZE_PASS_END(LoopFlattenLegacyPass, "loop-flatten", "Flattens loops", 713 false, false) 714 715 FunctionPass *llvm::createLoopFlattenPass() { return new LoopFlattenLegacyPass(); } 716 717 bool LoopFlattenLegacyPass::runOnFunction(Function &F) { 718 ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 719 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 720 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 721 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr; 722 auto &TTIP = getAnalysis<TargetTransformInfoWrapperPass>(); 723 auto *TTI = &TTIP.getTTI(F); 724 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 725 return Flatten(DT, LI, SE, AC, TTI); 726 } 727