1 //===- LoopUnroll.cpp - Loop unroller 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 implements a simple loop unroller. It works best when loops have 10 // been canonicalized by the -indvars pass, allowing it to determine the trip 11 // counts of loops easily. 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/Scalar/LoopUnrollPass.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/DenseMapInfo.h" 17 #include "llvm/ADT/DenseSet.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SetVector.h" 20 #include "llvm/ADT/SmallPtrSet.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/StringRef.h" 23 #include "llvm/Analysis/AssumptionCache.h" 24 #include "llvm/Analysis/BlockFrequencyInfo.h" 25 #include "llvm/Analysis/CodeMetrics.h" 26 #include "llvm/Analysis/LoopAnalysisManager.h" 27 #include "llvm/Analysis/LoopInfo.h" 28 #include "llvm/Analysis/LoopPass.h" 29 #include "llvm/Analysis/LoopUnrollAnalyzer.h" 30 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 31 #include "llvm/Analysis/ProfileSummaryInfo.h" 32 #include "llvm/Analysis/ScalarEvolution.h" 33 #include "llvm/Analysis/TargetTransformInfo.h" 34 #include "llvm/IR/BasicBlock.h" 35 #include "llvm/IR/CFG.h" 36 #include "llvm/IR/Constant.h" 37 #include "llvm/IR/Constants.h" 38 #include "llvm/IR/DiagnosticInfo.h" 39 #include "llvm/IR/Dominators.h" 40 #include "llvm/IR/Function.h" 41 #include "llvm/IR/Instruction.h" 42 #include "llvm/IR/Instructions.h" 43 #include "llvm/IR/IntrinsicInst.h" 44 #include "llvm/IR/Metadata.h" 45 #include "llvm/IR/PassManager.h" 46 #include "llvm/InitializePasses.h" 47 #include "llvm/Pass.h" 48 #include "llvm/Support/Casting.h" 49 #include "llvm/Support/CommandLine.h" 50 #include "llvm/Support/Debug.h" 51 #include "llvm/Support/ErrorHandling.h" 52 #include "llvm/Support/raw_ostream.h" 53 #include "llvm/Transforms/Scalar.h" 54 #include "llvm/Transforms/Scalar/LoopPassManager.h" 55 #include "llvm/Transforms/Utils.h" 56 #include "llvm/Transforms/Utils/LoopPeel.h" 57 #include "llvm/Transforms/Utils/LoopSimplify.h" 58 #include "llvm/Transforms/Utils/LoopUtils.h" 59 #include "llvm/Transforms/Utils/SizeOpts.h" 60 #include "llvm/Transforms/Utils/UnrollLoop.h" 61 #include <algorithm> 62 #include <cassert> 63 #include <cstdint> 64 #include <limits> 65 #include <optional> 66 #include <string> 67 #include <tuple> 68 #include <utility> 69 70 using namespace llvm; 71 72 #define DEBUG_TYPE "loop-unroll" 73 74 cl::opt<bool> llvm::ForgetSCEVInLoopUnroll( 75 "forget-scev-loop-unroll", cl::init(false), cl::Hidden, 76 cl::desc("Forget everything in SCEV when doing LoopUnroll, instead of just" 77 " the current top-most loop. This is sometimes preferred to reduce" 78 " compile time.")); 79 80 static cl::opt<unsigned> 81 UnrollThreshold("unroll-threshold", cl::Hidden, 82 cl::desc("The cost threshold for loop unrolling")); 83 84 static cl::opt<unsigned> 85 UnrollOptSizeThreshold( 86 "unroll-optsize-threshold", cl::init(0), cl::Hidden, 87 cl::desc("The cost threshold for loop unrolling when optimizing for " 88 "size")); 89 90 static cl::opt<unsigned> UnrollPartialThreshold( 91 "unroll-partial-threshold", cl::Hidden, 92 cl::desc("The cost threshold for partial loop unrolling")); 93 94 static cl::opt<unsigned> UnrollMaxPercentThresholdBoost( 95 "unroll-max-percent-threshold-boost", cl::init(400), cl::Hidden, 96 cl::desc("The maximum 'boost' (represented as a percentage >= 100) applied " 97 "to the threshold when aggressively unrolling a loop due to the " 98 "dynamic cost savings. If completely unrolling a loop will reduce " 99 "the total runtime from X to Y, we boost the loop unroll " 100 "threshold to DefaultThreshold*std::min(MaxPercentThresholdBoost, " 101 "X/Y). This limit avoids excessive code bloat.")); 102 103 static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze( 104 "unroll-max-iteration-count-to-analyze", cl::init(10), cl::Hidden, 105 cl::desc("Don't allow loop unrolling to simulate more than this number of" 106 "iterations when checking full unroll profitability")); 107 108 static cl::opt<unsigned> UnrollCount( 109 "unroll-count", cl::Hidden, 110 cl::desc("Use this unroll count for all loops including those with " 111 "unroll_count pragma values, for testing purposes")); 112 113 static cl::opt<unsigned> UnrollMaxCount( 114 "unroll-max-count", cl::Hidden, 115 cl::desc("Set the max unroll count for partial and runtime unrolling, for" 116 "testing purposes")); 117 118 static cl::opt<unsigned> UnrollFullMaxCount( 119 "unroll-full-max-count", cl::Hidden, 120 cl::desc( 121 "Set the max unroll count for full unrolling, for testing purposes")); 122 123 static cl::opt<bool> 124 UnrollAllowPartial("unroll-allow-partial", cl::Hidden, 125 cl::desc("Allows loops to be partially unrolled until " 126 "-unroll-threshold loop size is reached.")); 127 128 static cl::opt<bool> UnrollAllowRemainder( 129 "unroll-allow-remainder", cl::Hidden, 130 cl::desc("Allow generation of a loop remainder (extra iterations) " 131 "when unrolling a loop.")); 132 133 static cl::opt<bool> 134 UnrollRuntime("unroll-runtime", cl::Hidden, 135 cl::desc("Unroll loops with run-time trip counts")); 136 137 static cl::opt<unsigned> UnrollMaxUpperBound( 138 "unroll-max-upperbound", cl::init(8), cl::Hidden, 139 cl::desc( 140 "The max of trip count upper bound that is considered in unrolling")); 141 142 static cl::opt<unsigned> PragmaUnrollThreshold( 143 "pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden, 144 cl::desc("Unrolled size limit for loops with an unroll(full) or " 145 "unroll_count pragma.")); 146 147 static cl::opt<unsigned> FlatLoopTripCountThreshold( 148 "flat-loop-tripcount-threshold", cl::init(5), cl::Hidden, 149 cl::desc("If the runtime tripcount for the loop is lower than the " 150 "threshold, the loop is considered as flat and will be less " 151 "aggressively unrolled.")); 152 153 static cl::opt<bool> UnrollUnrollRemainder( 154 "unroll-remainder", cl::Hidden, 155 cl::desc("Allow the loop remainder to be unrolled.")); 156 157 // This option isn't ever intended to be enabled, it serves to allow 158 // experiments to check the assumptions about when this kind of revisit is 159 // necessary. 160 static cl::opt<bool> UnrollRevisitChildLoops( 161 "unroll-revisit-child-loops", cl::Hidden, 162 cl::desc("Enqueue and re-visit child loops in the loop PM after unrolling. " 163 "This shouldn't typically be needed as child loops (or their " 164 "clones) were already visited.")); 165 166 static cl::opt<unsigned> UnrollThresholdAggressive( 167 "unroll-threshold-aggressive", cl::init(300), cl::Hidden, 168 cl::desc("Threshold (max size of unrolled loop) to use in aggressive (O3) " 169 "optimizations")); 170 static cl::opt<unsigned> 171 UnrollThresholdDefault("unroll-threshold-default", cl::init(150), 172 cl::Hidden, 173 cl::desc("Default threshold (max size of unrolled " 174 "loop), used in all but O3 optimizations")); 175 176 static cl::opt<unsigned> PragmaUnrollFullMaxIterations( 177 "pragma-unroll-full-max-iterations", cl::init(1'000'000), cl::Hidden, 178 cl::desc("Maximum allowed iterations to unroll under pragma unroll full.")); 179 180 /// A magic value for use with the Threshold parameter to indicate 181 /// that the loop unroll should be performed regardless of how much 182 /// code expansion would result. 183 static const unsigned NoThreshold = std::numeric_limits<unsigned>::max(); 184 185 /// Gather the various unrolling parameters based on the defaults, compiler 186 /// flags, TTI overrides and user specified parameters. 187 TargetTransformInfo::UnrollingPreferences llvm::gatherUnrollingPreferences( 188 Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, 189 BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI, 190 OptimizationRemarkEmitter &ORE, int OptLevel, 191 std::optional<unsigned> UserThreshold, std::optional<unsigned> UserCount, 192 std::optional<bool> UserAllowPartial, std::optional<bool> UserRuntime, 193 std::optional<bool> UserUpperBound, 194 std::optional<unsigned> UserFullUnrollMaxCount) { 195 TargetTransformInfo::UnrollingPreferences UP; 196 197 // Set up the defaults 198 UP.Threshold = 199 OptLevel > 2 ? UnrollThresholdAggressive : UnrollThresholdDefault; 200 UP.MaxPercentThresholdBoost = 400; 201 UP.OptSizeThreshold = UnrollOptSizeThreshold; 202 UP.PartialThreshold = 150; 203 UP.PartialOptSizeThreshold = UnrollOptSizeThreshold; 204 UP.Count = 0; 205 UP.DefaultUnrollRuntimeCount = 8; 206 UP.MaxCount = std::numeric_limits<unsigned>::max(); 207 UP.MaxUpperBound = UnrollMaxUpperBound; 208 UP.FullUnrollMaxCount = std::numeric_limits<unsigned>::max(); 209 UP.BEInsns = 2; 210 UP.Partial = false; 211 UP.Runtime = false; 212 UP.AllowRemainder = true; 213 UP.UnrollRemainder = false; 214 UP.AllowExpensiveTripCount = false; 215 UP.Force = false; 216 UP.UpperBound = false; 217 UP.UnrollAndJam = false; 218 UP.UnrollAndJamInnerLoopThreshold = 60; 219 UP.MaxIterationsCountToAnalyze = UnrollMaxIterationsCountToAnalyze; 220 221 // Override with any target specific settings 222 TTI.getUnrollingPreferences(L, SE, UP, &ORE); 223 224 // Apply size attributes 225 bool OptForSize = L->getHeader()->getParent()->hasOptSize() || 226 // Let unroll hints / pragmas take precedence over PGSO. 227 (hasUnrollTransformation(L) != TM_ForcedByUser && 228 llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI, 229 PGSOQueryType::IRPass)); 230 if (OptForSize) { 231 UP.Threshold = UP.OptSizeThreshold; 232 UP.PartialThreshold = UP.PartialOptSizeThreshold; 233 UP.MaxPercentThresholdBoost = 100; 234 } 235 236 // Apply any user values specified by cl::opt 237 if (UnrollThreshold.getNumOccurrences() > 0) 238 UP.Threshold = UnrollThreshold; 239 if (UnrollPartialThreshold.getNumOccurrences() > 0) 240 UP.PartialThreshold = UnrollPartialThreshold; 241 if (UnrollMaxPercentThresholdBoost.getNumOccurrences() > 0) 242 UP.MaxPercentThresholdBoost = UnrollMaxPercentThresholdBoost; 243 if (UnrollMaxCount.getNumOccurrences() > 0) 244 UP.MaxCount = UnrollMaxCount; 245 if (UnrollMaxUpperBound.getNumOccurrences() > 0) 246 UP.MaxUpperBound = UnrollMaxUpperBound; 247 if (UnrollFullMaxCount.getNumOccurrences() > 0) 248 UP.FullUnrollMaxCount = UnrollFullMaxCount; 249 if (UnrollAllowPartial.getNumOccurrences() > 0) 250 UP.Partial = UnrollAllowPartial; 251 if (UnrollAllowRemainder.getNumOccurrences() > 0) 252 UP.AllowRemainder = UnrollAllowRemainder; 253 if (UnrollRuntime.getNumOccurrences() > 0) 254 UP.Runtime = UnrollRuntime; 255 if (UnrollMaxUpperBound == 0) 256 UP.UpperBound = false; 257 if (UnrollUnrollRemainder.getNumOccurrences() > 0) 258 UP.UnrollRemainder = UnrollUnrollRemainder; 259 if (UnrollMaxIterationsCountToAnalyze.getNumOccurrences() > 0) 260 UP.MaxIterationsCountToAnalyze = UnrollMaxIterationsCountToAnalyze; 261 262 // Apply user values provided by argument 263 if (UserThreshold) { 264 UP.Threshold = *UserThreshold; 265 UP.PartialThreshold = *UserThreshold; 266 } 267 if (UserCount) 268 UP.Count = *UserCount; 269 if (UserAllowPartial) 270 UP.Partial = *UserAllowPartial; 271 if (UserRuntime) 272 UP.Runtime = *UserRuntime; 273 if (UserUpperBound) 274 UP.UpperBound = *UserUpperBound; 275 if (UserFullUnrollMaxCount) 276 UP.FullUnrollMaxCount = *UserFullUnrollMaxCount; 277 278 return UP; 279 } 280 281 namespace { 282 283 /// A struct to densely store the state of an instruction after unrolling at 284 /// each iteration. 285 /// 286 /// This is designed to work like a tuple of <Instruction *, int> for the 287 /// purposes of hashing and lookup, but to be able to associate two boolean 288 /// states with each key. 289 struct UnrolledInstState { 290 Instruction *I; 291 int Iteration : 30; 292 unsigned IsFree : 1; 293 unsigned IsCounted : 1; 294 }; 295 296 /// Hashing and equality testing for a set of the instruction states. 297 struct UnrolledInstStateKeyInfo { 298 using PtrInfo = DenseMapInfo<Instruction *>; 299 using PairInfo = DenseMapInfo<std::pair<Instruction *, int>>; 300 301 static inline UnrolledInstState getEmptyKey() { 302 return {PtrInfo::getEmptyKey(), 0, 0, 0}; 303 } 304 305 static inline UnrolledInstState getTombstoneKey() { 306 return {PtrInfo::getTombstoneKey(), 0, 0, 0}; 307 } 308 309 static inline unsigned getHashValue(const UnrolledInstState &S) { 310 return PairInfo::getHashValue({S.I, S.Iteration}); 311 } 312 313 static inline bool isEqual(const UnrolledInstState &LHS, 314 const UnrolledInstState &RHS) { 315 return PairInfo::isEqual({LHS.I, LHS.Iteration}, {RHS.I, RHS.Iteration}); 316 } 317 }; 318 319 struct EstimatedUnrollCost { 320 /// The estimated cost after unrolling. 321 unsigned UnrolledCost; 322 323 /// The estimated dynamic cost of executing the instructions in the 324 /// rolled form. 325 unsigned RolledDynamicCost; 326 }; 327 328 struct PragmaInfo { 329 PragmaInfo(bool UUC, bool PFU, unsigned PC, bool PEU) 330 : UserUnrollCount(UUC), PragmaFullUnroll(PFU), PragmaCount(PC), 331 PragmaEnableUnroll(PEU) {} 332 const bool UserUnrollCount; 333 const bool PragmaFullUnroll; 334 const unsigned PragmaCount; 335 const bool PragmaEnableUnroll; 336 }; 337 338 } // end anonymous namespace 339 340 /// Figure out if the loop is worth full unrolling. 341 /// 342 /// Complete loop unrolling can make some loads constant, and we need to know 343 /// if that would expose any further optimization opportunities. This routine 344 /// estimates this optimization. It computes cost of unrolled loop 345 /// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By 346 /// dynamic cost we mean that we won't count costs of blocks that are known not 347 /// to be executed (i.e. if we have a branch in the loop and we know that at the 348 /// given iteration its condition would be resolved to true, we won't add up the 349 /// cost of the 'false'-block). 350 /// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If 351 /// the analysis failed (no benefits expected from the unrolling, or the loop is 352 /// too big to analyze), the returned value is std::nullopt. 353 static std::optional<EstimatedUnrollCost> analyzeLoopUnrollCost( 354 const Loop *L, unsigned TripCount, DominatorTree &DT, ScalarEvolution &SE, 355 const SmallPtrSetImpl<const Value *> &EphValues, 356 const TargetTransformInfo &TTI, unsigned MaxUnrolledLoopSize, 357 unsigned MaxIterationsCountToAnalyze) { 358 // We want to be able to scale offsets by the trip count and add more offsets 359 // to them without checking for overflows, and we already don't want to 360 // analyze *massive* trip counts, so we force the max to be reasonably small. 361 assert(MaxIterationsCountToAnalyze < 362 (unsigned)(std::numeric_limits<int>::max() / 2) && 363 "The unroll iterations max is too large!"); 364 365 // Only analyze inner loops. We can't properly estimate cost of nested loops 366 // and we won't visit inner loops again anyway. 367 if (!L->isInnermost()) 368 return std::nullopt; 369 370 // Don't simulate loops with a big or unknown tripcount 371 if (!TripCount || TripCount > MaxIterationsCountToAnalyze) 372 return std::nullopt; 373 374 SmallSetVector<BasicBlock *, 16> BBWorklist; 375 SmallSetVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitWorklist; 376 DenseMap<Value *, Value *> SimplifiedValues; 377 SmallVector<std::pair<Value *, Value *>, 4> SimplifiedInputValues; 378 379 // The estimated cost of the unrolled form of the loop. We try to estimate 380 // this by simplifying as much as we can while computing the estimate. 381 InstructionCost UnrolledCost = 0; 382 383 // We also track the estimated dynamic (that is, actually executed) cost in 384 // the rolled form. This helps identify cases when the savings from unrolling 385 // aren't just exposing dead control flows, but actual reduced dynamic 386 // instructions due to the simplifications which we expect to occur after 387 // unrolling. 388 InstructionCost RolledDynamicCost = 0; 389 390 // We track the simplification of each instruction in each iteration. We use 391 // this to recursively merge costs into the unrolled cost on-demand so that 392 // we don't count the cost of any dead code. This is essentially a map from 393 // <instruction, int> to <bool, bool>, but stored as a densely packed struct. 394 DenseSet<UnrolledInstState, UnrolledInstStateKeyInfo> InstCostMap; 395 396 // A small worklist used to accumulate cost of instructions from each 397 // observable and reached root in the loop. 398 SmallVector<Instruction *, 16> CostWorklist; 399 400 // PHI-used worklist used between iterations while accumulating cost. 401 SmallVector<Instruction *, 4> PHIUsedList; 402 403 // Helper function to accumulate cost for instructions in the loop. 404 auto AddCostRecursively = [&](Instruction &RootI, int Iteration) { 405 assert(Iteration >= 0 && "Cannot have a negative iteration!"); 406 assert(CostWorklist.empty() && "Must start with an empty cost list"); 407 assert(PHIUsedList.empty() && "Must start with an empty phi used list"); 408 CostWorklist.push_back(&RootI); 409 TargetTransformInfo::TargetCostKind CostKind = 410 RootI.getFunction()->hasMinSize() ? 411 TargetTransformInfo::TCK_CodeSize : 412 TargetTransformInfo::TCK_SizeAndLatency; 413 for (;; --Iteration) { 414 do { 415 Instruction *I = CostWorklist.pop_back_val(); 416 417 // InstCostMap only uses I and Iteration as a key, the other two values 418 // don't matter here. 419 auto CostIter = InstCostMap.find({I, Iteration, 0, 0}); 420 if (CostIter == InstCostMap.end()) 421 // If an input to a PHI node comes from a dead path through the loop 422 // we may have no cost data for it here. What that actually means is 423 // that it is free. 424 continue; 425 auto &Cost = *CostIter; 426 if (Cost.IsCounted) 427 // Already counted this instruction. 428 continue; 429 430 // Mark that we are counting the cost of this instruction now. 431 Cost.IsCounted = true; 432 433 // If this is a PHI node in the loop header, just add it to the PHI set. 434 if (auto *PhiI = dyn_cast<PHINode>(I)) 435 if (PhiI->getParent() == L->getHeader()) { 436 assert(Cost.IsFree && "Loop PHIs shouldn't be evaluated as they " 437 "inherently simplify during unrolling."); 438 if (Iteration == 0) 439 continue; 440 441 // Push the incoming value from the backedge into the PHI used list 442 // if it is an in-loop instruction. We'll use this to populate the 443 // cost worklist for the next iteration (as we count backwards). 444 if (auto *OpI = dyn_cast<Instruction>( 445 PhiI->getIncomingValueForBlock(L->getLoopLatch()))) 446 if (L->contains(OpI)) 447 PHIUsedList.push_back(OpI); 448 continue; 449 } 450 451 // First accumulate the cost of this instruction. 452 if (!Cost.IsFree) { 453 UnrolledCost += TTI.getInstructionCost(I, CostKind); 454 LLVM_DEBUG(dbgs() << "Adding cost of instruction (iteration " 455 << Iteration << "): "); 456 LLVM_DEBUG(I->dump()); 457 } 458 459 // We must count the cost of every operand which is not free, 460 // recursively. If we reach a loop PHI node, simply add it to the set 461 // to be considered on the next iteration (backwards!). 462 for (Value *Op : I->operands()) { 463 // Check whether this operand is free due to being a constant or 464 // outside the loop. 465 auto *OpI = dyn_cast<Instruction>(Op); 466 if (!OpI || !L->contains(OpI)) 467 continue; 468 469 // Otherwise accumulate its cost. 470 CostWorklist.push_back(OpI); 471 } 472 } while (!CostWorklist.empty()); 473 474 if (PHIUsedList.empty()) 475 // We've exhausted the search. 476 break; 477 478 assert(Iteration > 0 && 479 "Cannot track PHI-used values past the first iteration!"); 480 CostWorklist.append(PHIUsedList.begin(), PHIUsedList.end()); 481 PHIUsedList.clear(); 482 } 483 }; 484 485 // Ensure that we don't violate the loop structure invariants relied on by 486 // this analysis. 487 assert(L->isLoopSimplifyForm() && "Must put loop into normal form first."); 488 assert(L->isLCSSAForm(DT) && 489 "Must have loops in LCSSA form to track live-out values."); 490 491 LLVM_DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n"); 492 493 TargetTransformInfo::TargetCostKind CostKind = 494 L->getHeader()->getParent()->hasMinSize() ? 495 TargetTransformInfo::TCK_CodeSize : TargetTransformInfo::TCK_SizeAndLatency; 496 // Simulate execution of each iteration of the loop counting instructions, 497 // which would be simplified. 498 // Since the same load will take different values on different iterations, 499 // we literally have to go through all loop's iterations. 500 for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) { 501 LLVM_DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n"); 502 503 // Prepare for the iteration by collecting any simplified entry or backedge 504 // inputs. 505 for (Instruction &I : *L->getHeader()) { 506 auto *PHI = dyn_cast<PHINode>(&I); 507 if (!PHI) 508 break; 509 510 // The loop header PHI nodes must have exactly two input: one from the 511 // loop preheader and one from the loop latch. 512 assert( 513 PHI->getNumIncomingValues() == 2 && 514 "Must have an incoming value only for the preheader and the latch."); 515 516 Value *V = PHI->getIncomingValueForBlock( 517 Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch()); 518 if (Iteration != 0 && SimplifiedValues.count(V)) 519 V = SimplifiedValues.lookup(V); 520 SimplifiedInputValues.push_back({PHI, V}); 521 } 522 523 // Now clear and re-populate the map for the next iteration. 524 SimplifiedValues.clear(); 525 while (!SimplifiedInputValues.empty()) 526 SimplifiedValues.insert(SimplifiedInputValues.pop_back_val()); 527 528 UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SE, L); 529 530 BBWorklist.clear(); 531 BBWorklist.insert(L->getHeader()); 532 // Note that we *must not* cache the size, this loop grows the worklist. 533 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) { 534 BasicBlock *BB = BBWorklist[Idx]; 535 536 // Visit all instructions in the given basic block and try to simplify 537 // it. We don't change the actual IR, just count optimization 538 // opportunities. 539 for (Instruction &I : *BB) { 540 // These won't get into the final code - don't even try calculating the 541 // cost for them. 542 if (isa<DbgInfoIntrinsic>(I) || EphValues.count(&I)) 543 continue; 544 545 // Track this instruction's expected baseline cost when executing the 546 // rolled loop form. 547 RolledDynamicCost += TTI.getInstructionCost(&I, CostKind); 548 549 // Visit the instruction to analyze its loop cost after unrolling, 550 // and if the visitor returns true, mark the instruction as free after 551 // unrolling and continue. 552 bool IsFree = Analyzer.visit(I); 553 bool Inserted = InstCostMap.insert({&I, (int)Iteration, 554 (unsigned)IsFree, 555 /*IsCounted*/ false}).second; 556 (void)Inserted; 557 assert(Inserted && "Cannot have a state for an unvisited instruction!"); 558 559 if (IsFree) 560 continue; 561 562 // Can't properly model a cost of a call. 563 // FIXME: With a proper cost model we should be able to do it. 564 if (auto *CI = dyn_cast<CallInst>(&I)) { 565 const Function *Callee = CI->getCalledFunction(); 566 if (!Callee || TTI.isLoweredToCall(Callee)) { 567 LLVM_DEBUG(dbgs() << "Can't analyze cost of loop with call\n"); 568 return std::nullopt; 569 } 570 } 571 572 // If the instruction might have a side-effect recursively account for 573 // the cost of it and all the instructions leading up to it. 574 if (I.mayHaveSideEffects()) 575 AddCostRecursively(I, Iteration); 576 577 // If unrolled body turns out to be too big, bail out. 578 if (UnrolledCost > MaxUnrolledLoopSize) { 579 LLVM_DEBUG(dbgs() << " Exceeded threshold.. exiting.\n" 580 << " UnrolledCost: " << UnrolledCost 581 << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize 582 << "\n"); 583 return std::nullopt; 584 } 585 } 586 587 Instruction *TI = BB->getTerminator(); 588 589 auto getSimplifiedConstant = [&](Value *V) -> Constant * { 590 if (SimplifiedValues.count(V)) 591 V = SimplifiedValues.lookup(V); 592 return dyn_cast<Constant>(V); 593 }; 594 595 // Add in the live successors by first checking whether we have terminator 596 // that may be simplified based on the values simplified by this call. 597 BasicBlock *KnownSucc = nullptr; 598 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 599 if (BI->isConditional()) { 600 if (auto *SimpleCond = getSimplifiedConstant(BI->getCondition())) { 601 // Just take the first successor if condition is undef 602 if (isa<UndefValue>(SimpleCond)) 603 KnownSucc = BI->getSuccessor(0); 604 else if (ConstantInt *SimpleCondVal = 605 dyn_cast<ConstantInt>(SimpleCond)) 606 KnownSucc = BI->getSuccessor(SimpleCondVal->isZero() ? 1 : 0); 607 } 608 } 609 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 610 if (auto *SimpleCond = getSimplifiedConstant(SI->getCondition())) { 611 // Just take the first successor if condition is undef 612 if (isa<UndefValue>(SimpleCond)) 613 KnownSucc = SI->getSuccessor(0); 614 else if (ConstantInt *SimpleCondVal = 615 dyn_cast<ConstantInt>(SimpleCond)) 616 KnownSucc = SI->findCaseValue(SimpleCondVal)->getCaseSuccessor(); 617 } 618 } 619 if (KnownSucc) { 620 if (L->contains(KnownSucc)) 621 BBWorklist.insert(KnownSucc); 622 else 623 ExitWorklist.insert({BB, KnownSucc}); 624 continue; 625 } 626 627 // Add BB's successors to the worklist. 628 for (BasicBlock *Succ : successors(BB)) 629 if (L->contains(Succ)) 630 BBWorklist.insert(Succ); 631 else 632 ExitWorklist.insert({BB, Succ}); 633 AddCostRecursively(*TI, Iteration); 634 } 635 636 // If we found no optimization opportunities on the first iteration, we 637 // won't find them on later ones too. 638 if (UnrolledCost == RolledDynamicCost) { 639 LLVM_DEBUG(dbgs() << " No opportunities found.. exiting.\n" 640 << " UnrolledCost: " << UnrolledCost << "\n"); 641 return std::nullopt; 642 } 643 } 644 645 while (!ExitWorklist.empty()) { 646 BasicBlock *ExitingBB, *ExitBB; 647 std::tie(ExitingBB, ExitBB) = ExitWorklist.pop_back_val(); 648 649 for (Instruction &I : *ExitBB) { 650 auto *PN = dyn_cast<PHINode>(&I); 651 if (!PN) 652 break; 653 654 Value *Op = PN->getIncomingValueForBlock(ExitingBB); 655 if (auto *OpI = dyn_cast<Instruction>(Op)) 656 if (L->contains(OpI)) 657 AddCostRecursively(*OpI, TripCount - 1); 658 } 659 } 660 661 assert(UnrolledCost.isValid() && RolledDynamicCost.isValid() && 662 "All instructions must have a valid cost, whether the " 663 "loop is rolled or unrolled."); 664 665 LLVM_DEBUG(dbgs() << "Analysis finished:\n" 666 << "UnrolledCost: " << UnrolledCost << ", " 667 << "RolledDynamicCost: " << RolledDynamicCost << "\n"); 668 return {{unsigned(*UnrolledCost.getValue()), 669 unsigned(*RolledDynamicCost.getValue())}}; 670 } 671 672 UnrollCostEstimator::UnrollCostEstimator( 673 const Loop *L, const TargetTransformInfo &TTI, 674 const SmallPtrSetImpl<const Value *> &EphValues, unsigned BEInsns) { 675 CodeMetrics Metrics; 676 for (BasicBlock *BB : L->blocks()) 677 Metrics.analyzeBasicBlock(BB, TTI, EphValues); 678 NumInlineCandidates = Metrics.NumInlineCandidates; 679 NotDuplicatable = Metrics.notDuplicatable; 680 Convergent = Metrics.convergent; 681 LoopSize = Metrics.NumInsts; 682 683 // Don't allow an estimate of size zero. This would allows unrolling of loops 684 // with huge iteration counts, which is a compile time problem even if it's 685 // not a problem for code quality. Also, the code using this size may assume 686 // that each loop has at least three instructions (likely a conditional 687 // branch, a comparison feeding that branch, and some kind of loop increment 688 // feeding that comparison instruction). 689 if (LoopSize.isValid() && LoopSize < BEInsns + 1) 690 // This is an open coded max() on InstructionCost 691 LoopSize = BEInsns + 1; 692 } 693 694 uint64_t UnrollCostEstimator::getUnrolledLoopSize( 695 const TargetTransformInfo::UnrollingPreferences &UP, 696 unsigned CountOverwrite) const { 697 unsigned LS = *LoopSize.getValue(); 698 assert(LS >= UP.BEInsns && "LoopSize should not be less than BEInsns!"); 699 if (CountOverwrite) 700 return static_cast<uint64_t>(LS - UP.BEInsns) * CountOverwrite + UP.BEInsns; 701 else 702 return static_cast<uint64_t>(LS - UP.BEInsns) * UP.Count + UP.BEInsns; 703 } 704 705 // Returns the loop hint metadata node with the given name (for example, 706 // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is 707 // returned. 708 static MDNode *getUnrollMetadataForLoop(const Loop *L, StringRef Name) { 709 if (MDNode *LoopID = L->getLoopID()) 710 return GetUnrollMetadata(LoopID, Name); 711 return nullptr; 712 } 713 714 // Returns true if the loop has an unroll(full) pragma. 715 static bool hasUnrollFullPragma(const Loop *L) { 716 return getUnrollMetadataForLoop(L, "llvm.loop.unroll.full"); 717 } 718 719 // Returns true if the loop has an unroll(enable) pragma. This metadata is used 720 // for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives. 721 static bool hasUnrollEnablePragma(const Loop *L) { 722 return getUnrollMetadataForLoop(L, "llvm.loop.unroll.enable"); 723 } 724 725 // Returns true if the loop has an runtime unroll(disable) pragma. 726 static bool hasRuntimeUnrollDisablePragma(const Loop *L) { 727 return getUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable"); 728 } 729 730 // If loop has an unroll_count pragma return the (necessarily 731 // positive) value from the pragma. Otherwise return 0. 732 static unsigned unrollCountPragmaValue(const Loop *L) { 733 MDNode *MD = getUnrollMetadataForLoop(L, "llvm.loop.unroll.count"); 734 if (MD) { 735 assert(MD->getNumOperands() == 2 && 736 "Unroll count hint metadata should have two operands."); 737 unsigned Count = 738 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue(); 739 assert(Count >= 1 && "Unroll count must be positive."); 740 return Count; 741 } 742 return 0; 743 } 744 745 // Computes the boosting factor for complete unrolling. 746 // If fully unrolling the loop would save a lot of RolledDynamicCost, it would 747 // be beneficial to fully unroll the loop even if unrolledcost is large. We 748 // use (RolledDynamicCost / UnrolledCost) to model the unroll benefits to adjust 749 // the unroll threshold. 750 static unsigned getFullUnrollBoostingFactor(const EstimatedUnrollCost &Cost, 751 unsigned MaxPercentThresholdBoost) { 752 if (Cost.RolledDynamicCost >= std::numeric_limits<unsigned>::max() / 100) 753 return 100; 754 else if (Cost.UnrolledCost != 0) 755 // The boosting factor is RolledDynamicCost / UnrolledCost 756 return std::min(100 * Cost.RolledDynamicCost / Cost.UnrolledCost, 757 MaxPercentThresholdBoost); 758 else 759 return MaxPercentThresholdBoost; 760 } 761 762 static std::optional<unsigned> 763 shouldPragmaUnroll(Loop *L, const PragmaInfo &PInfo, 764 const unsigned TripMultiple, const unsigned TripCount, 765 unsigned MaxTripCount, const UnrollCostEstimator UCE, 766 const TargetTransformInfo::UnrollingPreferences &UP) { 767 768 // Using unroll pragma 769 // 1st priority is unroll count set by "unroll-count" option. 770 771 if (PInfo.UserUnrollCount) { 772 if (UP.AllowRemainder && 773 UCE.getUnrolledLoopSize(UP, (unsigned)UnrollCount) < UP.Threshold) 774 return (unsigned)UnrollCount; 775 } 776 777 // 2nd priority is unroll count set by pragma. 778 if (PInfo.PragmaCount > 0) { 779 if ((UP.AllowRemainder || (TripMultiple % PInfo.PragmaCount == 0))) 780 return PInfo.PragmaCount; 781 } 782 783 if (PInfo.PragmaFullUnroll && TripCount != 0) { 784 // Certain cases with UBSAN can cause trip count to be calculated as 785 // INT_MAX, Block full unrolling at a reasonable limit so that the compiler 786 // doesn't hang trying to unroll the loop. See PR77842 787 if (TripCount > PragmaUnrollFullMaxIterations) { 788 LLVM_DEBUG(dbgs() << "Won't unroll; trip count is too large\n"); 789 return std::nullopt; 790 } 791 792 return TripCount; 793 } 794 795 if (PInfo.PragmaEnableUnroll && !TripCount && MaxTripCount && 796 MaxTripCount <= UP.MaxUpperBound) 797 return MaxTripCount; 798 799 // if didn't return until here, should continue to other priorties 800 return std::nullopt; 801 } 802 803 static std::optional<unsigned> shouldFullUnroll( 804 Loop *L, const TargetTransformInfo &TTI, DominatorTree &DT, 805 ScalarEvolution &SE, const SmallPtrSetImpl<const Value *> &EphValues, 806 const unsigned FullUnrollTripCount, const UnrollCostEstimator UCE, 807 const TargetTransformInfo::UnrollingPreferences &UP) { 808 assert(FullUnrollTripCount && "should be non-zero!"); 809 810 if (FullUnrollTripCount > UP.FullUnrollMaxCount) 811 return std::nullopt; 812 813 // When computing the unrolled size, note that BEInsns are not replicated 814 // like the rest of the loop body. 815 if (UCE.getUnrolledLoopSize(UP) < UP.Threshold) 816 return FullUnrollTripCount; 817 818 // The loop isn't that small, but we still can fully unroll it if that 819 // helps to remove a significant number of instructions. 820 // To check that, run additional analysis on the loop. 821 if (std::optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost( 822 L, FullUnrollTripCount, DT, SE, EphValues, TTI, 823 UP.Threshold * UP.MaxPercentThresholdBoost / 100, 824 UP.MaxIterationsCountToAnalyze)) { 825 unsigned Boost = 826 getFullUnrollBoostingFactor(*Cost, UP.MaxPercentThresholdBoost); 827 if (Cost->UnrolledCost < UP.Threshold * Boost / 100) 828 return FullUnrollTripCount; 829 } 830 return std::nullopt; 831 } 832 833 static std::optional<unsigned> 834 shouldPartialUnroll(const unsigned LoopSize, const unsigned TripCount, 835 const UnrollCostEstimator UCE, 836 const TargetTransformInfo::UnrollingPreferences &UP) { 837 838 if (!TripCount) 839 return std::nullopt; 840 841 if (!UP.Partial) { 842 LLVM_DEBUG(dbgs() << " will not try to unroll partially because " 843 << "-unroll-allow-partial not given\n"); 844 return 0; 845 } 846 unsigned count = UP.Count; 847 if (count == 0) 848 count = TripCount; 849 if (UP.PartialThreshold != NoThreshold) { 850 // Reduce unroll count to be modulo of TripCount for partial unrolling. 851 if (UCE.getUnrolledLoopSize(UP, count) > UP.PartialThreshold) 852 count = (std::max(UP.PartialThreshold, UP.BEInsns + 1) - UP.BEInsns) / 853 (LoopSize - UP.BEInsns); 854 if (count > UP.MaxCount) 855 count = UP.MaxCount; 856 while (count != 0 && TripCount % count != 0) 857 count--; 858 if (UP.AllowRemainder && count <= 1) { 859 // If there is no Count that is modulo of TripCount, set Count to 860 // largest power-of-two factor that satisfies the threshold limit. 861 // As we'll create fixup loop, do the type of unrolling only if 862 // remainder loop is allowed. 863 count = UP.DefaultUnrollRuntimeCount; 864 while (count != 0 && 865 UCE.getUnrolledLoopSize(UP, count) > UP.PartialThreshold) 866 count >>= 1; 867 } 868 if (count < 2) { 869 count = 0; 870 } 871 } else { 872 count = TripCount; 873 } 874 if (count > UP.MaxCount) 875 count = UP.MaxCount; 876 877 LLVM_DEBUG(dbgs() << " partially unrolling with count: " << count << "\n"); 878 879 return count; 880 } 881 // Returns true if unroll count was set explicitly. 882 // Calculates unroll count and writes it to UP.Count. 883 // Unless IgnoreUser is true, will also use metadata and command-line options 884 // that are specific to to the LoopUnroll pass (which, for instance, are 885 // irrelevant for the LoopUnrollAndJam pass). 886 // FIXME: This function is used by LoopUnroll and LoopUnrollAndJam, but consumes 887 // many LoopUnroll-specific options. The shared functionality should be 888 // refactored into it own function. 889 bool llvm::computeUnrollCount( 890 Loop *L, const TargetTransformInfo &TTI, DominatorTree &DT, LoopInfo *LI, 891 AssumptionCache *AC, ScalarEvolution &SE, 892 const SmallPtrSetImpl<const Value *> &EphValues, 893 OptimizationRemarkEmitter *ORE, unsigned TripCount, unsigned MaxTripCount, 894 bool MaxOrZero, unsigned TripMultiple, const UnrollCostEstimator &UCE, 895 TargetTransformInfo::UnrollingPreferences &UP, 896 TargetTransformInfo::PeelingPreferences &PP, bool &UseUpperBound) { 897 898 unsigned LoopSize = UCE.getRolledLoopSize(); 899 900 const bool UserUnrollCount = UnrollCount.getNumOccurrences() > 0; 901 const bool PragmaFullUnroll = hasUnrollFullPragma(L); 902 const unsigned PragmaCount = unrollCountPragmaValue(L); 903 const bool PragmaEnableUnroll = hasUnrollEnablePragma(L); 904 905 const bool ExplicitUnroll = PragmaCount > 0 || PragmaFullUnroll || 906 PragmaEnableUnroll || UserUnrollCount; 907 908 PragmaInfo PInfo(UserUnrollCount, PragmaFullUnroll, PragmaCount, 909 PragmaEnableUnroll); 910 // Use an explicit peel count that has been specified for testing. In this 911 // case it's not permitted to also specify an explicit unroll count. 912 if (PP.PeelCount) { 913 if (UnrollCount.getNumOccurrences() > 0) { 914 report_fatal_error("Cannot specify both explicit peel count and " 915 "explicit unroll count", /*GenCrashDiag=*/false); 916 } 917 UP.Count = 1; 918 UP.Runtime = false; 919 return true; 920 } 921 // Check for explicit Count. 922 // 1st priority is unroll count set by "unroll-count" option. 923 // 2nd priority is unroll count set by pragma. 924 if (auto UnrollFactor = shouldPragmaUnroll(L, PInfo, TripMultiple, TripCount, 925 MaxTripCount, UCE, UP)) { 926 UP.Count = *UnrollFactor; 927 928 if (UserUnrollCount || (PragmaCount > 0)) { 929 UP.AllowExpensiveTripCount = true; 930 UP.Force = true; 931 } 932 UP.Runtime |= (PragmaCount > 0); 933 return ExplicitUnroll; 934 } else { 935 if (ExplicitUnroll && TripCount != 0) { 936 // If the loop has an unrolling pragma, we want to be more aggressive with 937 // unrolling limits. Set thresholds to at least the PragmaUnrollThreshold 938 // value which is larger than the default limits. 939 UP.Threshold = std::max<unsigned>(UP.Threshold, PragmaUnrollThreshold); 940 UP.PartialThreshold = 941 std::max<unsigned>(UP.PartialThreshold, PragmaUnrollThreshold); 942 } 943 } 944 945 // 3rd priority is exact full unrolling. This will eliminate all copies 946 // of some exit test. 947 UP.Count = 0; 948 if (TripCount) { 949 UP.Count = TripCount; 950 if (auto UnrollFactor = shouldFullUnroll(L, TTI, DT, SE, EphValues, 951 TripCount, UCE, UP)) { 952 UP.Count = *UnrollFactor; 953 UseUpperBound = false; 954 return ExplicitUnroll; 955 } 956 } 957 958 // 4th priority is bounded unrolling. 959 // We can unroll by the upper bound amount if it's generally allowed or if 960 // we know that the loop is executed either the upper bound or zero times. 961 // (MaxOrZero unrolling keeps only the first loop test, so the number of 962 // loop tests remains the same compared to the non-unrolled version, whereas 963 // the generic upper bound unrolling keeps all but the last loop test so the 964 // number of loop tests goes up which may end up being worse on targets with 965 // constrained branch predictor resources so is controlled by an option.) 966 // In addition we only unroll small upper bounds. 967 // Note that the cost of bounded unrolling is always strictly greater than 968 // cost of exact full unrolling. As such, if we have an exact count and 969 // found it unprofitable, we'll never chose to bounded unroll. 970 if (!TripCount && MaxTripCount && (UP.UpperBound || MaxOrZero) && 971 MaxTripCount <= UP.MaxUpperBound) { 972 UP.Count = MaxTripCount; 973 if (auto UnrollFactor = shouldFullUnroll(L, TTI, DT, SE, EphValues, 974 MaxTripCount, UCE, UP)) { 975 UP.Count = *UnrollFactor; 976 UseUpperBound = true; 977 return ExplicitUnroll; 978 } 979 } 980 981 // 5th priority is loop peeling. 982 computePeelCount(L, LoopSize, PP, TripCount, DT, SE, AC, UP.Threshold); 983 if (PP.PeelCount) { 984 UP.Runtime = false; 985 UP.Count = 1; 986 return ExplicitUnroll; 987 } 988 989 // Before starting partial unrolling, set up.partial to true, 990 // if user explicitly asked for unrolling 991 if (TripCount) 992 UP.Partial |= ExplicitUnroll; 993 994 // 6th priority is partial unrolling. 995 // Try partial unroll only when TripCount could be statically calculated. 996 if (auto UnrollFactor = shouldPartialUnroll(LoopSize, TripCount, UCE, UP)) { 997 UP.Count = *UnrollFactor; 998 999 if ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount && 1000 UP.Count != TripCount) 1001 ORE->emit([&]() { 1002 return OptimizationRemarkMissed(DEBUG_TYPE, 1003 "FullUnrollAsDirectedTooLarge", 1004 L->getStartLoc(), L->getHeader()) 1005 << "Unable to fully unroll loop as directed by unroll pragma " 1006 "because " 1007 "unrolled size is too large."; 1008 }); 1009 1010 if (UP.PartialThreshold != NoThreshold) { 1011 if (UP.Count == 0) { 1012 if (PragmaEnableUnroll) 1013 ORE->emit([&]() { 1014 return OptimizationRemarkMissed(DEBUG_TYPE, 1015 "UnrollAsDirectedTooLarge", 1016 L->getStartLoc(), L->getHeader()) 1017 << "Unable to unroll loop as directed by unroll(enable) " 1018 "pragma " 1019 "because unrolled size is too large."; 1020 }); 1021 } 1022 } 1023 return ExplicitUnroll; 1024 } 1025 assert(TripCount == 0 && 1026 "All cases when TripCount is constant should be covered here."); 1027 if (PragmaFullUnroll) 1028 ORE->emit([&]() { 1029 return OptimizationRemarkMissed( 1030 DEBUG_TYPE, "CantFullUnrollAsDirectedRuntimeTripCount", 1031 L->getStartLoc(), L->getHeader()) 1032 << "Unable to fully unroll loop as directed by unroll(full) " 1033 "pragma " 1034 "because loop has a runtime trip count."; 1035 }); 1036 1037 // 7th priority is runtime unrolling. 1038 // Don't unroll a runtime trip count loop when it is disabled. 1039 if (hasRuntimeUnrollDisablePragma(L)) { 1040 UP.Count = 0; 1041 return false; 1042 } 1043 1044 // Don't unroll a small upper bound loop unless user or TTI asked to do so. 1045 if (MaxTripCount && !UP.Force && MaxTripCount < UP.MaxUpperBound) { 1046 UP.Count = 0; 1047 return false; 1048 } 1049 1050 // Check if the runtime trip count is too small when profile is available. 1051 if (L->getHeader()->getParent()->hasProfileData()) { 1052 if (auto ProfileTripCount = getLoopEstimatedTripCount(L)) { 1053 if (*ProfileTripCount < FlatLoopTripCountThreshold) 1054 return false; 1055 else 1056 UP.AllowExpensiveTripCount = true; 1057 } 1058 } 1059 UP.Runtime |= PragmaEnableUnroll || PragmaCount > 0 || UserUnrollCount; 1060 if (!UP.Runtime) { 1061 LLVM_DEBUG( 1062 dbgs() << " will not try to unroll loop with runtime trip count " 1063 << "-unroll-runtime not given\n"); 1064 UP.Count = 0; 1065 return false; 1066 } 1067 if (UP.Count == 0) 1068 UP.Count = UP.DefaultUnrollRuntimeCount; 1069 1070 // Reduce unroll count to be the largest power-of-two factor of 1071 // the original count which satisfies the threshold limit. 1072 while (UP.Count != 0 && 1073 UCE.getUnrolledLoopSize(UP) > UP.PartialThreshold) 1074 UP.Count >>= 1; 1075 1076 #ifndef NDEBUG 1077 unsigned OrigCount = UP.Count; 1078 #endif 1079 1080 if (!UP.AllowRemainder && UP.Count != 0 && (TripMultiple % UP.Count) != 0) { 1081 while (UP.Count != 0 && TripMultiple % UP.Count != 0) 1082 UP.Count >>= 1; 1083 LLVM_DEBUG( 1084 dbgs() << "Remainder loop is restricted (that could architecture " 1085 "specific or because the loop contains a convergent " 1086 "instruction), so unroll count must divide the trip " 1087 "multiple, " 1088 << TripMultiple << ". Reducing unroll count from " << OrigCount 1089 << " to " << UP.Count << ".\n"); 1090 1091 using namespace ore; 1092 1093 if (unrollCountPragmaValue(L) > 0 && !UP.AllowRemainder) 1094 ORE->emit([&]() { 1095 return OptimizationRemarkMissed(DEBUG_TYPE, 1096 "DifferentUnrollCountFromDirected", 1097 L->getStartLoc(), L->getHeader()) 1098 << "Unable to unroll loop the number of times directed by " 1099 "unroll_count pragma because remainder loop is restricted " 1100 "(that could architecture specific or because the loop " 1101 "contains a convergent instruction) and so must have an " 1102 "unroll " 1103 "count that divides the loop trip multiple of " 1104 << NV("TripMultiple", TripMultiple) << ". Unrolling instead " 1105 << NV("UnrollCount", UP.Count) << " time(s)."; 1106 }); 1107 } 1108 1109 if (UP.Count > UP.MaxCount) 1110 UP.Count = UP.MaxCount; 1111 1112 if (MaxTripCount && UP.Count > MaxTripCount) 1113 UP.Count = MaxTripCount; 1114 1115 LLVM_DEBUG(dbgs() << " runtime unrolling with count: " << UP.Count 1116 << "\n"); 1117 if (UP.Count < 2) 1118 UP.Count = 0; 1119 return ExplicitUnroll; 1120 } 1121 1122 static LoopUnrollResult 1123 tryToUnrollLoop(Loop *L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution &SE, 1124 const TargetTransformInfo &TTI, AssumptionCache &AC, 1125 OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI, 1126 ProfileSummaryInfo *PSI, bool PreserveLCSSA, int OptLevel, 1127 bool OnlyFullUnroll, bool OnlyWhenForced, bool ForgetAllSCEV, 1128 std::optional<unsigned> ProvidedCount, 1129 std::optional<unsigned> ProvidedThreshold, 1130 std::optional<bool> ProvidedAllowPartial, 1131 std::optional<bool> ProvidedRuntime, 1132 std::optional<bool> ProvidedUpperBound, 1133 std::optional<bool> ProvidedAllowPeeling, 1134 std::optional<bool> ProvidedAllowProfileBasedPeeling, 1135 std::optional<unsigned> ProvidedFullUnrollMaxCount) { 1136 1137 LLVM_DEBUG(dbgs() << "Loop Unroll: F[" 1138 << L->getHeader()->getParent()->getName() << "] Loop %" 1139 << L->getHeader()->getName() << "\n"); 1140 TransformationMode TM = hasUnrollTransformation(L); 1141 if (TM & TM_Disable) 1142 return LoopUnrollResult::Unmodified; 1143 1144 // If this loop isn't forced to be unrolled, avoid unrolling it when the 1145 // parent loop has an explicit unroll-and-jam pragma. This is to prevent 1146 // automatic unrolling from interfering with the user requested 1147 // transformation. 1148 Loop *ParentL = L->getParentLoop(); 1149 if (ParentL != nullptr && 1150 hasUnrollAndJamTransformation(ParentL) == TM_ForcedByUser && 1151 hasUnrollTransformation(L) != TM_ForcedByUser) { 1152 LLVM_DEBUG(dbgs() << "Not unrolling loop since parent loop has" 1153 << " llvm.loop.unroll_and_jam.\n"); 1154 return LoopUnrollResult::Unmodified; 1155 } 1156 1157 // If this loop isn't forced to be unrolled, avoid unrolling it when the 1158 // loop has an explicit unroll-and-jam pragma. This is to prevent automatic 1159 // unrolling from interfering with the user requested transformation. 1160 if (hasUnrollAndJamTransformation(L) == TM_ForcedByUser && 1161 hasUnrollTransformation(L) != TM_ForcedByUser) { 1162 LLVM_DEBUG( 1163 dbgs() 1164 << " Not unrolling loop since it has llvm.loop.unroll_and_jam.\n"); 1165 return LoopUnrollResult::Unmodified; 1166 } 1167 1168 if (!L->isLoopSimplifyForm()) { 1169 LLVM_DEBUG( 1170 dbgs() << " Not unrolling loop which is not in loop-simplify form.\n"); 1171 return LoopUnrollResult::Unmodified; 1172 } 1173 1174 // When automatic unrolling is disabled, do not unroll unless overridden for 1175 // this loop. 1176 if (OnlyWhenForced && !(TM & TM_Enable)) 1177 return LoopUnrollResult::Unmodified; 1178 1179 bool OptForSize = L->getHeader()->getParent()->hasOptSize(); 1180 TargetTransformInfo::UnrollingPreferences UP = gatherUnrollingPreferences( 1181 L, SE, TTI, BFI, PSI, ORE, OptLevel, ProvidedThreshold, ProvidedCount, 1182 ProvidedAllowPartial, ProvidedRuntime, ProvidedUpperBound, 1183 ProvidedFullUnrollMaxCount); 1184 TargetTransformInfo::PeelingPreferences PP = gatherPeelingPreferences( 1185 L, SE, TTI, ProvidedAllowPeeling, ProvidedAllowProfileBasedPeeling, true); 1186 1187 // Exit early if unrolling is disabled. For OptForSize, we pick the loop size 1188 // as threshold later on. 1189 if (UP.Threshold == 0 && (!UP.Partial || UP.PartialThreshold == 0) && 1190 !OptForSize) 1191 return LoopUnrollResult::Unmodified; 1192 1193 SmallPtrSet<const Value *, 32> EphValues; 1194 CodeMetrics::collectEphemeralValues(L, &AC, EphValues); 1195 1196 UnrollCostEstimator UCE(L, TTI, EphValues, UP.BEInsns); 1197 if (!UCE.canUnroll()) { 1198 LLVM_DEBUG(dbgs() << " Not unrolling loop which contains instructions" 1199 << " which cannot be duplicated or have invalid cost.\n"); 1200 return LoopUnrollResult::Unmodified; 1201 } 1202 1203 unsigned LoopSize = UCE.getRolledLoopSize(); 1204 LLVM_DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n"); 1205 1206 // When optimizing for size, use LoopSize + 1 as threshold (we use < Threshold 1207 // later), to (fully) unroll loops, if it does not increase code size. 1208 if (OptForSize) 1209 UP.Threshold = std::max(UP.Threshold, LoopSize + 1); 1210 1211 if (UCE.NumInlineCandidates != 0) { 1212 LLVM_DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n"); 1213 return LoopUnrollResult::Unmodified; 1214 } 1215 1216 // Find the smallest exact trip count for any exit. This is an upper bound 1217 // on the loop trip count, but an exit at an earlier iteration is still 1218 // possible. An unroll by the smallest exact trip count guarantees that all 1219 // branches relating to at least one exit can be eliminated. This is unlike 1220 // the max trip count, which only guarantees that the backedge can be broken. 1221 unsigned TripCount = 0; 1222 unsigned TripMultiple = 1; 1223 SmallVector<BasicBlock *, 8> ExitingBlocks; 1224 L->getExitingBlocks(ExitingBlocks); 1225 for (BasicBlock *ExitingBlock : ExitingBlocks) 1226 if (unsigned TC = SE.getSmallConstantTripCount(L, ExitingBlock)) 1227 if (!TripCount || TC < TripCount) 1228 TripCount = TripMultiple = TC; 1229 1230 if (!TripCount) { 1231 // If no exact trip count is known, determine the trip multiple of either 1232 // the loop latch or the single exiting block. 1233 // TODO: Relax for multiple exits. 1234 BasicBlock *ExitingBlock = L->getLoopLatch(); 1235 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock)) 1236 ExitingBlock = L->getExitingBlock(); 1237 if (ExitingBlock) 1238 TripMultiple = SE.getSmallConstantTripMultiple(L, ExitingBlock); 1239 } 1240 1241 // If the loop contains a convergent operation, the prelude we'd add 1242 // to do the first few instructions before we hit the unrolled loop 1243 // is unsafe -- it adds a control-flow dependency to the convergent 1244 // operation. Therefore restrict remainder loop (try unrolling without). 1245 // 1246 // TODO: This is quite conservative. In practice, convergent_op() 1247 // is likely to be called unconditionally in the loop. In this 1248 // case, the program would be ill-formed (on most architectures) 1249 // unless n were the same on all threads in a thread group. 1250 // Assuming n is the same on all threads, any kind of unrolling is 1251 // safe. But currently llvm's notion of convergence isn't powerful 1252 // enough to express this. 1253 if (UCE.Convergent) 1254 UP.AllowRemainder = false; 1255 1256 // Try to find the trip count upper bound if we cannot find the exact trip 1257 // count. 1258 unsigned MaxTripCount = 0; 1259 bool MaxOrZero = false; 1260 if (!TripCount) { 1261 MaxTripCount = SE.getSmallConstantMaxTripCount(L); 1262 MaxOrZero = SE.isBackedgeTakenCountMaxOrZero(L); 1263 } 1264 1265 // computeUnrollCount() decides whether it is beneficial to use upper bound to 1266 // fully unroll the loop. 1267 bool UseUpperBound = false; 1268 bool IsCountSetExplicitly = computeUnrollCount( 1269 L, TTI, DT, LI, &AC, SE, EphValues, &ORE, TripCount, MaxTripCount, 1270 MaxOrZero, TripMultiple, UCE, UP, PP, UseUpperBound); 1271 if (!UP.Count) 1272 return LoopUnrollResult::Unmodified; 1273 1274 if (PP.PeelCount) { 1275 assert(UP.Count == 1 && "Cannot perform peel and unroll in the same step"); 1276 LLVM_DEBUG(dbgs() << "PEELING loop %" << L->getHeader()->getName() 1277 << " with iteration count " << PP.PeelCount << "!\n"); 1278 ORE.emit([&]() { 1279 return OptimizationRemark(DEBUG_TYPE, "Peeled", L->getStartLoc(), 1280 L->getHeader()) 1281 << " peeled loop by " << ore::NV("PeelCount", PP.PeelCount) 1282 << " iterations"; 1283 }); 1284 1285 ValueToValueMapTy VMap; 1286 if (peelLoop(L, PP.PeelCount, LI, &SE, DT, &AC, PreserveLCSSA, VMap)) { 1287 simplifyLoopAfterUnroll(L, true, LI, &SE, &DT, &AC, &TTI); 1288 // If the loop was peeled, we already "used up" the profile information 1289 // we had, so we don't want to unroll or peel again. 1290 if (PP.PeelProfiledIterations) 1291 L->setLoopAlreadyUnrolled(); 1292 return LoopUnrollResult::PartiallyUnrolled; 1293 } 1294 return LoopUnrollResult::Unmodified; 1295 } 1296 1297 // Do not attempt partial/runtime unrolling in FullLoopUnrolling 1298 if (OnlyFullUnroll && (UP.Count < TripCount || UP.Count < MaxTripCount)) { 1299 LLVM_DEBUG( 1300 dbgs() << "Not attempting partial/runtime unroll in FullLoopUnroll.\n"); 1301 return LoopUnrollResult::Unmodified; 1302 } 1303 1304 // At this point, UP.Runtime indicates that run-time unrolling is allowed. 1305 // However, we only want to actually perform it if we don't know the trip 1306 // count and the unroll count doesn't divide the known trip multiple. 1307 // TODO: This decision should probably be pushed up into 1308 // computeUnrollCount(). 1309 UP.Runtime &= TripCount == 0 && TripMultiple % UP.Count != 0; 1310 1311 // Save loop properties before it is transformed. 1312 MDNode *OrigLoopID = L->getLoopID(); 1313 1314 // Unroll the loop. 1315 Loop *RemainderLoop = nullptr; 1316 LoopUnrollResult UnrollResult = UnrollLoop( 1317 L, 1318 {UP.Count, UP.Force, UP.Runtime, UP.AllowExpensiveTripCount, 1319 UP.UnrollRemainder, ForgetAllSCEV}, 1320 LI, &SE, &DT, &AC, &TTI, &ORE, PreserveLCSSA, &RemainderLoop); 1321 if (UnrollResult == LoopUnrollResult::Unmodified) 1322 return LoopUnrollResult::Unmodified; 1323 1324 if (RemainderLoop) { 1325 std::optional<MDNode *> RemainderLoopID = 1326 makeFollowupLoopID(OrigLoopID, {LLVMLoopUnrollFollowupAll, 1327 LLVMLoopUnrollFollowupRemainder}); 1328 if (RemainderLoopID) 1329 RemainderLoop->setLoopID(*RemainderLoopID); 1330 } 1331 1332 if (UnrollResult != LoopUnrollResult::FullyUnrolled) { 1333 std::optional<MDNode *> NewLoopID = 1334 makeFollowupLoopID(OrigLoopID, {LLVMLoopUnrollFollowupAll, 1335 LLVMLoopUnrollFollowupUnrolled}); 1336 if (NewLoopID) { 1337 L->setLoopID(*NewLoopID); 1338 1339 // Do not setLoopAlreadyUnrolled if loop attributes have been specified 1340 // explicitly. 1341 return UnrollResult; 1342 } 1343 } 1344 1345 // If loop has an unroll count pragma or unrolled by explicitly set count 1346 // mark loop as unrolled to prevent unrolling beyond that requested. 1347 if (UnrollResult != LoopUnrollResult::FullyUnrolled && IsCountSetExplicitly) 1348 L->setLoopAlreadyUnrolled(); 1349 1350 return UnrollResult; 1351 } 1352 1353 namespace { 1354 1355 class LoopUnroll : public LoopPass { 1356 public: 1357 static char ID; // Pass ID, replacement for typeid 1358 1359 int OptLevel; 1360 1361 /// If false, use a cost model to determine whether unrolling of a loop is 1362 /// profitable. If true, only loops that explicitly request unrolling via 1363 /// metadata are considered. All other loops are skipped. 1364 bool OnlyWhenForced; 1365 1366 /// If false, when SCEV is invalidated, only forget everything in the 1367 /// top-most loop (call forgetTopMostLoop), of the loop being processed. 1368 /// Otherwise, forgetAllLoops and rebuild when needed next. 1369 bool ForgetAllSCEV; 1370 1371 std::optional<unsigned> ProvidedCount; 1372 std::optional<unsigned> ProvidedThreshold; 1373 std::optional<bool> ProvidedAllowPartial; 1374 std::optional<bool> ProvidedRuntime; 1375 std::optional<bool> ProvidedUpperBound; 1376 std::optional<bool> ProvidedAllowPeeling; 1377 std::optional<bool> ProvidedAllowProfileBasedPeeling; 1378 std::optional<unsigned> ProvidedFullUnrollMaxCount; 1379 1380 LoopUnroll(int OptLevel = 2, bool OnlyWhenForced = false, 1381 bool ForgetAllSCEV = false, 1382 std::optional<unsigned> Threshold = std::nullopt, 1383 std::optional<unsigned> Count = std::nullopt, 1384 std::optional<bool> AllowPartial = std::nullopt, 1385 std::optional<bool> Runtime = std::nullopt, 1386 std::optional<bool> UpperBound = std::nullopt, 1387 std::optional<bool> AllowPeeling = std::nullopt, 1388 std::optional<bool> AllowProfileBasedPeeling = std::nullopt, 1389 std::optional<unsigned> ProvidedFullUnrollMaxCount = std::nullopt) 1390 : LoopPass(ID), OptLevel(OptLevel), OnlyWhenForced(OnlyWhenForced), 1391 ForgetAllSCEV(ForgetAllSCEV), ProvidedCount(std::move(Count)), 1392 ProvidedThreshold(Threshold), ProvidedAllowPartial(AllowPartial), 1393 ProvidedRuntime(Runtime), ProvidedUpperBound(UpperBound), 1394 ProvidedAllowPeeling(AllowPeeling), 1395 ProvidedAllowProfileBasedPeeling(AllowProfileBasedPeeling), 1396 ProvidedFullUnrollMaxCount(ProvidedFullUnrollMaxCount) { 1397 initializeLoopUnrollPass(*PassRegistry::getPassRegistry()); 1398 } 1399 1400 bool runOnLoop(Loop *L, LPPassManager &LPM) override { 1401 if (skipLoop(L)) 1402 return false; 1403 1404 Function &F = *L->getHeader()->getParent(); 1405 1406 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 1407 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 1408 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 1409 const TargetTransformInfo &TTI = 1410 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 1411 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 1412 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis 1413 // pass. Function analyses need to be preserved across loop transformations 1414 // but ORE cannot be preserved (see comment before the pass definition). 1415 OptimizationRemarkEmitter ORE(&F); 1416 bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID); 1417 1418 LoopUnrollResult Result = tryToUnrollLoop( 1419 L, DT, LI, SE, TTI, AC, ORE, nullptr, nullptr, PreserveLCSSA, OptLevel, 1420 /*OnlyFullUnroll*/ false, OnlyWhenForced, ForgetAllSCEV, ProvidedCount, 1421 ProvidedThreshold, ProvidedAllowPartial, ProvidedRuntime, 1422 ProvidedUpperBound, ProvidedAllowPeeling, 1423 ProvidedAllowProfileBasedPeeling, ProvidedFullUnrollMaxCount); 1424 1425 if (Result == LoopUnrollResult::FullyUnrolled) 1426 LPM.markLoopAsDeleted(*L); 1427 1428 return Result != LoopUnrollResult::Unmodified; 1429 } 1430 1431 /// This transformation requires natural loop information & requires that 1432 /// loop preheaders be inserted into the CFG... 1433 void getAnalysisUsage(AnalysisUsage &AU) const override { 1434 AU.addRequired<AssumptionCacheTracker>(); 1435 AU.addRequired<TargetTransformInfoWrapperPass>(); 1436 // FIXME: Loop passes are required to preserve domtree, and for now we just 1437 // recreate dom info if anything gets unrolled. 1438 getLoopAnalysisUsage(AU); 1439 } 1440 }; 1441 1442 } // end anonymous namespace 1443 1444 char LoopUnroll::ID = 0; 1445 1446 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false) 1447 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1448 INITIALIZE_PASS_DEPENDENCY(LoopPass) 1449 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 1450 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false) 1451 1452 Pass *llvm::createLoopUnrollPass(int OptLevel, bool OnlyWhenForced, 1453 bool ForgetAllSCEV, int Threshold, int Count, 1454 int AllowPartial, int Runtime, int UpperBound, 1455 int AllowPeeling) { 1456 // TODO: It would make more sense for this function to take the optionals 1457 // directly, but that's dangerous since it would silently break out of tree 1458 // callers. 1459 return new LoopUnroll( 1460 OptLevel, OnlyWhenForced, ForgetAllSCEV, 1461 Threshold == -1 ? std::nullopt : std::optional<unsigned>(Threshold), 1462 Count == -1 ? std::nullopt : std::optional<unsigned>(Count), 1463 AllowPartial == -1 ? std::nullopt : std::optional<bool>(AllowPartial), 1464 Runtime == -1 ? std::nullopt : std::optional<bool>(Runtime), 1465 UpperBound == -1 ? std::nullopt : std::optional<bool>(UpperBound), 1466 AllowPeeling == -1 ? std::nullopt : std::optional<bool>(AllowPeeling)); 1467 } 1468 1469 PreservedAnalyses LoopFullUnrollPass::run(Loop &L, LoopAnalysisManager &AM, 1470 LoopStandardAnalysisResults &AR, 1471 LPMUpdater &Updater) { 1472 // For the new PM, we can't use OptimizationRemarkEmitter as an analysis 1473 // pass. Function analyses need to be preserved across loop transformations 1474 // but ORE cannot be preserved (see comment before the pass definition). 1475 OptimizationRemarkEmitter ORE(L.getHeader()->getParent()); 1476 1477 // Keep track of the previous loop structure so we can identify new loops 1478 // created by unrolling. 1479 Loop *ParentL = L.getParentLoop(); 1480 SmallPtrSet<Loop *, 4> OldLoops; 1481 if (ParentL) 1482 OldLoops.insert(ParentL->begin(), ParentL->end()); 1483 else 1484 OldLoops.insert(AR.LI.begin(), AR.LI.end()); 1485 1486 std::string LoopName = std::string(L.getName()); 1487 1488 bool Changed = 1489 tryToUnrollLoop(&L, AR.DT, &AR.LI, AR.SE, AR.TTI, AR.AC, ORE, 1490 /*BFI*/ nullptr, /*PSI*/ nullptr, 1491 /*PreserveLCSSA*/ true, OptLevel, /*OnlyFullUnroll*/ true, 1492 OnlyWhenForced, ForgetSCEV, /*Count*/ std::nullopt, 1493 /*Threshold*/ std::nullopt, /*AllowPartial*/ false, 1494 /*Runtime*/ false, /*UpperBound*/ false, 1495 /*AllowPeeling*/ true, 1496 /*AllowProfileBasedPeeling*/ false, 1497 /*FullUnrollMaxCount*/ std::nullopt) != 1498 LoopUnrollResult::Unmodified; 1499 if (!Changed) 1500 return PreservedAnalyses::all(); 1501 1502 // The parent must not be damaged by unrolling! 1503 #ifndef NDEBUG 1504 if (ParentL) 1505 ParentL->verifyLoop(); 1506 #endif 1507 1508 // Unrolling can do several things to introduce new loops into a loop nest: 1509 // - Full unrolling clones child loops within the current loop but then 1510 // removes the current loop making all of the children appear to be new 1511 // sibling loops. 1512 // 1513 // When a new loop appears as a sibling loop after fully unrolling, 1514 // its nesting structure has fundamentally changed and we want to revisit 1515 // it to reflect that. 1516 // 1517 // When unrolling has removed the current loop, we need to tell the 1518 // infrastructure that it is gone. 1519 // 1520 // Finally, we support a debugging/testing mode where we revisit child loops 1521 // as well. These are not expected to require further optimizations as either 1522 // they or the loop they were cloned from have been directly visited already. 1523 // But the debugging mode allows us to check this assumption. 1524 bool IsCurrentLoopValid = false; 1525 SmallVector<Loop *, 4> SibLoops; 1526 if (ParentL) 1527 SibLoops.append(ParentL->begin(), ParentL->end()); 1528 else 1529 SibLoops.append(AR.LI.begin(), AR.LI.end()); 1530 erase_if(SibLoops, [&](Loop *SibLoop) { 1531 if (SibLoop == &L) { 1532 IsCurrentLoopValid = true; 1533 return true; 1534 } 1535 1536 // Otherwise erase the loop from the list if it was in the old loops. 1537 return OldLoops.contains(SibLoop); 1538 }); 1539 Updater.addSiblingLoops(SibLoops); 1540 1541 if (!IsCurrentLoopValid) { 1542 Updater.markLoopAsDeleted(L, LoopName); 1543 } else { 1544 // We can only walk child loops if the current loop remained valid. 1545 if (UnrollRevisitChildLoops) { 1546 // Walk *all* of the child loops. 1547 SmallVector<Loop *, 4> ChildLoops(L.begin(), L.end()); 1548 Updater.addChildLoops(ChildLoops); 1549 } 1550 } 1551 1552 return getLoopPassPreservedAnalyses(); 1553 } 1554 1555 PreservedAnalyses LoopUnrollPass::run(Function &F, 1556 FunctionAnalysisManager &AM) { 1557 auto &LI = AM.getResult<LoopAnalysis>(F); 1558 // There are no loops in the function. Return before computing other expensive 1559 // analyses. 1560 if (LI.empty()) 1561 return PreservedAnalyses::all(); 1562 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F); 1563 auto &TTI = AM.getResult<TargetIRAnalysis>(F); 1564 auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 1565 auto &AC = AM.getResult<AssumptionAnalysis>(F); 1566 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 1567 1568 LoopAnalysisManager *LAM = nullptr; 1569 if (auto *LAMProxy = AM.getCachedResult<LoopAnalysisManagerFunctionProxy>(F)) 1570 LAM = &LAMProxy->getManager(); 1571 1572 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F); 1573 ProfileSummaryInfo *PSI = 1574 MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent()); 1575 auto *BFI = (PSI && PSI->hasProfileSummary()) ? 1576 &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr; 1577 1578 bool Changed = false; 1579 1580 // The unroller requires loops to be in simplified form, and also needs LCSSA. 1581 // Since simplification may add new inner loops, it has to run before the 1582 // legality and profitability checks. This means running the loop unroller 1583 // will simplify all loops, regardless of whether anything end up being 1584 // unrolled. 1585 for (const auto &L : LI) { 1586 Changed |= 1587 simplifyLoop(L, &DT, &LI, &SE, &AC, nullptr, false /* PreserveLCSSA */); 1588 Changed |= formLCSSARecursively(*L, DT, &LI, &SE); 1589 } 1590 1591 // Add the loop nests in the reverse order of LoopInfo. See method 1592 // declaration. 1593 SmallPriorityWorklist<Loop *, 4> Worklist; 1594 appendLoopsToWorklist(LI, Worklist); 1595 1596 while (!Worklist.empty()) { 1597 // Because the LoopInfo stores the loops in RPO, we walk the worklist 1598 // from back to front so that we work forward across the CFG, which 1599 // for unrolling is only needed to get optimization remarks emitted in 1600 // a forward order. 1601 Loop &L = *Worklist.pop_back_val(); 1602 #ifndef NDEBUG 1603 Loop *ParentL = L.getParentLoop(); 1604 #endif 1605 1606 // Check if the profile summary indicates that the profiled application 1607 // has a huge working set size, in which case we disable peeling to avoid 1608 // bloating it further. 1609 std::optional<bool> LocalAllowPeeling = UnrollOpts.AllowPeeling; 1610 if (PSI && PSI->hasHugeWorkingSetSize()) 1611 LocalAllowPeeling = false; 1612 std::string LoopName = std::string(L.getName()); 1613 // The API here is quite complex to call and we allow to select some 1614 // flavors of unrolling during construction time (by setting UnrollOpts). 1615 LoopUnrollResult Result = tryToUnrollLoop( 1616 &L, DT, &LI, SE, TTI, AC, ORE, BFI, PSI, 1617 /*PreserveLCSSA*/ true, UnrollOpts.OptLevel, /*OnlyFullUnroll*/ false, 1618 UnrollOpts.OnlyWhenForced, UnrollOpts.ForgetSCEV, 1619 /*Count*/ std::nullopt, 1620 /*Threshold*/ std::nullopt, UnrollOpts.AllowPartial, 1621 UnrollOpts.AllowRuntime, UnrollOpts.AllowUpperBound, LocalAllowPeeling, 1622 UnrollOpts.AllowProfileBasedPeeling, UnrollOpts.FullUnrollMaxCount); 1623 Changed |= Result != LoopUnrollResult::Unmodified; 1624 1625 // The parent must not be damaged by unrolling! 1626 #ifndef NDEBUG 1627 if (Result != LoopUnrollResult::Unmodified && ParentL) 1628 ParentL->verifyLoop(); 1629 #endif 1630 1631 // Clear any cached analysis results for L if we removed it completely. 1632 if (LAM && Result == LoopUnrollResult::FullyUnrolled) 1633 LAM->clear(L, LoopName); 1634 } 1635 1636 if (!Changed) 1637 return PreservedAnalyses::all(); 1638 1639 return getLoopPassPreservedAnalyses(); 1640 } 1641 1642 void LoopUnrollPass::printPipeline( 1643 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) { 1644 static_cast<PassInfoMixin<LoopUnrollPass> *>(this)->printPipeline( 1645 OS, MapClassName2PassName); 1646 OS << '<'; 1647 if (UnrollOpts.AllowPartial != std::nullopt) 1648 OS << (*UnrollOpts.AllowPartial ? "" : "no-") << "partial;"; 1649 if (UnrollOpts.AllowPeeling != std::nullopt) 1650 OS << (*UnrollOpts.AllowPeeling ? "" : "no-") << "peeling;"; 1651 if (UnrollOpts.AllowRuntime != std::nullopt) 1652 OS << (*UnrollOpts.AllowRuntime ? "" : "no-") << "runtime;"; 1653 if (UnrollOpts.AllowUpperBound != std::nullopt) 1654 OS << (*UnrollOpts.AllowUpperBound ? "" : "no-") << "upperbound;"; 1655 if (UnrollOpts.AllowProfileBasedPeeling != std::nullopt) 1656 OS << (*UnrollOpts.AllowProfileBasedPeeling ? "" : "no-") 1657 << "profile-peeling;"; 1658 if (UnrollOpts.FullUnrollMaxCount != std::nullopt) 1659 OS << "full-unroll-max=" << UnrollOpts.FullUnrollMaxCount << ';'; 1660 OS << 'O' << UnrollOpts.OptLevel; 1661 OS << '>'; 1662 } 1663