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