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/Metadata.h" 32 #include "llvm/IR/PatternMatch.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/UnrollLoop.h" 42 #include "llvm/Transforms/Utils/ValueMapper.h" 43 #include <algorithm> 44 #include <cassert> 45 #include <cstdint> 46 #include <limits> 47 48 using namespace llvm; 49 using namespace llvm::PatternMatch; 50 51 #define DEBUG_TYPE "loop-peel" 52 53 STATISTIC(NumPeeled, "Number of loops peeled"); 54 55 static cl::opt<unsigned> UnrollPeelCount( 56 "unroll-peel-count", cl::Hidden, 57 cl::desc("Set the unroll peeling count, for testing purposes")); 58 59 static cl::opt<bool> 60 UnrollAllowPeeling("unroll-allow-peeling", cl::init(true), cl::Hidden, 61 cl::desc("Allows loops to be peeled when the dynamic " 62 "trip count is known to be low.")); 63 64 static cl::opt<bool> 65 UnrollAllowLoopNestsPeeling("unroll-allow-loop-nests-peeling", 66 cl::init(false), cl::Hidden, 67 cl::desc("Allows loop nests to be peeled.")); 68 69 static cl::opt<unsigned> UnrollPeelMaxCount( 70 "unroll-peel-max-count", cl::init(7), cl::Hidden, 71 cl::desc("Max average trip count which will cause loop peeling.")); 72 73 static cl::opt<unsigned> UnrollForcePeelCount( 74 "unroll-force-peel-count", cl::init(0), cl::Hidden, 75 cl::desc("Force a peel count regardless of profiling information.")); 76 77 static const char *PeeledCountMetaData = "llvm.loop.peeled.count"; 78 79 // Designates that a Phi is estimated to become invariant after an "infinite" 80 // number of loop iterations (i.e. only may become an invariant if the loop is 81 // fully unrolled). 82 static const unsigned InfiniteIterationsToInvariance = 83 std::numeric_limits<unsigned>::max(); 84 85 // Check whether we are capable of peeling this loop. 86 bool llvm::canPeel(Loop *L) { 87 // Make sure the loop is in simplified form 88 if (!L->isLoopSimplifyForm()) 89 return false; 90 91 // Don't try to peel loops where the latch is not the exiting block. 92 // This can be an indication of two different things: 93 // 1) The loop is not rotated. 94 // 2) The loop contains irreducible control flow that involves the latch. 95 const BasicBlock *Latch = L->getLoopLatch(); 96 if (!L->isLoopExiting(Latch)) 97 return false; 98 99 // Peeling is only supported if the latch is a branch. 100 if (!isa<BranchInst>(Latch->getTerminator())) 101 return false; 102 103 SmallVector<BasicBlock *, 4> Exits; 104 L->getUniqueNonLatchExitBlocks(Exits); 105 // The latch must either be the only exiting block or all non-latch exit 106 // blocks have either a deopt or unreachable terminator. Both deopt and 107 // unreachable terminators are a strong indication they are not taken. Note 108 // that this is a profitability check, not a legality check. Also note that 109 // LoopPeeling currently can only update the branch weights of latch blocks 110 // and branch weights to blocks with deopt or unreachable do not need 111 // updating. 112 return all_of(Exits, [](const BasicBlock *BB) { 113 return BB->getTerminatingDeoptimizeCall() || 114 isa<UnreachableInst>(BB->getTerminator()); 115 }); 116 } 117 118 // This function calculates the number of iterations after which the given Phi 119 // becomes an invariant. The pre-calculated values are memorized in the map. The 120 // function (shortcut is I) is calculated according to the following definition: 121 // Given %x = phi <Inputs from above the loop>, ..., [%y, %back.edge]. 122 // If %y is a loop invariant, then I(%x) = 1. 123 // If %y is a Phi from the loop header, I(%x) = I(%y) + 1. 124 // Otherwise, I(%x) is infinite. 125 // TODO: Actually if %y is an expression that depends only on Phi %z and some 126 // loop invariants, we can estimate I(%x) = I(%z) + 1. The example 127 // looks like: 128 // %x = phi(0, %a), <-- becomes invariant starting from 3rd iteration. 129 // %y = phi(0, 5), 130 // %a = %y + 1. 131 static unsigned calculateIterationsToInvariance( 132 PHINode *Phi, Loop *L, BasicBlock *BackEdge, 133 SmallDenseMap<PHINode *, unsigned> &IterationsToInvariance) { 134 assert(Phi->getParent() == L->getHeader() && 135 "Non-loop Phi should not be checked for turning into invariant."); 136 assert(BackEdge == L->getLoopLatch() && "Wrong latch?"); 137 // If we already know the answer, take it from the map. 138 auto I = IterationsToInvariance.find(Phi); 139 if (I != IterationsToInvariance.end()) 140 return I->second; 141 142 // Otherwise we need to analyze the input from the back edge. 143 Value *Input = Phi->getIncomingValueForBlock(BackEdge); 144 // Place infinity to map to avoid infinite recursion for cycled Phis. Such 145 // cycles can never stop on an invariant. 146 IterationsToInvariance[Phi] = InfiniteIterationsToInvariance; 147 unsigned ToInvariance = InfiniteIterationsToInvariance; 148 149 if (L->isLoopInvariant(Input)) 150 ToInvariance = 1u; 151 else if (PHINode *IncPhi = dyn_cast<PHINode>(Input)) { 152 // Only consider Phis in header block. 153 if (IncPhi->getParent() != L->getHeader()) 154 return InfiniteIterationsToInvariance; 155 // If the input becomes an invariant after X iterations, then our Phi 156 // becomes an invariant after X + 1 iterations. 157 unsigned InputToInvariance = calculateIterationsToInvariance( 158 IncPhi, L, BackEdge, IterationsToInvariance); 159 if (InputToInvariance != InfiniteIterationsToInvariance) 160 ToInvariance = InputToInvariance + 1u; 161 } 162 163 // If we found that this Phi lies in an invariant chain, update the map. 164 if (ToInvariance != InfiniteIterationsToInvariance) 165 IterationsToInvariance[Phi] = ToInvariance; 166 return ToInvariance; 167 } 168 169 // Try to find any invariant memory reads that will become dereferenceable in 170 // the remainder loop after peeling. The load must also be used (transitively) 171 // by an exit condition. Returns the number of iterations to peel off (at the 172 // moment either 0 or 1). 173 static unsigned peelToTurnInvariantLoadsDerefencebale(Loop &L, 174 DominatorTree &DT) { 175 // Skip loops with a single exiting block, because there should be no benefit 176 // for the heuristic below. 177 if (L.getExitingBlock()) 178 return 0; 179 180 // All non-latch exit blocks must have an UnreachableInst terminator. 181 // Otherwise the heuristic below may not be profitable. 182 SmallVector<BasicBlock *, 4> Exits; 183 L.getUniqueNonLatchExitBlocks(Exits); 184 if (any_of(Exits, [](const BasicBlock *BB) { 185 return !isa<UnreachableInst>(BB->getTerminator()); 186 })) 187 return 0; 188 189 // Now look for invariant loads that dominate the latch and are not known to 190 // be dereferenceable. If there are such loads and no writes, they will become 191 // dereferenceable in the loop if the first iteration is peeled off. Also 192 // collect the set of instructions controlled by such loads. Only peel if an 193 // exit condition uses (transitively) such a load. 194 BasicBlock *Header = L.getHeader(); 195 BasicBlock *Latch = L.getLoopLatch(); 196 SmallPtrSet<Value *, 8> LoadUsers; 197 const DataLayout &DL = L.getHeader()->getModule()->getDataLayout(); 198 for (BasicBlock *BB : L.blocks()) { 199 for (Instruction &I : *BB) { 200 if (I.mayWriteToMemory()) 201 return 0; 202 203 auto Iter = LoadUsers.find(&I); 204 if (Iter != LoadUsers.end()) { 205 for (Value *U : I.users()) 206 LoadUsers.insert(U); 207 } 208 // Do not look for reads in the header; they can already be hoisted 209 // without peeling. 210 if (BB == Header) 211 continue; 212 if (auto *LI = dyn_cast<LoadInst>(&I)) { 213 Value *Ptr = LI->getPointerOperand(); 214 if (DT.dominates(BB, Latch) && L.isLoopInvariant(Ptr) && 215 !isDereferenceablePointer(Ptr, LI->getType(), DL, LI, &DT)) 216 for (Value *U : I.users()) 217 LoadUsers.insert(U); 218 } 219 } 220 } 221 SmallVector<BasicBlock *> ExitingBlocks; 222 L.getExitingBlocks(ExitingBlocks); 223 for (BasicBlock *Exiting : ExitingBlocks) 224 if (LoadUsers.find(Exiting->getTerminator()) != LoadUsers.end()) 225 return 1; 226 return 0; 227 } 228 229 // Return the number of iterations to peel off that make conditions in the 230 // body true/false. For example, if we peel 2 iterations off the loop below, 231 // the condition i < 2 can be evaluated at compile time. 232 // for (i = 0; i < n; i++) 233 // if (i < 2) 234 // .. 235 // else 236 // .. 237 // } 238 static unsigned countToEliminateCompares(Loop &L, unsigned MaxPeelCount, 239 ScalarEvolution &SE) { 240 assert(L.isLoopSimplifyForm() && "Loop needs to be in loop simplify form"); 241 unsigned DesiredPeelCount = 0; 242 243 for (auto *BB : L.blocks()) { 244 auto *BI = dyn_cast<BranchInst>(BB->getTerminator()); 245 if (!BI || BI->isUnconditional()) 246 continue; 247 248 // Ignore loop exit condition. 249 if (L.getLoopLatch() == BB) 250 continue; 251 252 Value *Condition = BI->getCondition(); 253 Value *LeftVal, *RightVal; 254 CmpInst::Predicate Pred; 255 if (!match(Condition, m_ICmp(Pred, m_Value(LeftVal), m_Value(RightVal)))) 256 continue; 257 258 const SCEV *LeftSCEV = SE.getSCEV(LeftVal); 259 const SCEV *RightSCEV = SE.getSCEV(RightVal); 260 261 // Do not consider predicates that are known to be true or false 262 // independently of the loop iteration. 263 if (SE.evaluatePredicate(Pred, LeftSCEV, RightSCEV)) 264 continue; 265 266 // Check if we have a condition with one AddRec and one non AddRec 267 // expression. Normalize LeftSCEV to be the AddRec. 268 if (!isa<SCEVAddRecExpr>(LeftSCEV)) { 269 if (isa<SCEVAddRecExpr>(RightSCEV)) { 270 std::swap(LeftSCEV, RightSCEV); 271 Pred = ICmpInst::getSwappedPredicate(Pred); 272 } else 273 continue; 274 } 275 276 const SCEVAddRecExpr *LeftAR = cast<SCEVAddRecExpr>(LeftSCEV); 277 278 // Avoid huge SCEV computations in the loop below, make sure we only 279 // consider AddRecs of the loop we are trying to peel. 280 if (!LeftAR->isAffine() || LeftAR->getLoop() != &L) 281 continue; 282 if (!(ICmpInst::isEquality(Pred) && LeftAR->hasNoSelfWrap()) && 283 !SE.getMonotonicPredicateType(LeftAR, Pred)) 284 continue; 285 286 // Check if extending the current DesiredPeelCount lets us evaluate Pred 287 // or !Pred in the loop body statically. 288 unsigned NewPeelCount = DesiredPeelCount; 289 290 const SCEV *IterVal = LeftAR->evaluateAtIteration( 291 SE.getConstant(LeftSCEV->getType(), NewPeelCount), SE); 292 293 // If the original condition is not known, get the negated predicate 294 // (which holds on the else branch) and check if it is known. This allows 295 // us to peel of iterations that make the original condition false. 296 if (!SE.isKnownPredicate(Pred, IterVal, RightSCEV)) 297 Pred = ICmpInst::getInversePredicate(Pred); 298 299 const SCEV *Step = LeftAR->getStepRecurrence(SE); 300 const SCEV *NextIterVal = SE.getAddExpr(IterVal, Step); 301 auto PeelOneMoreIteration = [&IterVal, &NextIterVal, &SE, Step, 302 &NewPeelCount]() { 303 IterVal = NextIterVal; 304 NextIterVal = SE.getAddExpr(IterVal, Step); 305 NewPeelCount++; 306 }; 307 308 auto CanPeelOneMoreIteration = [&NewPeelCount, &MaxPeelCount]() { 309 return NewPeelCount < MaxPeelCount; 310 }; 311 312 while (CanPeelOneMoreIteration() && 313 SE.isKnownPredicate(Pred, IterVal, RightSCEV)) 314 PeelOneMoreIteration(); 315 316 // With *that* peel count, does the predicate !Pred become known in the 317 // first iteration of the loop body after peeling? 318 if (!SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), IterVal, 319 RightSCEV)) 320 continue; // If not, give up. 321 322 // However, for equality comparisons, that isn't always sufficient to 323 // eliminate the comparsion in loop body, we may need to peel one more 324 // iteration. See if that makes !Pred become unknown again. 325 if (ICmpInst::isEquality(Pred) && 326 !SE.isKnownPredicate(ICmpInst::getInversePredicate(Pred), NextIterVal, 327 RightSCEV) && 328 !SE.isKnownPredicate(Pred, IterVal, RightSCEV) && 329 SE.isKnownPredicate(Pred, NextIterVal, RightSCEV)) { 330 if (!CanPeelOneMoreIteration()) 331 continue; // Need to peel one more iteration, but can't. Give up. 332 PeelOneMoreIteration(); // Great! 333 } 334 335 DesiredPeelCount = std::max(DesiredPeelCount, NewPeelCount); 336 } 337 338 return DesiredPeelCount; 339 } 340 341 // Return the number of iterations we want to peel off. 342 void llvm::computePeelCount(Loop *L, unsigned LoopSize, 343 TargetTransformInfo::PeelingPreferences &PP, 344 unsigned &TripCount, DominatorTree &DT, 345 ScalarEvolution &SE, unsigned Threshold) { 346 assert(LoopSize > 0 && "Zero loop size is not allowed!"); 347 // Save the PP.PeelCount value set by the target in 348 // TTI.getPeelingPreferences or by the flag -unroll-peel-count. 349 unsigned TargetPeelCount = PP.PeelCount; 350 PP.PeelCount = 0; 351 if (!canPeel(L)) 352 return; 353 354 // Only try to peel innermost loops by default. 355 // The constraint can be relaxed by the target in TTI.getUnrollingPreferences 356 // or by the flag -unroll-allow-loop-nests-peeling. 357 if (!PP.AllowLoopNestsPeeling && !L->isInnermost()) 358 return; 359 360 // If the user provided a peel count, use that. 361 bool UserPeelCount = UnrollForcePeelCount.getNumOccurrences() > 0; 362 if (UserPeelCount) { 363 LLVM_DEBUG(dbgs() << "Force-peeling first " << UnrollForcePeelCount 364 << " iterations.\n"); 365 PP.PeelCount = UnrollForcePeelCount; 366 PP.PeelProfiledIterations = true; 367 return; 368 } 369 370 // Skip peeling if it's disabled. 371 if (!PP.AllowPeeling) 372 return; 373 374 unsigned AlreadyPeeled = 0; 375 if (auto Peeled = getOptionalIntLoopAttribute(L, PeeledCountMetaData)) 376 AlreadyPeeled = *Peeled; 377 // Stop if we already peeled off the maximum number of iterations. 378 if (AlreadyPeeled >= UnrollPeelMaxCount) 379 return; 380 381 // Here we try to get rid of Phis which become invariants after 1, 2, ..., N 382 // iterations of the loop. For this we compute the number for iterations after 383 // which every Phi is guaranteed to become an invariant, and try to peel the 384 // maximum number of iterations among these values, thus turning all those 385 // Phis into invariants. 386 // First, check that we can peel at least one iteration. 387 if (2 * LoopSize <= Threshold && UnrollPeelMaxCount > 0) { 388 // Store the pre-calculated values here. 389 SmallDenseMap<PHINode *, unsigned> IterationsToInvariance; 390 // Now go through all Phis to calculate their the number of iterations they 391 // need to become invariants. 392 // Start the max computation with the UP.PeelCount value set by the target 393 // in TTI.getUnrollingPreferences or by the flag -unroll-peel-count. 394 unsigned DesiredPeelCount = TargetPeelCount; 395 BasicBlock *BackEdge = L->getLoopLatch(); 396 assert(BackEdge && "Loop is not in simplified form?"); 397 for (auto BI = L->getHeader()->begin(); isa<PHINode>(&*BI); ++BI) { 398 PHINode *Phi = cast<PHINode>(&*BI); 399 unsigned ToInvariance = calculateIterationsToInvariance( 400 Phi, L, BackEdge, IterationsToInvariance); 401 if (ToInvariance != InfiniteIterationsToInvariance) 402 DesiredPeelCount = std::max(DesiredPeelCount, ToInvariance); 403 } 404 405 // Pay respect to limitations implied by loop size and the max peel count. 406 unsigned MaxPeelCount = UnrollPeelMaxCount; 407 MaxPeelCount = std::min(MaxPeelCount, Threshold / LoopSize - 1); 408 409 DesiredPeelCount = std::max(DesiredPeelCount, 410 countToEliminateCompares(*L, MaxPeelCount, SE)); 411 412 if (DesiredPeelCount == 0) 413 DesiredPeelCount = peelToTurnInvariantLoadsDerefencebale(*L, DT); 414 415 if (DesiredPeelCount > 0) { 416 DesiredPeelCount = std::min(DesiredPeelCount, MaxPeelCount); 417 // Consider max peel count limitation. 418 assert(DesiredPeelCount > 0 && "Wrong loop size estimation?"); 419 if (DesiredPeelCount + AlreadyPeeled <= UnrollPeelMaxCount) { 420 LLVM_DEBUG(dbgs() << "Peel " << DesiredPeelCount 421 << " iteration(s) to turn" 422 << " some Phis into invariants.\n"); 423 PP.PeelCount = DesiredPeelCount; 424 PP.PeelProfiledIterations = false; 425 return; 426 } 427 } 428 } 429 430 // Bail if we know the statically calculated trip count. 431 // In this case we rather prefer partial unrolling. 432 if (TripCount) 433 return; 434 435 // Do not apply profile base peeling if it is disabled. 436 if (!PP.PeelProfiledIterations) 437 return; 438 // If we don't know the trip count, but have reason to believe the average 439 // trip count is low, peeling should be beneficial, since we will usually 440 // hit the peeled section. 441 // We only do this in the presence of profile information, since otherwise 442 // our estimates of the trip count are not reliable enough. 443 if (L->getHeader()->getParent()->hasProfileData()) { 444 Optional<unsigned> PeelCount = getLoopEstimatedTripCount(L); 445 if (!PeelCount) 446 return; 447 448 LLVM_DEBUG(dbgs() << "Profile-based estimated trip count is " << *PeelCount 449 << "\n"); 450 451 if (*PeelCount) { 452 if ((*PeelCount + AlreadyPeeled <= UnrollPeelMaxCount) && 453 (LoopSize * (*PeelCount + 1) <= Threshold)) { 454 LLVM_DEBUG(dbgs() << "Peeling first " << *PeelCount 455 << " iterations.\n"); 456 PP.PeelCount = *PeelCount; 457 return; 458 } 459 LLVM_DEBUG(dbgs() << "Requested peel count: " << *PeelCount << "\n"); 460 LLVM_DEBUG(dbgs() << "Already peel count: " << AlreadyPeeled << "\n"); 461 LLVM_DEBUG(dbgs() << "Max peel count: " << UnrollPeelMaxCount << "\n"); 462 LLVM_DEBUG(dbgs() << "Peel cost: " << LoopSize * (*PeelCount + 1) 463 << "\n"); 464 LLVM_DEBUG(dbgs() << "Max peel cost: " << Threshold << "\n"); 465 } 466 } 467 } 468 469 /// Update the branch weights of the latch of a peeled-off loop 470 /// iteration. 471 /// This sets the branch weights for the latch of the recently peeled off loop 472 /// iteration correctly. 473 /// Let F is a weight of the edge from latch to header. 474 /// Let E is a weight of the edge from latch to exit. 475 /// F/(F+E) is a probability to go to loop and E/(F+E) is a probability to 476 /// go to exit. 477 /// Then, Estimated TripCount = F / E. 478 /// For I-th (counting from 0) peeled off iteration we set the the weights for 479 /// the peeled latch as (TC - I, 1). It gives us reasonable distribution, 480 /// The probability to go to exit 1/(TC-I) increases. At the same time 481 /// the estimated trip count of remaining loop reduces by I. 482 /// To avoid dealing with division rounding we can just multiple both part 483 /// of weights to E and use weight as (F - I * E, E). 484 /// 485 /// \param Header The copy of the header block that belongs to next iteration. 486 /// \param LatchBR The copy of the latch branch that belongs to this iteration. 487 /// \param[in,out] FallThroughWeight The weight of the edge from latch to 488 /// header before peeling (in) and after peeled off one iteration (out). 489 static void updateBranchWeights(BasicBlock *Header, BranchInst *LatchBR, 490 uint64_t ExitWeight, 491 uint64_t &FallThroughWeight) { 492 // FallThroughWeight is 0 means that there is no branch weights on original 493 // latch block or estimated trip count is zero. 494 if (!FallThroughWeight) 495 return; 496 497 unsigned HeaderIdx = (LatchBR->getSuccessor(0) == Header ? 0 : 1); 498 MDBuilder MDB(LatchBR->getContext()); 499 MDNode *WeightNode = 500 HeaderIdx ? MDB.createBranchWeights(ExitWeight, FallThroughWeight) 501 : MDB.createBranchWeights(FallThroughWeight, ExitWeight); 502 LatchBR->setMetadata(LLVMContext::MD_prof, WeightNode); 503 FallThroughWeight = 504 FallThroughWeight > ExitWeight ? FallThroughWeight - ExitWeight : 1; 505 } 506 507 /// Initialize the weights. 508 /// 509 /// \param Header The header block. 510 /// \param LatchBR The latch branch. 511 /// \param[out] ExitWeight The weight of the edge from Latch to Exit. 512 /// \param[out] FallThroughWeight The weight of the edge from Latch to Header. 513 static void initBranchWeights(BasicBlock *Header, BranchInst *LatchBR, 514 uint64_t &ExitWeight, 515 uint64_t &FallThroughWeight) { 516 uint64_t TrueWeight, FalseWeight; 517 if (!LatchBR->extractProfMetadata(TrueWeight, FalseWeight)) 518 return; 519 unsigned HeaderIdx = LatchBR->getSuccessor(0) == Header ? 0 : 1; 520 ExitWeight = HeaderIdx ? TrueWeight : FalseWeight; 521 FallThroughWeight = HeaderIdx ? FalseWeight : TrueWeight; 522 } 523 524 /// Update the weights of original Latch block after peeling off all iterations. 525 /// 526 /// \param Header The header block. 527 /// \param LatchBR The latch branch. 528 /// \param ExitWeight The weight of the edge from Latch to Exit. 529 /// \param FallThroughWeight The weight of the edge from Latch to Header. 530 static void fixupBranchWeights(BasicBlock *Header, BranchInst *LatchBR, 531 uint64_t ExitWeight, 532 uint64_t FallThroughWeight) { 533 // FallThroughWeight is 0 means that there is no branch weights on original 534 // latch block or estimated trip count is zero. 535 if (!FallThroughWeight) 536 return; 537 538 // Sets the branch weights on the loop exit. 539 MDBuilder MDB(LatchBR->getContext()); 540 unsigned HeaderIdx = LatchBR->getSuccessor(0) == Header ? 0 : 1; 541 MDNode *WeightNode = 542 HeaderIdx ? MDB.createBranchWeights(ExitWeight, FallThroughWeight) 543 : MDB.createBranchWeights(FallThroughWeight, ExitWeight); 544 LatchBR->setMetadata(LLVMContext::MD_prof, WeightNode); 545 } 546 547 /// Clones the body of the loop L, putting it between \p InsertTop and \p 548 /// InsertBot. 549 /// \param IterNumber The serial number of the iteration currently being 550 /// peeled off. 551 /// \param ExitEdges The exit edges of the original loop. 552 /// \param[out] NewBlocks A list of the blocks in the newly created clone 553 /// \param[out] VMap The value map between the loop and the new clone. 554 /// \param LoopBlocks A helper for DFS-traversal of the loop. 555 /// \param LVMap A value-map that maps instructions from the original loop to 556 /// instructions in the last peeled-off iteration. 557 static void cloneLoopBlocks( 558 Loop *L, unsigned IterNumber, BasicBlock *InsertTop, BasicBlock *InsertBot, 559 SmallVectorImpl<std::pair<BasicBlock *, BasicBlock *>> &ExitEdges, 560 SmallVectorImpl<BasicBlock *> &NewBlocks, LoopBlocksDFS &LoopBlocks, 561 ValueToValueMapTy &VMap, ValueToValueMapTy &LVMap, DominatorTree *DT, 562 LoopInfo *LI, ArrayRef<MDNode *> LoopLocalNoAliasDeclScopes) { 563 BasicBlock *Header = L->getHeader(); 564 BasicBlock *Latch = L->getLoopLatch(); 565 BasicBlock *PreHeader = L->getLoopPreheader(); 566 567 Function *F = Header->getParent(); 568 LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO(); 569 LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO(); 570 Loop *ParentLoop = L->getParentLoop(); 571 572 // For each block in the original loop, create a new copy, 573 // and update the value map with the newly created values. 574 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { 575 BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".peel", F); 576 NewBlocks.push_back(NewBB); 577 578 // If an original block is an immediate child of the loop L, its copy 579 // is a child of a ParentLoop after peeling. If a block is a child of 580 // a nested loop, it is handled in the cloneLoop() call below. 581 if (ParentLoop && LI->getLoopFor(*BB) == L) 582 ParentLoop->addBasicBlockToLoop(NewBB, *LI); 583 584 VMap[*BB] = NewBB; 585 586 // If dominator tree is available, insert nodes to represent cloned blocks. 587 if (DT) { 588 if (Header == *BB) 589 DT->addNewBlock(NewBB, InsertTop); 590 else { 591 DomTreeNode *IDom = DT->getNode(*BB)->getIDom(); 592 // VMap must contain entry for IDom, as the iteration order is RPO. 593 DT->addNewBlock(NewBB, cast<BasicBlock>(VMap[IDom->getBlock()])); 594 } 595 } 596 } 597 598 { 599 // Identify what other metadata depends on the cloned version. After 600 // cloning, replace the metadata with the corrected version for both 601 // memory instructions and noalias intrinsics. 602 std::string Ext = (Twine("Peel") + Twine(IterNumber)).str(); 603 cloneAndAdaptNoAliasScopes(LoopLocalNoAliasDeclScopes, NewBlocks, 604 Header->getContext(), Ext); 605 } 606 607 // Recursively create the new Loop objects for nested loops, if any, 608 // to preserve LoopInfo. 609 for (Loop *ChildLoop : *L) { 610 cloneLoop(ChildLoop, ParentLoop, VMap, LI, nullptr); 611 } 612 613 // Hook-up the control flow for the newly inserted blocks. 614 // The new header is hooked up directly to the "top", which is either 615 // the original loop preheader (for the first iteration) or the previous 616 // iteration's exiting block (for every other iteration) 617 InsertTop->getTerminator()->setSuccessor(0, cast<BasicBlock>(VMap[Header])); 618 619 // Similarly, for the latch: 620 // The original exiting edge is still hooked up to the loop exit. 621 // The backedge now goes to the "bottom", which is either the loop's real 622 // header (for the last peeled iteration) or the copied header of the next 623 // iteration (for every other iteration) 624 BasicBlock *NewLatch = cast<BasicBlock>(VMap[Latch]); 625 BranchInst *LatchBR = cast<BranchInst>(NewLatch->getTerminator()); 626 for (unsigned idx = 0, e = LatchBR->getNumSuccessors(); idx < e; ++idx) 627 if (LatchBR->getSuccessor(idx) == Header) { 628 LatchBR->setSuccessor(idx, InsertBot); 629 break; 630 } 631 if (DT) 632 DT->changeImmediateDominator(InsertBot, NewLatch); 633 634 // The new copy of the loop body starts with a bunch of PHI nodes 635 // that pick an incoming value from either the preheader, or the previous 636 // loop iteration. Since this copy is no longer part of the loop, we 637 // resolve this statically: 638 // For the first iteration, we use the value from the preheader directly. 639 // For any other iteration, we replace the phi with the value generated by 640 // the immediately preceding clone of the loop body (which represents 641 // the previous iteration). 642 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 643 PHINode *NewPHI = cast<PHINode>(VMap[&*I]); 644 if (IterNumber == 0) { 645 VMap[&*I] = NewPHI->getIncomingValueForBlock(PreHeader); 646 } else { 647 Value *LatchVal = NewPHI->getIncomingValueForBlock(Latch); 648 Instruction *LatchInst = dyn_cast<Instruction>(LatchVal); 649 if (LatchInst && L->contains(LatchInst)) 650 VMap[&*I] = LVMap[LatchInst]; 651 else 652 VMap[&*I] = LatchVal; 653 } 654 cast<BasicBlock>(VMap[Header])->getInstList().erase(NewPHI); 655 } 656 657 // Fix up the outgoing values - we need to add a value for the iteration 658 // we've just created. Note that this must happen *after* the incoming 659 // values are adjusted, since the value going out of the latch may also be 660 // a value coming into the header. 661 for (auto Edge : ExitEdges) 662 for (PHINode &PHI : Edge.second->phis()) { 663 Value *LatchVal = PHI.getIncomingValueForBlock(Edge.first); 664 Instruction *LatchInst = dyn_cast<Instruction>(LatchVal); 665 if (LatchInst && L->contains(LatchInst)) 666 LatchVal = VMap[LatchVal]; 667 PHI.addIncoming(LatchVal, cast<BasicBlock>(VMap[Edge.first])); 668 } 669 670 // LastValueMap is updated with the values for the current loop 671 // which are used the next time this function is called. 672 for (auto KV : VMap) 673 LVMap[KV.first] = KV.second; 674 } 675 676 TargetTransformInfo::PeelingPreferences llvm::gatherPeelingPreferences( 677 Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, 678 Optional<bool> UserAllowPeeling, 679 Optional<bool> UserAllowProfileBasedPeeling, bool UnrollingSpecficValues) { 680 TargetTransformInfo::PeelingPreferences PP; 681 682 // Set the default values. 683 PP.PeelCount = 0; 684 PP.AllowPeeling = true; 685 PP.AllowLoopNestsPeeling = false; 686 PP.PeelProfiledIterations = true; 687 688 // Get the target specifc values. 689 TTI.getPeelingPreferences(L, SE, PP); 690 691 // User specified values using cl::opt. 692 if (UnrollingSpecficValues) { 693 if (UnrollPeelCount.getNumOccurrences() > 0) 694 PP.PeelCount = UnrollPeelCount; 695 if (UnrollAllowPeeling.getNumOccurrences() > 0) 696 PP.AllowPeeling = UnrollAllowPeeling; 697 if (UnrollAllowLoopNestsPeeling.getNumOccurrences() > 0) 698 PP.AllowLoopNestsPeeling = UnrollAllowLoopNestsPeeling; 699 } 700 701 // User specifed values provided by argument. 702 if (UserAllowPeeling.hasValue()) 703 PP.AllowPeeling = *UserAllowPeeling; 704 if (UserAllowProfileBasedPeeling.hasValue()) 705 PP.PeelProfiledIterations = *UserAllowProfileBasedPeeling; 706 707 return PP; 708 } 709 710 /// Peel off the first \p PeelCount iterations of loop \p L. 711 /// 712 /// Note that this does not peel them off as a single straight-line block. 713 /// Rather, each iteration is peeled off separately, and needs to check the 714 /// exit condition. 715 /// For loops that dynamically execute \p PeelCount iterations or less 716 /// this provides a benefit, since the peeled off iterations, which account 717 /// for the bulk of dynamic execution, can be further simplified by scalar 718 /// optimizations. 719 bool llvm::peelLoop(Loop *L, unsigned PeelCount, LoopInfo *LI, 720 ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, 721 bool PreserveLCSSA) { 722 assert(PeelCount > 0 && "Attempt to peel out zero iterations?"); 723 assert(canPeel(L) && "Attempt to peel a loop which is not peelable?"); 724 725 LoopBlocksDFS LoopBlocks(L); 726 LoopBlocks.perform(LI); 727 728 BasicBlock *Header = L->getHeader(); 729 BasicBlock *PreHeader = L->getLoopPreheader(); 730 BasicBlock *Latch = L->getLoopLatch(); 731 SmallVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitEdges; 732 L->getExitEdges(ExitEdges); 733 734 DenseMap<BasicBlock *, BasicBlock *> ExitIDom; 735 if (DT) { 736 // We'd like to determine the idom of exit block after peeling one 737 // iteration. 738 // Let Exit is exit block. 739 // Let ExitingSet - is a set of predecessors of Exit block. They are exiting 740 // blocks. 741 // Let Latch' and ExitingSet' are copies after a peeling. 742 // We'd like to find an idom'(Exit) - idom of Exit after peeling. 743 // It is an evident that idom'(Exit) will be the nearest common dominator 744 // of ExitingSet and ExitingSet'. 745 // idom(Exit) is a nearest common dominator of ExitingSet. 746 // idom(Exit)' is a nearest common dominator of ExitingSet'. 747 // Taking into account that we have a single Latch, Latch' will dominate 748 // Header and idom(Exit). 749 // So the idom'(Exit) is nearest common dominator of idom(Exit)' and Latch'. 750 // All these basic blocks are in the same loop, so what we find is 751 // (nearest common dominator of idom(Exit) and Latch)'. 752 // In the loop below we remember nearest common dominator of idom(Exit) and 753 // Latch to update idom of Exit later. 754 assert(L->hasDedicatedExits() && "No dedicated exits?"); 755 for (auto Edge : ExitEdges) { 756 if (ExitIDom.count(Edge.second)) 757 continue; 758 BasicBlock *BB = DT->findNearestCommonDominator( 759 DT->getNode(Edge.second)->getIDom()->getBlock(), Latch); 760 assert(L->contains(BB) && "IDom is not in a loop"); 761 ExitIDom[Edge.second] = BB; 762 } 763 } 764 765 Function *F = Header->getParent(); 766 767 // Set up all the necessary basic blocks. It is convenient to split the 768 // preheader into 3 parts - two blocks to anchor the peeled copy of the loop 769 // body, and a new preheader for the "real" loop. 770 771 // Peeling the first iteration transforms. 772 // 773 // PreHeader: 774 // ... 775 // Header: 776 // LoopBody 777 // If (cond) goto Header 778 // Exit: 779 // 780 // into 781 // 782 // InsertTop: 783 // LoopBody 784 // If (!cond) goto Exit 785 // InsertBot: 786 // NewPreHeader: 787 // ... 788 // Header: 789 // LoopBody 790 // If (cond) goto Header 791 // Exit: 792 // 793 // Each following iteration will split the current bottom anchor in two, 794 // and put the new copy of the loop body between these two blocks. That is, 795 // after peeling another iteration from the example above, we'll split 796 // InsertBot, and get: 797 // 798 // InsertTop: 799 // LoopBody 800 // If (!cond) goto Exit 801 // InsertBot: 802 // LoopBody 803 // If (!cond) goto Exit 804 // InsertBot.next: 805 // NewPreHeader: 806 // ... 807 // Header: 808 // LoopBody 809 // If (cond) goto Header 810 // Exit: 811 812 BasicBlock *InsertTop = SplitEdge(PreHeader, Header, DT, LI); 813 BasicBlock *InsertBot = 814 SplitBlock(InsertTop, InsertTop->getTerminator(), DT, LI); 815 BasicBlock *NewPreHeader = 816 SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI); 817 818 InsertTop->setName(Header->getName() + ".peel.begin"); 819 InsertBot->setName(Header->getName() + ".peel.next"); 820 NewPreHeader->setName(PreHeader->getName() + ".peel.newph"); 821 822 ValueToValueMapTy LVMap; 823 824 // If we have branch weight information, we'll want to update it for the 825 // newly created branches. 826 BranchInst *LatchBR = 827 cast<BranchInst>(cast<BasicBlock>(Latch)->getTerminator()); 828 uint64_t ExitWeight = 0, FallThroughWeight = 0; 829 initBranchWeights(Header, LatchBR, ExitWeight, FallThroughWeight); 830 831 // Identify what noalias metadata is inside the loop: if it is inside the 832 // loop, the associated metadata must be cloned for each iteration. 833 SmallVector<MDNode *, 6> LoopLocalNoAliasDeclScopes; 834 identifyNoAliasScopesToClone(L->getBlocks(), LoopLocalNoAliasDeclScopes); 835 836 // For each peeled-off iteration, make a copy of the loop. 837 for (unsigned Iter = 0; Iter < PeelCount; ++Iter) { 838 SmallVector<BasicBlock *, 8> NewBlocks; 839 ValueToValueMapTy VMap; 840 841 cloneLoopBlocks(L, Iter, InsertTop, InsertBot, ExitEdges, NewBlocks, 842 LoopBlocks, VMap, LVMap, DT, LI, 843 LoopLocalNoAliasDeclScopes); 844 845 // Remap to use values from the current iteration instead of the 846 // previous one. 847 remapInstructionsInBlocks(NewBlocks, VMap); 848 849 if (DT) { 850 // Latches of the cloned loops dominate over the loop exit, so idom of the 851 // latter is the first cloned loop body, as original PreHeader dominates 852 // the original loop body. 853 if (Iter == 0) 854 for (auto Exit : ExitIDom) 855 DT->changeImmediateDominator(Exit.first, 856 cast<BasicBlock>(LVMap[Exit.second])); 857 #ifdef EXPENSIVE_CHECKS 858 assert(DT->verify(DominatorTree::VerificationLevel::Fast)); 859 #endif 860 } 861 862 auto *LatchBRCopy = cast<BranchInst>(VMap[LatchBR]); 863 updateBranchWeights(InsertBot, LatchBRCopy, ExitWeight, FallThroughWeight); 864 // Remove Loop metadata from the latch branch instruction 865 // because it is not the Loop's latch branch anymore. 866 LatchBRCopy->setMetadata(LLVMContext::MD_loop, nullptr); 867 868 InsertTop = InsertBot; 869 InsertBot = SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI); 870 InsertBot->setName(Header->getName() + ".peel.next"); 871 872 F->getBasicBlockList().splice(InsertTop->getIterator(), 873 F->getBasicBlockList(), 874 NewBlocks[0]->getIterator(), F->end()); 875 } 876 877 // Now adjust the phi nodes in the loop header to get their initial values 878 // from the last peeled-off iteration instead of the preheader. 879 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) { 880 PHINode *PHI = cast<PHINode>(I); 881 Value *NewVal = PHI->getIncomingValueForBlock(Latch); 882 Instruction *LatchInst = dyn_cast<Instruction>(NewVal); 883 if (LatchInst && L->contains(LatchInst)) 884 NewVal = LVMap[LatchInst]; 885 886 PHI->setIncomingValueForBlock(NewPreHeader, NewVal); 887 } 888 889 fixupBranchWeights(Header, LatchBR, ExitWeight, FallThroughWeight); 890 891 // Update Metadata for count of peeled off iterations. 892 unsigned AlreadyPeeled = 0; 893 if (auto Peeled = getOptionalIntLoopAttribute(L, PeeledCountMetaData)) 894 AlreadyPeeled = *Peeled; 895 addStringMetadataToLoop(L, PeeledCountMetaData, AlreadyPeeled + PeelCount); 896 897 if (Loop *ParentLoop = L->getParentLoop()) 898 L = ParentLoop; 899 900 // We modified the loop, update SE. 901 SE->forgetTopmostLoop(L); 902 903 // Finally DomtTree must be correct. 904 assert(DT->verify(DominatorTree::VerificationLevel::Fast)); 905 906 // FIXME: Incrementally update loop-simplify 907 simplifyLoop(L, DT, LI, SE, AC, nullptr, PreserveLCSSA); 908 909 NumPeeled++; 910 911 return true; 912 } 913