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