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