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