1 //===- LoopPeel.cpp -------------------------------------------------------===// 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 // Loop Peeling Utilities. 10 //===----------------------------------------------------------------------===// 11 12 #include "llvm/Transforms/Utils/LoopPeel.h" 13 #include "llvm/ADT/DenseMap.h" 14 #include "llvm/ADT/Optional.h" 15 #include "llvm/ADT/SmallVector.h" 16 #include "llvm/ADT/Statistic.h" 17 #include "llvm/Analysis/Loads.h" 18 #include "llvm/Analysis/LoopInfo.h" 19 #include "llvm/Analysis/LoopIterator.h" 20 #include "llvm/Analysis/ScalarEvolution.h" 21 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 22 #include "llvm/Analysis/TargetTransformInfo.h" 23 #include "llvm/IR/BasicBlock.h" 24 #include "llvm/IR/Dominators.h" 25 #include "llvm/IR/Function.h" 26 #include "llvm/IR/InstrTypes.h" 27 #include "llvm/IR/Instruction.h" 28 #include "llvm/IR/Instructions.h" 29 #include "llvm/IR/LLVMContext.h" 30 #include "llvm/IR/MDBuilder.h" 31 #include "llvm/IR/PatternMatch.h" 32 #include "llvm/IR/ProfDataUtils.h" 33 #include "llvm/Support/Casting.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 38 #include "llvm/Transforms/Utils/Cloning.h" 39 #include "llvm/Transforms/Utils/LoopSimplify.h" 40 #include "llvm/Transforms/Utils/LoopUtils.h" 41 #include "llvm/Transforms/Utils/ValueMapper.h" 42 #include <algorithm> 43 #include <cassert> 44 #include <cstdint> 45 #include <optional> 46 47 using namespace llvm; 48 using namespace llvm::PatternMatch; 49 50 #define DEBUG_TYPE "loop-peel" 51 52 STATISTIC(NumPeeled, "Number of loops peeled"); 53 54 static cl::opt<unsigned> UnrollPeelCount( 55 "unroll-peel-count", cl::Hidden, 56 cl::desc("Set the unroll peeling count, for testing purposes")); 57 58 static cl::opt<bool> 59 UnrollAllowPeeling("unroll-allow-peeling", cl::init(true), cl::Hidden, 60 cl::desc("Allows loops to be peeled when the dynamic " 61 "trip count is known to be low.")); 62 63 static cl::opt<bool> 64 UnrollAllowLoopNestsPeeling("unroll-allow-loop-nests-peeling", 65 cl::init(false), cl::Hidden, 66 cl::desc("Allows loop nests to be peeled.")); 67 68 static cl::opt<unsigned> UnrollPeelMaxCount( 69 "unroll-peel-max-count", cl::init(7), cl::Hidden, 70 cl::desc("Max average trip count which will cause loop peeling.")); 71 72 static cl::opt<unsigned> UnrollForcePeelCount( 73 "unroll-force-peel-count", cl::init(0), cl::Hidden, 74 cl::desc("Force a peel count regardless of profiling information.")); 75 76 static cl::opt<bool> DisableAdvancedPeeling( 77 "disable-advanced-peeling", cl::init(false), cl::Hidden, 78 cl::desc( 79 "Disable advance peeling. Issues for convergent targets (D134803).")); 80 81 static const char *PeeledCountMetaData = "llvm.loop.peeled.count"; 82 83 // Check whether we are capable of peeling this loop. 84 bool llvm::canPeel(const Loop *L) { 85 // Make sure the loop is in simplified form 86 if (!L->isLoopSimplifyForm()) 87 return false; 88 if (!DisableAdvancedPeeling) 89 return true; 90 91 SmallVector<BasicBlock *, 4> Exits; 92 L->getUniqueNonLatchExitBlocks(Exits); 93 // The latch must either be the only exiting block or all non-latch exit 94 // blocks have either a deopt or unreachable terminator or compose a chain of 95 // blocks where the last one is either deopt or unreachable terminated. Both 96 // deopt and unreachable terminators are a strong indication they are not 97 // taken. Note that this is a profitability check, not a legality check. Also 98 // note that LoopPeeling currently can only update the branch weights of latch 99 // blocks and branch weights to blocks with deopt or unreachable do not need 100 // updating. 101 return llvm::all_of(Exits, IsBlockFollowedByDeoptOrUnreachable); 102 } 103 104 namespace { 105 106 // As a loop is peeled, it may be the case that Phi nodes become 107 // loop-invariant (ie, known because there is only one choice). 108 // For example, consider the following function: 109 // void g(int); 110 // void binary() { 111 // int x = 0; 112 // int y = 0; 113 // int a = 0; 114 // for(int i = 0; i <100000; ++i) { 115 // g(x); 116 // x = y; 117 // g(a); 118 // y = a + 1; 119 // a = 5; 120 // } 121 // } 122 // Peeling 3 iterations is beneficial because the values for x, y and a 123 // become known. The IR for this loop looks something like the following: 124 // 125 // %i = phi i32 [ 0, %entry ], [ %inc, %if.end ] 126 // %a = phi i32 [ 0, %entry ], [ 5, %if.end ] 127 // %y = phi i32 [ 0, %entry ], [ %add, %if.end ] 128 // %x = phi i32 [ 0, %entry ], [ %y, %if.end ] 129 // ... 130 // tail call void @_Z1gi(i32 signext %x) 131 // tail call void @_Z1gi(i32 signext %a) 132 // %add = add nuw nsw i32 %a, 1 133 // %inc = add nuw nsw i32 %i, 1 134 // %exitcond = icmp eq i32 %inc, 100000 135 // br i1 %exitcond, label %for.cond.cleanup, label %for.body 136 // 137 // The arguments for the calls to g will become known after 3 iterations 138 // of the loop, because the phi nodes values become known after 3 iterations 139 // of the loop (ie, they are known on the 4th iteration, so peel 3 iterations). 140 // The first iteration has g(0), g(0); the second has g(0), g(5); the 141 // third has g(1), g(5) and the fourth (and all subsequent) have g(6), g(5). 142 // Now consider the phi nodes: 143 // %a is a phi with constants so it is determined after iteration 1. 144 // %y is a phi based on a constant and %a so it is determined on 145 // the iteration after %a is determined, so iteration 2. 146 // %x is a phi based on a constant and %y so it is determined on 147 // the iteration after %y, so iteration 3. 148 // %i is based on itself (and is an induction variable) so it is 149 // never determined. 150 // This means that peeling off 3 iterations will result in being able to 151 // remove the phi nodes for %a, %y, and %x. The arguments for the 152 // corresponding calls to g are determined and the code for computing 153 // x, y, and a can be removed. 154 // 155 // The PhiAnalyzer class calculates how many times a loop should be 156 // peeled based on the above analysis of the phi nodes in the loop while 157 // respecting the maximum specified. 158 class PhiAnalyzer { 159 public: 160 PhiAnalyzer(const Loop &L, unsigned MaxIterations); 161 162 // Calculate the sufficient minimum number of iterations of the loop to peel 163 // such that phi instructions become determined (subject to allowable limits) 164 Optional<unsigned> calculateIterationsToPeel(); 165 166 protected: 167 using PeelCounter = std::optional<unsigned>; 168 const PeelCounter Unknown = std::nullopt; 169 170 // Add 1 respecting Unknown and return Unknown if result over MaxIterations 171 PeelCounter addOne(PeelCounter PC) const { 172 if (PC == Unknown) 173 return Unknown; 174 return (*PC + 1 <= MaxIterations) ? PeelCounter{*PC + 1} : Unknown; 175 } 176 177 // Calculate the number of iterations after which the given value 178 // becomes an invariant. 179 PeelCounter calculate(const Value &); 180 181 const Loop &L; 182 const unsigned MaxIterations; 183 184 // Map of Values to number of iterations to invariance 185 SmallDenseMap<const Value *, PeelCounter> IterationsToInvariance; 186 }; 187 188 PhiAnalyzer::PhiAnalyzer(const Loop &L, unsigned MaxIterations) 189 : L(L), MaxIterations(MaxIterations) { 190 assert(canPeel(&L) && "loop is not suitable for peeling"); 191 assert(MaxIterations > 0 && "no peeling is allowed?"); 192 } 193 194 // This function calculates the number of iterations after which the value 195 // becomes an invariant. The pre-calculated values are memorized in a map. 196 // N.B. This number will be Unknown or <= MaxIterations. 197 // The function is calculated according to the following definition: 198 // Given %x = phi <Inputs from above the loop>, ..., [%y, %back.edge]. 199 // F(%x) = G(%y) + 1 (N.B. [MaxIterations | Unknown] + 1 => Unknown) 200 // G(%y) = 0 if %y is a loop invariant 201 // G(%y) = G(%BackEdgeValue) if %y is a phi in the header block 202 // G(%y) = TODO: if %y is an expression based on phis and loop invariants 203 // The example looks like: 204 // %x = phi(0, %a) <-- becomes invariant starting from 3rd iteration. 205 // %y = phi(0, 5) 206 // %a = %y + 1 207 // G(%y) = Unknown otherwise (including phi not in header block) 208 PhiAnalyzer::PeelCounter PhiAnalyzer::calculate(const Value &V) { 209 // If we already know the answer, take it from the map. 210 auto I = IterationsToInvariance.find(&V); 211 if (I != IterationsToInvariance.end()) 212 return I->second; 213 214 // Place Unknown to map to avoid infinite recursion. Such 215 // cycles can never stop on an invariant. 216 IterationsToInvariance[&V] = Unknown; 217 218 if (L.isLoopInvariant(&V)) 219 // Loop invariant so known at start. 220 return (IterationsToInvariance[&V] = 0); 221 if (const PHINode *Phi = dyn_cast<PHINode>(&V)) { 222 if (Phi->getParent() != L.getHeader()) { 223 // Phi is not in header block so Unknown. 224 assert(IterationsToInvariance[&V] == Unknown && "unexpected value saved"); 225 return Unknown; 226 } 227 // We need to analyze the input from the back edge and add 1. 228 Value *Input = Phi->getIncomingValueForBlock(L.getLoopLatch()); 229 PeelCounter Iterations = calculate(*Input); 230 assert(IterationsToInvariance[Input] == Iterations && 231 "unexpected value saved"); 232 return (IterationsToInvariance[Phi] = addOne(Iterations)); 233 } 234 if (const Instruction *I = dyn_cast<Instruction>(&V)) { 235 if (isa<CmpInst>(I) || I->isBinaryOp()) { 236 // Binary instructions get the max of the operands. 237 PeelCounter LHS = calculate(*I->getOperand(0)); 238 if (LHS == Unknown) 239 return Unknown; 240 PeelCounter RHS = calculate(*I->getOperand(1)); 241 if (RHS == Unknown) 242 return Unknown; 243 return (IterationsToInvariance[I] = {std::max(*LHS, *RHS)}); 244 } 245 if (I->isCast()) 246 // Cast instructions get the value of the operand. 247 return (IterationsToInvariance[I] = calculate(*I->getOperand(0))); 248 } 249 // TODO: handle more expressions 250 251 // Everything else is Unknown. 252 assert(IterationsToInvariance[&V] == Unknown && "unexpected value saved"); 253 return Unknown; 254 } 255 256 Optional<unsigned> PhiAnalyzer::calculateIterationsToPeel() { 257 unsigned Iterations = 0; 258 for (auto &PHI : L.getHeader()->phis()) { 259 PeelCounter ToInvariance = calculate(PHI); 260 if (ToInvariance != Unknown) { 261 assert(*ToInvariance <= MaxIterations && "bad result in phi analysis"); 262 Iterations = std::max(Iterations, *ToInvariance); 263 if (Iterations == MaxIterations) 264 break; 265 } 266 } 267 assert((Iterations <= MaxIterations) && "bad result in phi analysis"); 268 return Iterations ? Optional<unsigned>(Iterations) : std::nullopt; 269 } 270 271 } // unnamed namespace 272 273 // Try to find any invariant memory reads that will become dereferenceable in 274 // the remainder loop after peeling. The load must also be used (transitively) 275 // by an exit condition. Returns the number of iterations to peel off (at the 276 // moment either 0 or 1). 277 static unsigned peelToTurnInvariantLoadsDerefencebale(Loop &L, 278 DominatorTree &DT, 279 AssumptionCache *AC) { 280 // Skip loops with a single exiting block, because there should be no benefit 281 // for the heuristic below. 282 if (L.getExitingBlock()) 283 return 0; 284 285 // All non-latch exit blocks must have an UnreachableInst terminator. 286 // Otherwise the heuristic below may not be profitable. 287 SmallVector<BasicBlock *, 4> Exits; 288 L.getUniqueNonLatchExitBlocks(Exits); 289 if (any_of(Exits, [](const BasicBlock *BB) { 290 return !isa<UnreachableInst>(BB->getTerminator()); 291 })) 292 return 0; 293 294 // Now look for invariant loads that dominate the latch and are not known to 295 // be dereferenceable. If there are such loads and no writes, they will become 296 // dereferenceable in the loop if the first iteration is peeled off. Also 297 // collect the set of instructions controlled by such loads. Only peel if an 298 // exit condition uses (transitively) such a load. 299 BasicBlock *Header = L.getHeader(); 300 BasicBlock *Latch = L.getLoopLatch(); 301 SmallPtrSet<Value *, 8> LoadUsers; 302 const DataLayout &DL = L.getHeader()->getModule()->getDataLayout(); 303 for (BasicBlock *BB : L.blocks()) { 304 for (Instruction &I : *BB) { 305 if (I.mayWriteToMemory()) 306 return 0; 307 308 auto Iter = LoadUsers.find(&I); 309 if (Iter != LoadUsers.end()) { 310 for (Value *U : I.users()) 311 LoadUsers.insert(U); 312 } 313 // Do not look for reads in the header; they can already be hoisted 314 // without peeling. 315 if (BB == Header) 316 continue; 317 if (auto *LI = dyn_cast<LoadInst>(&I)) { 318 Value *Ptr = LI->getPointerOperand(); 319 if (DT.dominates(BB, Latch) && L.isLoopInvariant(Ptr) && 320 !isDereferenceablePointer(Ptr, LI->getType(), DL, LI, AC, &DT)) 321 for (Value *U : I.users()) 322 LoadUsers.insert(U); 323 } 324 } 325 } 326 SmallVector<BasicBlock *> ExitingBlocks; 327 L.getExitingBlocks(ExitingBlocks); 328 if (any_of(ExitingBlocks, [&LoadUsers](BasicBlock *Exiting) { 329 return LoadUsers.contains(Exiting->getTerminator()); 330 })) 331 return 1; 332 return 0; 333 } 334 335 // Return the number of iterations to peel off that make conditions in the 336 // body true/false. For example, if we peel 2 iterations off the loop below, 337 // the condition i < 2 can be evaluated at compile time. 338 // for (i = 0; i < n; i++) 339 // if (i < 2) 340 // .. 341 // else 342 // .. 343 // } 344 static unsigned countToEliminateCompares(Loop &L, unsigned MaxPeelCount, 345 ScalarEvolution &SE) { 346 assert(L.isLoopSimplifyForm() && "Loop needs to be in loop simplify form"); 347 unsigned DesiredPeelCount = 0; 348 349 for (auto *BB : L.blocks()) { 350 auto *BI = dyn_cast<BranchInst>(BB->getTerminator()); 351 if (!BI || BI->isUnconditional()) 352 continue; 353 354 // Ignore loop exit condition. 355 if (L.getLoopLatch() == BB) 356 continue; 357 358 Value *Condition = BI->getCondition(); 359 Value *LeftVal, *RightVal; 360 CmpInst::Predicate Pred; 361 if (!match(Condition, m_ICmp(Pred, m_Value(LeftVal), m_Value(RightVal)))) 362 continue; 363 364 const SCEV *LeftSCEV = SE.getSCEV(LeftVal); 365 const SCEV *RightSCEV = SE.getSCEV(RightVal); 366 367 // Do not consider predicates that are known to be true or false 368 // independently of the loop iteration. 369 if (SE.evaluatePredicate(Pred, LeftSCEV, RightSCEV)) 370 continue; 371 372 // Check if we have a condition with one AddRec and one non AddRec 373 // expression. Normalize LeftSCEV to be the AddRec. 374 if (!isa<SCEVAddRecExpr>(LeftSCEV)) { 375 if (isa<SCEVAddRecExpr>(RightSCEV)) { 376 std::swap(LeftSCEV, RightSCEV); 377 Pred = ICmpInst::getSwappedPredicate(Pred); 378 } else 379 continue; 380 } 381 382 const SCEVAddRecExpr *LeftAR = cast<SCEVAddRecExpr>(LeftSCEV); 383 384 // Avoid huge SCEV computations in the loop below, make sure we only 385 // consider AddRecs of the loop we are trying to peel. 386 if (!LeftAR->isAffine() || LeftAR->getLoop() != &L) 387 continue; 388 if (!(ICmpInst::isEquality(Pred) && LeftAR->hasNoSelfWrap()) && 389 !SE.getMonotonicPredicateType(LeftAR, Pred)) 390 continue; 391 392 // Check if extending the current DesiredPeelCount lets us evaluate Pred 393 // or !Pred in the loop body statically. 394 unsigned NewPeelCount = DesiredPeelCount; 395 396 const SCEV *IterVal = LeftAR->evaluateAtIteration( 397 SE.getConstant(LeftSCEV->getType(), NewPeelCount), SE); 398 399 // If the original condition is not known, get the negated predicate 400 // (which holds on the else branch) and check if it is known. This allows 401 // us to peel of iterations that make the original condition false. 402 if (!SE.isKnownPredicate(Pred, IterVal, RightSCEV)) 403 Pred = ICmpInst::getInversePredicate(Pred); 404 405 const SCEV *Step = LeftAR->getStepRecurrence(SE); 406 const SCEV *NextIterVal = SE.getAddExpr(IterVal, Step); 407 auto PeelOneMoreIteration = [&IterVal, &NextIterVal, &SE, Step, 408 &NewPeelCount]() { 409 IterVal = NextIterVal; 410 NextIterVal = SE.getAddExpr(IterVal, Step); 411 NewPeelCount++; 412 }; 413 414 auto CanPeelOneMoreIteration = [&NewPeelCount, &MaxPeelCount]() { 415 return NewPeelCount < MaxPeelCount; 416 }; 417 418 while (CanPeelOneMoreIteration() && 419 SE.isKnownPredicate(Pred, IterVal, RightSCEV)) 420 PeelOneMoreIteration(); 421 422 // With *that* peel count, does the predicate !Pred become known in the 423 // first iteration of the loop body after peeling? 424 if (!SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), IterVal, 425 RightSCEV)) 426 continue; // If not, give up. 427 428 // However, for equality comparisons, that isn't always sufficient to 429 // eliminate the comparsion in loop body, we may need to peel one more 430 // iteration. See if that makes !Pred become unknown again. 431 if (ICmpInst::isEquality(Pred) && 432 !SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), NextIterVal, 433 RightSCEV) && 434 !SE.isKnownPredicate(Pred, IterVal, RightSCEV) && 435 SE.isKnownPredicate(Pred, NextIterVal, RightSCEV)) { 436 if (!CanPeelOneMoreIteration()) 437 continue; // Need to peel one more iteration, but can't. Give up. 438 PeelOneMoreIteration(); // Great! 439 } 440 441 DesiredPeelCount = std::max(DesiredPeelCount, NewPeelCount); 442 } 443 444 return DesiredPeelCount; 445 } 446 447 /// This "heuristic" exactly matches implicit behavior which used to exist 448 /// inside getLoopEstimatedTripCount. It was added here to keep an 449 /// improvement inside that API from causing peeling to become more aggressive. 450 /// This should probably be removed. 451 static bool violatesLegacyMultiExitLoopCheck(Loop *L) { 452 BasicBlock *Latch = L->getLoopLatch(); 453 if (!Latch) 454 return true; 455 456 BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator()); 457 if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch)) 458 return true; 459 460 assert((LatchBR->getSuccessor(0) == L->getHeader() || 461 LatchBR->getSuccessor(1) == L->getHeader()) && 462 "At least one edge out of the latch must go to the header"); 463 464 SmallVector<BasicBlock *, 4> ExitBlocks; 465 L->getUniqueNonLatchExitBlocks(ExitBlocks); 466 return any_of(ExitBlocks, [](const BasicBlock *EB) { 467 return !EB->getTerminatingDeoptimizeCall(); 468 }); 469 } 470 471 472 // Return the number of iterations we want to peel off. 473 void llvm::computePeelCount(Loop *L, unsigned LoopSize, 474 TargetTransformInfo::PeelingPreferences &PP, 475 unsigned TripCount, DominatorTree &DT, 476 ScalarEvolution &SE, AssumptionCache *AC, 477 unsigned Threshold) { 478 assert(LoopSize > 0 && "Zero loop size is not allowed!"); 479 // Save the PP.PeelCount value set by the target in 480 // TTI.getPeelingPreferences or by the flag -unroll-peel-count. 481 unsigned TargetPeelCount = PP.PeelCount; 482 PP.PeelCount = 0; 483 if (!canPeel(L)) 484 return; 485 486 // Only try to peel innermost loops by default. 487 // The constraint can be relaxed by the target in TTI.getPeelingPreferences 488 // or by the flag -unroll-allow-loop-nests-peeling. 489 if (!PP.AllowLoopNestsPeeling && !L->isInnermost()) 490 return; 491 492 // If the user provided a peel count, use that. 493 bool UserPeelCount = UnrollForcePeelCount.getNumOccurrences() > 0; 494 if (UserPeelCount) { 495 LLVM_DEBUG(dbgs() << "Force-peeling first " << UnrollForcePeelCount 496 << " iterations.\n"); 497 PP.PeelCount = UnrollForcePeelCount; 498 PP.PeelProfiledIterations = true; 499 return; 500 } 501 502 // Skip peeling if it's disabled. 503 if (!PP.AllowPeeling) 504 return; 505 506 // Check that we can peel at least one iteration. 507 if (2 * LoopSize > Threshold) 508 return; 509 510 unsigned AlreadyPeeled = 0; 511 if (auto Peeled = getOptionalIntLoopAttribute(L, PeeledCountMetaData)) 512 AlreadyPeeled = *Peeled; 513 // Stop if we already peeled off the maximum number of iterations. 514 if (AlreadyPeeled >= UnrollPeelMaxCount) 515 return; 516 517 // Pay respect to limitations implied by loop size and the max peel count. 518 unsigned MaxPeelCount = UnrollPeelMaxCount; 519 MaxPeelCount = std::min(MaxPeelCount, Threshold / LoopSize - 1); 520 521 // Start the max computation with the PP.PeelCount value set by the target 522 // in TTI.getPeelingPreferences or by the flag -unroll-peel-count. 523 unsigned DesiredPeelCount = TargetPeelCount; 524 525 // Here we try to get rid of Phis which become invariants after 1, 2, ..., N 526 // iterations of the loop. For this we compute the number for iterations after 527 // which every Phi is guaranteed to become an invariant, and try to peel the 528 // maximum number of iterations among these values, thus turning all those 529 // Phis into invariants. 530 if (MaxPeelCount > DesiredPeelCount) { 531 // Check how many iterations are useful for resolving Phis 532 auto NumPeels = PhiAnalyzer(*L, MaxPeelCount).calculateIterationsToPeel(); 533 if (NumPeels) 534 DesiredPeelCount = std::max(DesiredPeelCount, *NumPeels); 535 } 536 537 DesiredPeelCount = std::max(DesiredPeelCount, 538 countToEliminateCompares(*L, MaxPeelCount, SE)); 539 540 if (DesiredPeelCount == 0) 541 DesiredPeelCount = peelToTurnInvariantLoadsDerefencebale(*L, DT, AC); 542 543 if (DesiredPeelCount > 0) { 544 DesiredPeelCount = std::min(DesiredPeelCount, MaxPeelCount); 545 // Consider max peel count limitation. 546 assert(DesiredPeelCount > 0 && "Wrong loop size estimation?"); 547 if (DesiredPeelCount + AlreadyPeeled <= UnrollPeelMaxCount) { 548 LLVM_DEBUG(dbgs() << "Peel " << DesiredPeelCount 549 << " iteration(s) to turn" 550 << " some Phis into invariants.\n"); 551 PP.PeelCount = DesiredPeelCount; 552 PP.PeelProfiledIterations = false; 553 return; 554 } 555 } 556 557 // Bail if we know the statically calculated trip count. 558 // In this case we rather prefer partial unrolling. 559 if (TripCount) 560 return; 561 562 // Do not apply profile base peeling if it is disabled. 563 if (!PP.PeelProfiledIterations) 564 return; 565 // If we don't know the trip count, but have reason to believe the average 566 // trip count is low, peeling should be beneficial, since we will usually 567 // hit the peeled section. 568 // We only do this in the presence of profile information, since otherwise 569 // our estimates of the trip count are not reliable enough. 570 if (L->getHeader()->getParent()->hasProfileData()) { 571 if (violatesLegacyMultiExitLoopCheck(L)) 572 return; 573 Optional<unsigned> EstimatedTripCount = getLoopEstimatedTripCount(L); 574 if (!EstimatedTripCount) 575 return; 576 577 LLVM_DEBUG(dbgs() << "Profile-based estimated trip count is " 578 << *EstimatedTripCount << "\n"); 579 580 if (*EstimatedTripCount) { 581 if (*EstimatedTripCount + AlreadyPeeled <= MaxPeelCount) { 582 unsigned PeelCount = *EstimatedTripCount; 583 LLVM_DEBUG(dbgs() << "Peeling first " << PeelCount << " iterations.\n"); 584 PP.PeelCount = PeelCount; 585 return; 586 } 587 LLVM_DEBUG(dbgs() << "Already peel count: " << AlreadyPeeled << "\n"); 588 LLVM_DEBUG(dbgs() << "Max peel count: " << UnrollPeelMaxCount << "\n"); 589 LLVM_DEBUG(dbgs() << "Loop cost: " << LoopSize << "\n"); 590 LLVM_DEBUG(dbgs() << "Max peel cost: " << Threshold << "\n"); 591 LLVM_DEBUG(dbgs() << "Max peel count by cost: " 592 << (Threshold / LoopSize - 1) << "\n"); 593 } 594 } 595 } 596 597 struct WeightInfo { 598 // Weights for current iteration. 599 SmallVector<uint32_t> Weights; 600 // Weights to subtract after each iteration. 601 const SmallVector<uint32_t> SubWeights; 602 }; 603 604 /// Update the branch weights of an exiting block of a peeled-off loop 605 /// iteration. 606 /// Let F is a weight of the edge to continue (fallthrough) into the loop. 607 /// Let E is a weight of the edge to an exit. 608 /// F/(F+E) is a probability to go to loop and E/(F+E) is a probability to 609 /// go to exit. 610 /// Then, Estimated ExitCount = F / E. 611 /// For I-th (counting from 0) peeled off iteration we set the the weights for 612 /// the peeled exit as (EC - I, 1). It gives us reasonable distribution, 613 /// The probability to go to exit 1/(EC-I) increases. At the same time 614 /// the estimated exit count in the remainder loop reduces by I. 615 /// To avoid dealing with division rounding we can just multiple both part 616 /// of weights to E and use weight as (F - I * E, E). 617 static void updateBranchWeights(Instruction *Term, WeightInfo &Info) { 618 MDBuilder MDB(Term->getContext()); 619 Term->setMetadata(LLVMContext::MD_prof, 620 MDB.createBranchWeights(Info.Weights)); 621 for (auto [Idx, SubWeight] : enumerate(Info.SubWeights)) 622 if (SubWeight != 0) 623 Info.Weights[Idx] = Info.Weights[Idx] > SubWeight 624 ? Info.Weights[Idx] - SubWeight 625 : 1; 626 } 627 628 /// Initialize the weights for all exiting blocks. 629 static void initBranchWeights(DenseMap<Instruction *, WeightInfo> &WeightInfos, 630 Loop *L) { 631 SmallVector<BasicBlock *> ExitingBlocks; 632 L->getExitingBlocks(ExitingBlocks); 633 for (BasicBlock *ExitingBlock : ExitingBlocks) { 634 Instruction *Term = ExitingBlock->getTerminator(); 635 SmallVector<uint32_t> Weights; 636 if (!extractBranchWeights(*Term, Weights)) 637 continue; 638 639 // See the comment on updateBranchWeights() for an explanation of what we 640 // do here. 641 uint32_t FallThroughWeights = 0; 642 uint32_t ExitWeights = 0; 643 for (auto [Succ, Weight] : zip(successors(Term), Weights)) { 644 if (L->contains(Succ)) 645 FallThroughWeights += Weight; 646 else 647 ExitWeights += Weight; 648 } 649 650 // Don't try to update weights for degenerate case. 651 if (FallThroughWeights == 0) 652 continue; 653 654 SmallVector<uint32_t> SubWeights; 655 for (auto [Succ, Weight] : zip(successors(Term), Weights)) { 656 if (!L->contains(Succ)) { 657 // Exit weights stay the same. 658 SubWeights.push_back(0); 659 continue; 660 } 661 662 // Subtract exit weights on each iteration, distributed across all 663 // fallthrough edges. 664 double W = (double)Weight / (double)FallThroughWeights; 665 SubWeights.push_back((uint32_t)(ExitWeights * W)); 666 } 667 668 WeightInfos.insert({Term, {std::move(Weights), std::move(SubWeights)}}); 669 } 670 } 671 672 /// Update the weights of original exiting block after peeling off all 673 /// iterations. 674 static void fixupBranchWeights(Instruction *Term, const WeightInfo &Info) { 675 MDBuilder MDB(Term->getContext()); 676 Term->setMetadata(LLVMContext::MD_prof, 677 MDB.createBranchWeights(Info.Weights)); 678 } 679 680 /// Clones the body of the loop L, putting it between \p InsertTop and \p 681 /// InsertBot. 682 /// \param IterNumber The serial number of the iteration currently being 683 /// peeled off. 684 /// \param ExitEdges The exit edges of the original loop. 685 /// \param[out] NewBlocks A list of the blocks in the newly created clone 686 /// \param[out] VMap The value map between the loop and the new clone. 687 /// \param LoopBlocks A helper for DFS-traversal of the loop. 688 /// \param LVMap A value-map that maps instructions from the original loop to 689 /// instructions in the last peeled-off iteration. 690 static void cloneLoopBlocks( 691 Loop *L, unsigned IterNumber, BasicBlock *InsertTop, BasicBlock *InsertBot, 692 SmallVectorImpl<std::pair<BasicBlock *, BasicBlock *>> &ExitEdges, 693 SmallVectorImpl<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks, 694 ValueToValueMapTy &VMap, ValueToValueMapTy &LVMap, DominatorTree *DT, 695 LoopInfo *LI, ArrayRef<MDNode *> LoopLocalNoAliasDeclScopes, 696 ScalarEvolution &SE) { 697 BasicBlock *Header = L->getHeader(); 698 BasicBlock *Latch = L->getLoopLatch(); 699 BasicBlock *PreHeader = L->getLoopPreheader(); 700 701 Function *F = Header->getParent(); 702 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO(); 703 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO(); 704 Loop *ParentLoop = L->getParentLoop(); 705 706 // For each block in the original loop, create a new copy, 707 // and update the value map with the newly created values. 708 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { 709 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".peel", F); 710 NewBlocks.push_back(NewBB); 711 712 // If an original block is an immediate child of the loop L, its copy 713 // is a child of a ParentLoop after peeling. If a block is a child of 714 // a nested loop, it is handled in the cloneLoop() call below. 715 if (ParentLoop && LI->getLoopFor(*BB) == L) 716 ParentLoop->addBasicBlockToLoop(NewBB, *LI); 717 718 VMap[*BB] = NewBB; 719 720 // If dominator tree is available, insert nodes to represent cloned blocks. 721 if (DT) { 722 if (Header == *BB) 723 DT->addNewBlock(NewBB, InsertTop); 724 else { 725 DomTreeNode *IDom = DT->getNode(*BB)->getIDom(); 726 // VMap must contain entry for IDom, as the iteration order is RPO. 727 DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDom->getBlock()])); 728 } 729 } 730 } 731 732 { 733 // Identify what other metadata depends on the cloned version. After 734 // cloning, replace the metadata with the corrected version for both 735 // memory instructions and noalias intrinsics. 736 std::string Ext = (Twine("Peel") + Twine(IterNumber)).str(); 737 cloneAndAdaptNoAliasScopes(LoopLocalNoAliasDeclScopes, NewBlocks, 738 Header->getContext(), Ext); 739 } 740 741 // Recursively create the new Loop objects for nested loops, if any, 742 // to preserve LoopInfo. 743 for (Loop *ChildLoop : *L) { 744 cloneLoop(ChildLoop, ParentLoop, VMap, LI, nullptr); 745 } 746 747 // Hook-up the control flow for the newly inserted blocks. 748 // The new header is hooked up directly to the "top", which is either 749 // the original loop preheader (for the first iteration) or the previous 750 // iteration's exiting block (for every other iteration) 751 InsertTop->getTerminator()->setSuccessor(0, cast<BasicBlock>(VMap[Header])); 752 753 // Similarly, for the latch: 754 // The original exiting edge is still hooked up to the loop exit. 755 // The backedge now goes to the "bottom", which is either the loop's real 756 // header (for the last peeled iteration) or the copied header of the next 757 // iteration (for every other iteration) 758 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]); 759 auto *LatchTerm = cast<Instruction>(NewLatch->getTerminator()); 760 for (unsigned idx = 0, e = LatchTerm->getNumSuccessors(); idx < e; ++idx) 761 if (LatchTerm->getSuccessor(idx) == Header) { 762 LatchTerm->setSuccessor(idx, InsertBot); 763 break; 764 } 765 if (DT) 766 DT->changeImmediateDominator(InsertBot, NewLatch); 767 768 // The new copy of the loop body starts with a bunch of PHI nodes 769 // that pick an incoming value from either the preheader, or the previous 770 // loop iteration. Since this copy is no longer part of the loop, we 771 // resolve this statically: 772 // For the first iteration, we use the value from the preheader directly. 773 // For any other iteration, we replace the phi with the value generated by 774 // the immediately preceding clone of the loop body (which represents 775 // the previous iteration). 776 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 777 PHINode *NewPHI = cast<PHINode>(VMap[&*I]); 778 if (IterNumber == 0) { 779 VMap[&*I] = NewPHI->getIncomingValueForBlock(PreHeader); 780 } else { 781 Value *LatchVal = NewPHI->getIncomingValueForBlock(Latch); 782 Instruction *LatchInst = dyn_cast<Instruction>(LatchVal); 783 if (LatchInst && L->contains(LatchInst)) 784 VMap[&*I] = LVMap[LatchInst]; 785 else 786 VMap[&*I] = LatchVal; 787 } 788 NewPHI->eraseFromParent(); 789 } 790 791 // Fix up the outgoing values - we need to add a value for the iteration 792 // we've just created. Note that this must happen *after* the incoming 793 // values are adjusted, since the value going out of the latch may also be 794 // a value coming into the header. 795 for (auto Edge : ExitEdges) 796 for (PHINode &PHI : Edge.second->phis()) { 797 Value *LatchVal = PHI.getIncomingValueForBlock(Edge.first); 798 Instruction *LatchInst = dyn_cast<Instruction>(LatchVal); 799 if (LatchInst && L->contains(LatchInst)) 800 LatchVal = VMap[LatchVal]; 801 PHI.addIncoming(LatchVal, cast<BasicBlock>(VMap[Edge.first])); 802 SE.forgetValue(&PHI); 803 } 804 805 // LastValueMap is updated with the values for the current loop 806 // which are used the next time this function is called. 807 for (auto KV : VMap) 808 LVMap[KV.first] = KV.second; 809 } 810 811 TargetTransformInfo::PeelingPreferences llvm::gatherPeelingPreferences( 812 Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, 813 Optional<bool> UserAllowPeeling, 814 Optional<bool> UserAllowProfileBasedPeeling, bool UnrollingSpecficValues) { 815 TargetTransformInfo::PeelingPreferences PP; 816 817 // Set the default values. 818 PP.PeelCount = 0; 819 PP.AllowPeeling = true; 820 PP.AllowLoopNestsPeeling = false; 821 PP.PeelProfiledIterations = true; 822 823 // Get the target specifc values. 824 TTI.getPeelingPreferences(L, SE, PP); 825 826 // User specified values using cl::opt. 827 if (UnrollingSpecficValues) { 828 if (UnrollPeelCount.getNumOccurrences() > 0) 829 PP.PeelCount = UnrollPeelCount; 830 if (UnrollAllowPeeling.getNumOccurrences() > 0) 831 PP.AllowPeeling = UnrollAllowPeeling; 832 if (UnrollAllowLoopNestsPeeling.getNumOccurrences() > 0) 833 PP.AllowLoopNestsPeeling = UnrollAllowLoopNestsPeeling; 834 } 835 836 // User specifed values provided by argument. 837 if (UserAllowPeeling) 838 PP.AllowPeeling = *UserAllowPeeling; 839 if (UserAllowProfileBasedPeeling) 840 PP.PeelProfiledIterations = *UserAllowProfileBasedPeeling; 841 842 return PP; 843 } 844 845 /// Peel off the first \p PeelCount iterations of loop \p L. 846 /// 847 /// Note that this does not peel them off as a single straight-line block. 848 /// Rather, each iteration is peeled off separately, and needs to check the 849 /// exit condition. 850 /// For loops that dynamically execute \p PeelCount iterations or less 851 /// this provides a benefit, since the peeled off iterations, which account 852 /// for the bulk of dynamic execution, can be further simplified by scalar 853 /// optimizations. 854 bool llvm::peelLoop(Loop *L, unsigned PeelCount, LoopInfo *LI, 855 ScalarEvolution *SE, DominatorTree &DT, AssumptionCache *AC, 856 bool PreserveLCSSA) { 857 assert(PeelCount > 0 && "Attempt to peel out zero iterations?"); 858 assert(canPeel(L) && "Attempt to peel a loop which is not peelable?"); 859 860 LoopBlocksDFS LoopBlocks(L); 861 LoopBlocks.perform(LI); 862 863 BasicBlock *Header = L->getHeader(); 864 BasicBlock *PreHeader = L->getLoopPreheader(); 865 BasicBlock *Latch = L->getLoopLatch(); 866 SmallVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitEdges; 867 L->getExitEdges(ExitEdges); 868 869 // Remember dominators of blocks we might reach through exits to change them 870 // later. Immediate dominator of such block might change, because we add more 871 // routes which can lead to the exit: we can reach it from the peeled 872 // iterations too. 873 DenseMap<BasicBlock *, BasicBlock *> NonLoopBlocksIDom; 874 for (auto *BB : L->blocks()) { 875 auto *BBDomNode = DT.getNode(BB); 876 SmallVector<BasicBlock *, 16> ChildrenToUpdate; 877 for (auto *ChildDomNode : BBDomNode->children()) { 878 auto *ChildBB = ChildDomNode->getBlock(); 879 if (!L->contains(ChildBB)) 880 ChildrenToUpdate.push_back(ChildBB); 881 } 882 // The new idom of the block will be the nearest common dominator 883 // of all copies of the previous idom. This is equivalent to the 884 // nearest common dominator of the previous idom and the first latch, 885 // which dominates all copies of the previous idom. 886 BasicBlock *NewIDom = DT.findNearestCommonDominator(BB, Latch); 887 for (auto *ChildBB : ChildrenToUpdate) 888 NonLoopBlocksIDom[ChildBB] = NewIDom; 889 } 890 891 Function *F = Header->getParent(); 892 893 // Set up all the necessary basic blocks. It is convenient to split the 894 // preheader into 3 parts - two blocks to anchor the peeled copy of the loop 895 // body, and a new preheader for the "real" loop. 896 897 // Peeling the first iteration transforms. 898 // 899 // PreHeader: 900 // ... 901 // Header: 902 // LoopBody 903 // If (cond) goto Header 904 // Exit: 905 // 906 // into 907 // 908 // InsertTop: 909 // LoopBody 910 // If (!cond) goto Exit 911 // InsertBot: 912 // NewPreHeader: 913 // ... 914 // Header: 915 // LoopBody 916 // If (cond) goto Header 917 // Exit: 918 // 919 // Each following iteration will split the current bottom anchor in two, 920 // and put the new copy of the loop body between these two blocks. That is, 921 // after peeling another iteration from the example above, we'll split 922 // InsertBot, and get: 923 // 924 // InsertTop: 925 // LoopBody 926 // If (!cond) goto Exit 927 // InsertBot: 928 // LoopBody 929 // If (!cond) goto Exit 930 // InsertBot.next: 931 // NewPreHeader: 932 // ... 933 // Header: 934 // LoopBody 935 // If (cond) goto Header 936 // Exit: 937 938 BasicBlock *InsertTop = SplitEdge(PreHeader, Header, &DT, LI); 939 BasicBlock *InsertBot = 940 SplitBlock(InsertTop, InsertTop->getTerminator(), &DT, LI); 941 BasicBlock *NewPreHeader = 942 SplitBlock(InsertBot, InsertBot->getTerminator(), &DT, LI); 943 944 InsertTop->setName(Header->getName() + ".peel.begin"); 945 InsertBot->setName(Header->getName() + ".peel.next"); 946 NewPreHeader->setName(PreHeader->getName() + ".peel.newph"); 947 948 ValueToValueMapTy LVMap; 949 950 Instruction *LatchTerm = 951 cast<Instruction>(cast<BasicBlock>(Latch)->getTerminator()); 952 953 // If we have branch weight information, we'll want to update it for the 954 // newly created branches. 955 DenseMap<Instruction *, WeightInfo> Weights; 956 initBranchWeights(Weights, L); 957 958 // Identify what noalias metadata is inside the loop: if it is inside the 959 // loop, the associated metadata must be cloned for each iteration. 960 SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes; 961 identifyNoAliasScopesToClone(L->getBlocks(), LoopLocalNoAliasDeclScopes); 962 963 // For each peeled-off iteration, make a copy of the loop. 964 for (unsigned Iter = 0; Iter < PeelCount; ++Iter) { 965 SmallVector<BasicBlock *, 8> NewBlocks; 966 ValueToValueMapTy VMap; 967 968 cloneLoopBlocks(L, Iter, InsertTop, InsertBot, ExitEdges, NewBlocks, 969 LoopBlocks, VMap, LVMap, &DT, LI, 970 LoopLocalNoAliasDeclScopes, *SE); 971 972 // Remap to use values from the current iteration instead of the 973 // previous one. 974 remapInstructionsInBlocks(NewBlocks, VMap); 975 976 // Update IDoms of the blocks reachable through exits. 977 if (Iter == 0) 978 for (auto BBIDom : NonLoopBlocksIDom) 979 DT.changeImmediateDominator(BBIDom.first, 980 cast<BasicBlock>(LVMap[BBIDom.second])); 981 #ifdef EXPENSIVE_CHECKS 982 assert(DT.verify(DominatorTree::VerificationLevel::Fast)); 983 #endif 984 985 for (auto &[Term, Info] : Weights) { 986 auto *TermCopy = cast<Instruction>(VMap[Term]); 987 updateBranchWeights(TermCopy, Info); 988 } 989 990 // Remove Loop metadata from the latch branch instruction 991 // because it is not the Loop's latch branch anymore. 992 auto *LatchTermCopy = cast<Instruction>(VMap[LatchTerm]); 993 LatchTermCopy->setMetadata(LLVMContext::MD_loop, nullptr); 994 995 InsertTop = InsertBot; 996 InsertBot = SplitBlock(InsertBot, InsertBot->getTerminator(), &DT, LI); 997 InsertBot->setName(Header->getName() + ".peel.next"); 998 999 F->getBasicBlockList().splice(InsertTop->getIterator(), 1000 F->getBasicBlockList(), 1001 NewBlocks[0]->getIterator(), F->end()); 1002 } 1003 1004 // Now adjust the phi nodes in the loop header to get their initial values 1005 // from the last peeled-off iteration instead of the preheader. 1006 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 1007 PHINode *PHI = cast<PHINode>(I); 1008 Value *NewVal = PHI->getIncomingValueForBlock(Latch); 1009 Instruction *LatchInst = dyn_cast<Instruction>(NewVal); 1010 if (LatchInst && L->contains(LatchInst)) 1011 NewVal = LVMap[LatchInst]; 1012 1013 PHI->setIncomingValueForBlock(NewPreHeader, NewVal); 1014 } 1015 1016 for (const auto &[Term, Info] : Weights) 1017 fixupBranchWeights(Term, Info); 1018 1019 // Update Metadata for count of peeled off iterations. 1020 unsigned AlreadyPeeled = 0; 1021 if (auto Peeled = getOptionalIntLoopAttribute(L, PeeledCountMetaData)) 1022 AlreadyPeeled = *Peeled; 1023 addStringMetadataToLoop(L, PeeledCountMetaData, AlreadyPeeled + PeelCount); 1024 1025 if (Loop *ParentLoop = L->getParentLoop()) 1026 L = ParentLoop; 1027 1028 // We modified the loop, update SE. 1029 SE->forgetTopmostLoop(L); 1030 1031 #ifdef EXPENSIVE_CHECKS 1032 // Finally DomtTree must be correct. 1033 assert(DT.verify(DominatorTree::VerificationLevel::Fast)); 1034 #endif 1035 1036 // FIXME: Incrementally update loop-simplify 1037 simplifyLoop(L, &DT, LI, SE, AC, nullptr, PreserveLCSSA); 1038 1039 NumPeeled++; 1040 1041 return true; 1042 } 1043