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