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.h" 16 #include "llvm/ADT/SetVector.h" 17 #include "llvm/Analysis/AssumptionCache.h" 18 #include "llvm/Analysis/CodeMetrics.h" 19 #include "llvm/Analysis/InstructionSimplify.h" 20 #include "llvm/Analysis/LoopPass.h" 21 #include "llvm/Analysis/ScalarEvolution.h" 22 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 23 #include "llvm/Analysis/TargetTransformInfo.h" 24 #include "llvm/IR/DataLayout.h" 25 #include "llvm/IR/DiagnosticInfo.h" 26 #include "llvm/IR/Dominators.h" 27 #include "llvm/IR/InstVisitor.h" 28 #include "llvm/IR/IntrinsicInst.h" 29 #include "llvm/IR/Metadata.h" 30 #include "llvm/Support/CommandLine.h" 31 #include "llvm/Support/Debug.h" 32 #include "llvm/Support/raw_ostream.h" 33 #include "llvm/Transforms/Utils/UnrollLoop.h" 34 #include <climits> 35 36 using namespace llvm; 37 38 #define DEBUG_TYPE "loop-unroll" 39 40 static cl::opt<unsigned> 41 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden, 42 cl::desc("The baseline cost threshold for loop unrolling")); 43 44 static cl::opt<unsigned> UnrollPercentDynamicCostSavedThreshold( 45 "unroll-percent-dynamic-cost-saved-threshold", cl::init(20), cl::Hidden, 46 cl::desc("The percentage of estimated dynamic cost which must be saved by " 47 "unrolling to allow unrolling up to the max threshold.")); 48 49 static cl::opt<unsigned> UnrollDynamicCostSavingsDiscount( 50 "unroll-dynamic-cost-savings-discount", cl::init(2000), cl::Hidden, 51 cl::desc("This is the amount discounted from the total unroll cost when " 52 "the unrolled form has a high dynamic cost savings (triggered by " 53 "the '-unroll-perecent-dynamic-cost-saved-threshold' flag).")); 54 55 static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze( 56 "unroll-max-iteration-count-to-analyze", cl::init(0), cl::Hidden, 57 cl::desc("Don't allow loop unrolling to simulate more than this number of" 58 "iterations when checking full unroll profitability")); 59 60 static cl::opt<unsigned> 61 UnrollCount("unroll-count", cl::init(0), cl::Hidden, 62 cl::desc("Use this unroll count for all loops including those with " 63 "unroll_count pragma values, for testing purposes")); 64 65 static cl::opt<bool> 66 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden, 67 cl::desc("Allows loops to be partially unrolled until " 68 "-unroll-threshold loop size is reached.")); 69 70 static cl::opt<bool> 71 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden, 72 cl::desc("Unroll loops with run-time trip counts")); 73 74 static cl::opt<unsigned> 75 PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden, 76 cl::desc("Unrolled size limit for loops with an unroll(full) or " 77 "unroll_count pragma.")); 78 79 namespace { 80 class LoopUnroll : public LoopPass { 81 public: 82 static char ID; // Pass ID, replacement for typeid 83 LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) { 84 CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T); 85 CurrentPercentDynamicCostSavedThreshold = 86 UnrollPercentDynamicCostSavedThreshold; 87 CurrentDynamicCostSavingsDiscount = UnrollDynamicCostSavingsDiscount; 88 CurrentCount = (C == -1) ? UnrollCount : unsigned(C); 89 CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P; 90 CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R; 91 92 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0); 93 UserPercentDynamicCostSavedThreshold = 94 (UnrollPercentDynamicCostSavedThreshold.getNumOccurrences() > 0); 95 UserDynamicCostSavingsDiscount = 96 (UnrollDynamicCostSavingsDiscount.getNumOccurrences() > 0); 97 UserAllowPartial = (P != -1) || 98 (UnrollAllowPartial.getNumOccurrences() > 0); 99 UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0); 100 UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0); 101 102 initializeLoopUnrollPass(*PassRegistry::getPassRegistry()); 103 } 104 105 /// A magic value for use with the Threshold parameter to indicate 106 /// that the loop unroll should be performed regardless of how much 107 /// code expansion would result. 108 static const unsigned NoThreshold = UINT_MAX; 109 110 // Threshold to use when optsize is specified (and there is no 111 // explicit -unroll-threshold). 112 static const unsigned OptSizeUnrollThreshold = 50; 113 114 // Default unroll count for loops with run-time trip count if 115 // -unroll-count is not set 116 static const unsigned UnrollRuntimeCount = 8; 117 118 unsigned CurrentCount; 119 unsigned CurrentThreshold; 120 unsigned CurrentPercentDynamicCostSavedThreshold; 121 unsigned CurrentDynamicCostSavingsDiscount; 122 bool CurrentAllowPartial; 123 bool CurrentRuntime; 124 125 // Flags for whether the 'current' settings are user-specified. 126 bool UserCount; 127 bool UserThreshold; 128 bool UserPercentDynamicCostSavedThreshold; 129 bool UserDynamicCostSavingsDiscount; 130 bool UserAllowPartial; 131 bool UserRuntime; 132 133 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 134 135 /// This transformation requires natural loop information & requires that 136 /// loop preheaders be inserted into the CFG... 137 /// 138 void getAnalysisUsage(AnalysisUsage &AU) const override { 139 AU.addRequired<AssumptionCacheTracker>(); 140 AU.addRequired<LoopInfoWrapperPass>(); 141 AU.addPreserved<LoopInfoWrapperPass>(); 142 AU.addRequiredID(LoopSimplifyID); 143 AU.addPreservedID(LoopSimplifyID); 144 AU.addRequiredID(LCSSAID); 145 AU.addPreservedID(LCSSAID); 146 AU.addRequired<ScalarEvolution>(); 147 AU.addPreserved<ScalarEvolution>(); 148 AU.addRequired<TargetTransformInfoWrapperPass>(); 149 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info. 150 // If loop unroll does not preserve dom info then LCSSA pass on next 151 // loop will receive invalid dom info. 152 // For now, recreate dom info, if loop is unrolled. 153 AU.addPreserved<DominatorTreeWrapperPass>(); 154 } 155 156 // Fill in the UnrollingPreferences parameter with values from the 157 // TargetTransformationInfo. 158 void getUnrollingPreferences(Loop *L, const TargetTransformInfo &TTI, 159 TargetTransformInfo::UnrollingPreferences &UP) { 160 UP.Threshold = CurrentThreshold; 161 UP.PercentDynamicCostSavedThreshold = 162 CurrentPercentDynamicCostSavedThreshold; 163 UP.DynamicCostSavingsDiscount = CurrentDynamicCostSavingsDiscount; 164 UP.OptSizeThreshold = OptSizeUnrollThreshold; 165 UP.PartialThreshold = CurrentThreshold; 166 UP.PartialOptSizeThreshold = OptSizeUnrollThreshold; 167 UP.Count = CurrentCount; 168 UP.MaxCount = UINT_MAX; 169 UP.Partial = CurrentAllowPartial; 170 UP.Runtime = CurrentRuntime; 171 UP.AllowExpensiveTripCount = false; 172 TTI.getUnrollingPreferences(L, UP); 173 } 174 175 // Select and return an unroll count based on parameters from 176 // user, unroll preferences, unroll pragmas, or a heuristic. 177 // SetExplicitly is set to true if the unroll count is is set by 178 // the user or a pragma rather than selected heuristically. 179 unsigned 180 selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll, 181 unsigned PragmaCount, 182 const TargetTransformInfo::UnrollingPreferences &UP, 183 bool &SetExplicitly); 184 185 // Select threshold values used to limit unrolling based on a 186 // total unrolled size. Parameters Threshold and PartialThreshold 187 // are set to the maximum unrolled size for fully and partially 188 // unrolled loops respectively. 189 void selectThresholds(const Loop *L, bool HasPragma, 190 const TargetTransformInfo::UnrollingPreferences &UP, 191 unsigned &Threshold, unsigned &PartialThreshold, 192 unsigned &PercentDynamicCostSavedThreshold, 193 unsigned &DynamicCostSavingsDiscount) { 194 // Determine the current unrolling threshold. While this is 195 // normally set from UnrollThreshold, it is overridden to a 196 // smaller value if the current function is marked as 197 // optimize-for-size, and the unroll threshold was not user 198 // specified. 199 Threshold = UserThreshold ? CurrentThreshold : UP.Threshold; 200 PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold; 201 PercentDynamicCostSavedThreshold = 202 UserPercentDynamicCostSavedThreshold 203 ? CurrentPercentDynamicCostSavedThreshold 204 : UP.PercentDynamicCostSavedThreshold; 205 DynamicCostSavingsDiscount = UserDynamicCostSavingsDiscount 206 ? CurrentDynamicCostSavingsDiscount 207 : UP.DynamicCostSavingsDiscount; 208 209 if (!UserThreshold && 210 L->getHeader()->getParent()->hasFnAttribute( 211 Attribute::OptimizeForSize)) { 212 Threshold = UP.OptSizeThreshold; 213 PartialThreshold = UP.PartialOptSizeThreshold; 214 } 215 if (HasPragma) { 216 // If the loop has an unrolling pragma, we want to be more 217 // aggressive with unrolling limits. Set thresholds to at 218 // least the PragmaTheshold value which is larger than the 219 // default limits. 220 if (Threshold != NoThreshold) 221 Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold); 222 if (PartialThreshold != NoThreshold) 223 PartialThreshold = 224 std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold); 225 } 226 } 227 bool canUnrollCompletely(Loop *L, unsigned Threshold, 228 unsigned PercentDynamicCostSavedThreshold, 229 unsigned DynamicCostSavingsDiscount, 230 uint64_t UnrolledCost, uint64_t RolledDynamicCost); 231 }; 232 } 233 234 char LoopUnroll::ID = 0; 235 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false) 236 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 237 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 238 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 239 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 240 INITIALIZE_PASS_DEPENDENCY(LCSSA) 241 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) 242 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false) 243 244 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial, 245 int Runtime) { 246 return new LoopUnroll(Threshold, Count, AllowPartial, Runtime); 247 } 248 249 Pass *llvm::createSimpleLoopUnrollPass() { 250 return llvm::createLoopUnrollPass(-1, -1, 0, 0); 251 } 252 253 namespace { 254 // This class is used to get an estimate of the optimization effects that we 255 // could get from complete loop unrolling. It comes from the fact that some 256 // loads might be replaced with concrete constant values and that could trigger 257 // a chain of instruction simplifications. 258 // 259 // E.g. we might have: 260 // int a[] = {0, 1, 0}; 261 // v = 0; 262 // for (i = 0; i < 3; i ++) 263 // v += b[i]*a[i]; 264 // If we completely unroll the loop, we would get: 265 // v = b[0]*a[0] + b[1]*a[1] + b[2]*a[2] 266 // Which then will be simplified to: 267 // v = b[0]* 0 + b[1]* 1 + b[2]* 0 268 // And finally: 269 // v = b[1] 270 class UnrolledInstAnalyzer : private InstVisitor<UnrolledInstAnalyzer, bool> { 271 typedef InstVisitor<UnrolledInstAnalyzer, bool> Base; 272 friend class InstVisitor<UnrolledInstAnalyzer, bool>; 273 struct SimplifiedAddress { 274 Value *Base = nullptr; 275 ConstantInt *Offset = nullptr; 276 }; 277 278 public: 279 UnrolledInstAnalyzer(unsigned Iteration, 280 DenseMap<Value *, Constant *> &SimplifiedValues, 281 const Loop *L, ScalarEvolution &SE) 282 : Iteration(Iteration), SimplifiedValues(SimplifiedValues), L(L), SE(SE) { 283 IterationNumber = SE.getConstant(APInt(64, Iteration)); 284 } 285 286 // Allow access to the initial visit method. 287 using Base::visit; 288 289 private: 290 /// \brief A cache of pointer bases and constant-folded offsets corresponding 291 /// to GEP (or derived from GEP) instructions. 292 /// 293 /// In order to find the base pointer one needs to perform non-trivial 294 /// traversal of the corresponding SCEV expression, so it's good to have the 295 /// results saved. 296 DenseMap<Value *, SimplifiedAddress> SimplifiedAddresses; 297 298 /// \brief Number of currently simulated iteration. 299 /// 300 /// If an expression is ConstAddress+Constant, then the Constant is 301 /// Start + Iteration*Step, where Start and Step could be obtained from 302 /// SCEVGEPCache. 303 unsigned Iteration; 304 305 /// \brief SCEV expression corresponding to number of currently simulated 306 /// iteration. 307 const SCEV *IterationNumber; 308 309 /// \brief A Value->Constant map for keeping values that we managed to 310 /// constant-fold on the given iteration. 311 /// 312 /// While we walk the loop instructions, we build up and maintain a mapping 313 /// of simplified values specific to this iteration. The idea is to propagate 314 /// any special information we have about loads that can be replaced with 315 /// constants after complete unrolling, and account for likely simplifications 316 /// post-unrolling. 317 DenseMap<Value *, Constant *> &SimplifiedValues; 318 319 const Loop *L; 320 ScalarEvolution &SE; 321 322 /// \brief Try to simplify instruction \param I using its SCEV expression. 323 /// 324 /// The idea is that some AddRec expressions become constants, which then 325 /// could trigger folding of other instructions. However, that only happens 326 /// for expressions whose start value is also constant, which isn't always the 327 /// case. In another common and important case the start value is just some 328 /// address (i.e. SCEVUnknown) - in this case we compute the offset and save 329 /// it along with the base address instead. 330 bool simplifyInstWithSCEV(Instruction *I) { 331 if (!SE.isSCEVable(I->getType())) 332 return false; 333 334 const SCEV *S = SE.getSCEV(I); 335 if (auto *SC = dyn_cast<SCEVConstant>(S)) { 336 SimplifiedValues[I] = SC->getValue(); 337 return true; 338 } 339 340 auto *AR = dyn_cast<SCEVAddRecExpr>(S); 341 if (!AR) 342 return false; 343 344 const SCEV *ValueAtIteration = AR->evaluateAtIteration(IterationNumber, SE); 345 // Check if the AddRec expression becomes a constant. 346 if (auto *SC = dyn_cast<SCEVConstant>(ValueAtIteration)) { 347 SimplifiedValues[I] = SC->getValue(); 348 return true; 349 } 350 351 // Check if the offset from the base address becomes a constant. 352 auto *Base = dyn_cast<SCEVUnknown>(SE.getPointerBase(S)); 353 if (!Base) 354 return false; 355 auto *Offset = 356 dyn_cast<SCEVConstant>(SE.getMinusSCEV(ValueAtIteration, Base)); 357 if (!Offset) 358 return false; 359 SimplifiedAddress Address; 360 Address.Base = Base->getValue(); 361 Address.Offset = Offset->getValue(); 362 SimplifiedAddresses[I] = Address; 363 return true; 364 } 365 366 /// Base case for the instruction visitor. 367 bool visitInstruction(Instruction &I) { 368 return simplifyInstWithSCEV(&I); 369 } 370 371 /// TODO: Add visitors for other instruction types, e.g. ZExt, SExt. 372 373 /// Try to simplify binary operator I. 374 /// 375 /// TODO: Probaly it's worth to hoist the code for estimating the 376 /// simplifications effects to a separate class, since we have a very similar 377 /// code in InlineCost already. 378 bool visitBinaryOperator(BinaryOperator &I) { 379 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 380 if (!isa<Constant>(LHS)) 381 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS)) 382 LHS = SimpleLHS; 383 if (!isa<Constant>(RHS)) 384 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS)) 385 RHS = SimpleRHS; 386 387 Value *SimpleV = nullptr; 388 const DataLayout &DL = I.getModule()->getDataLayout(); 389 if (auto FI = dyn_cast<FPMathOperator>(&I)) 390 SimpleV = 391 SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL); 392 else 393 SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL); 394 395 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) 396 SimplifiedValues[&I] = C; 397 398 if (SimpleV) 399 return true; 400 return Base::visitBinaryOperator(I); 401 } 402 403 /// Try to fold load I. 404 bool visitLoad(LoadInst &I) { 405 Value *AddrOp = I.getPointerOperand(); 406 407 auto AddressIt = SimplifiedAddresses.find(AddrOp); 408 if (AddressIt == SimplifiedAddresses.end()) 409 return false; 410 ConstantInt *SimplifiedAddrOp = AddressIt->second.Offset; 411 412 auto *GV = dyn_cast<GlobalVariable>(AddressIt->second.Base); 413 // We're only interested in loads that can be completely folded to a 414 // constant. 415 if (!GV || !GV->hasInitializer()) 416 return false; 417 418 ConstantDataSequential *CDS = 419 dyn_cast<ConstantDataSequential>(GV->getInitializer()); 420 if (!CDS) 421 return false; 422 423 int ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U; 424 assert(SimplifiedAddrOp->getValue().getActiveBits() < 64 && 425 "Unexpectedly large index value."); 426 int64_t Index = SimplifiedAddrOp->getSExtValue() / ElemSize; 427 if (Index >= CDS->getNumElements()) { 428 // FIXME: For now we conservatively ignore out of bound accesses, but 429 // we're allowed to perform the optimization in this case. 430 return false; 431 } 432 433 Constant *CV = CDS->getElementAsConstant(Index); 434 assert(CV && "Constant expected."); 435 SimplifiedValues[&I] = CV; 436 437 return true; 438 } 439 }; 440 } // namespace 441 442 443 namespace { 444 struct EstimatedUnrollCost { 445 /// \brief The estimated cost after unrolling. 446 unsigned UnrolledCost; 447 448 /// \brief The estimated dynamic cost of executing the instructions in the 449 /// rolled form. 450 unsigned RolledDynamicCost; 451 }; 452 } 453 454 /// \brief Figure out if the loop is worth full unrolling. 455 /// 456 /// Complete loop unrolling can make some loads constant, and we need to know 457 /// if that would expose any further optimization opportunities. This routine 458 /// estimates this optimization. It assigns computed number of instructions, 459 /// that potentially might be optimized away, to 460 /// NumberOfOptimizedInstructions, and total number of instructions to 461 /// UnrolledLoopSize (not counting blocks that won't be reached, if we were 462 /// able to compute the condition). 463 /// \returns false if we can't analyze the loop, or if we discovered that 464 /// unrolling won't give anything. Otherwise, returns true. 465 Optional<EstimatedUnrollCost> 466 analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, ScalarEvolution &SE, 467 const TargetTransformInfo &TTI, 468 unsigned MaxUnrolledLoopSize) { 469 // We want to be able to scale offsets by the trip count and add more offsets 470 // to them without checking for overflows, and we already don't want to 471 // analyze *massive* trip counts, so we force the max to be reasonably small. 472 assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) && 473 "The unroll iterations max is too large!"); 474 475 // Don't simulate loops with a big or unknown tripcount 476 if (!UnrollMaxIterationsCountToAnalyze || !TripCount || 477 TripCount > UnrollMaxIterationsCountToAnalyze) 478 return None; 479 480 SmallSetVector<BasicBlock *, 16> BBWorklist; 481 DenseMap<Value *, Constant *> SimplifiedValues; 482 483 // The estimated cost of the unrolled form of the loop. We try to estimate 484 // this by simplifying as much as we can while computing the estimate. 485 unsigned UnrolledCost = 0; 486 // We also track the estimated dynamic (that is, actually executed) cost in 487 // the rolled form. This helps identify cases when the savings from unrolling 488 // aren't just exposing dead control flows, but actual reduced dynamic 489 // instructions due to the simplifications which we expect to occur after 490 // unrolling. 491 unsigned RolledDynamicCost = 0; 492 493 // Simulate execution of each iteration of the loop counting instructions, 494 // which would be simplified. 495 // Since the same load will take different values on different iterations, 496 // we literally have to go through all loop's iterations. 497 for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) { 498 SimplifiedValues.clear(); 499 UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, L, SE); 500 501 BBWorklist.clear(); 502 BBWorklist.insert(L->getHeader()); 503 // Note that we *must not* cache the size, this loop grows the worklist. 504 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) { 505 BasicBlock *BB = BBWorklist[Idx]; 506 507 // Visit all instructions in the given basic block and try to simplify 508 // it. We don't change the actual IR, just count optimization 509 // opportunities. 510 for (Instruction &I : *BB) { 511 unsigned InstCost = TTI.getUserCost(&I); 512 513 // Visit the instruction to analyze its loop cost after unrolling, 514 // and if the visitor returns false, include this instruction in the 515 // unrolled cost. 516 if (!Analyzer.visit(I)) 517 UnrolledCost += InstCost; 518 519 // Also track this instructions expected cost when executing the rolled 520 // loop form. 521 RolledDynamicCost += InstCost; 522 523 // If unrolled body turns out to be too big, bail out. 524 if (UnrolledCost > MaxUnrolledLoopSize) 525 return None; 526 } 527 528 // Add BB's successors to the worklist. 529 for (BasicBlock *Succ : successors(BB)) 530 if (L->contains(Succ)) 531 BBWorklist.insert(Succ); 532 } 533 534 // If we found no optimization opportunities on the first iteration, we 535 // won't find them on later ones too. 536 if (UnrolledCost == RolledDynamicCost) 537 return None; 538 } 539 return {{UnrolledCost, RolledDynamicCost}}; 540 } 541 542 /// ApproximateLoopSize - Approximate the size of the loop. 543 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls, 544 bool &NotDuplicatable, 545 const TargetTransformInfo &TTI, 546 AssumptionCache *AC) { 547 SmallPtrSet<const Value *, 32> EphValues; 548 CodeMetrics::collectEphemeralValues(L, AC, EphValues); 549 550 CodeMetrics Metrics; 551 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 552 I != E; ++I) 553 Metrics.analyzeBasicBlock(*I, TTI, EphValues); 554 NumCalls = Metrics.NumInlineCandidates; 555 NotDuplicatable = Metrics.notDuplicatable; 556 557 unsigned LoopSize = Metrics.NumInsts; 558 559 // Don't allow an estimate of size zero. This would allows unrolling of loops 560 // with huge iteration counts, which is a compile time problem even if it's 561 // not a problem for code quality. Also, the code using this size may assume 562 // that each loop has at least three instructions (likely a conditional 563 // branch, a comparison feeding that branch, and some kind of loop increment 564 // feeding that comparison instruction). 565 LoopSize = std::max(LoopSize, 3u); 566 567 return LoopSize; 568 } 569 570 // Returns the loop hint metadata node with the given name (for example, 571 // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is 572 // returned. 573 static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) { 574 if (MDNode *LoopID = L->getLoopID()) 575 return GetUnrollMetadata(LoopID, Name); 576 return nullptr; 577 } 578 579 // Returns true if the loop has an unroll(full) pragma. 580 static bool HasUnrollFullPragma(const Loop *L) { 581 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full"); 582 } 583 584 // Returns true if the loop has an unroll(disable) pragma. 585 static bool HasUnrollDisablePragma(const Loop *L) { 586 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable"); 587 } 588 589 // Returns true if the loop has an runtime unroll(disable) pragma. 590 static bool HasRuntimeUnrollDisablePragma(const Loop *L) { 591 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable"); 592 } 593 594 // If loop has an unroll_count pragma return the (necessarily 595 // positive) value from the pragma. Otherwise return 0. 596 static unsigned UnrollCountPragmaValue(const Loop *L) { 597 MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count"); 598 if (MD) { 599 assert(MD->getNumOperands() == 2 && 600 "Unroll count hint metadata should have two operands."); 601 unsigned Count = 602 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue(); 603 assert(Count >= 1 && "Unroll count must be positive."); 604 return Count; 605 } 606 return 0; 607 } 608 609 // Remove existing unroll metadata and add unroll disable metadata to 610 // indicate the loop has already been unrolled. This prevents a loop 611 // from being unrolled more than is directed by a pragma if the loop 612 // unrolling pass is run more than once (which it generally is). 613 static void SetLoopAlreadyUnrolled(Loop *L) { 614 MDNode *LoopID = L->getLoopID(); 615 if (!LoopID) return; 616 617 // First remove any existing loop unrolling metadata. 618 SmallVector<Metadata *, 4> MDs; 619 // Reserve first location for self reference to the LoopID metadata node. 620 MDs.push_back(nullptr); 621 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 622 bool IsUnrollMetadata = false; 623 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 624 if (MD) { 625 const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 626 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll."); 627 } 628 if (!IsUnrollMetadata) 629 MDs.push_back(LoopID->getOperand(i)); 630 } 631 632 // Add unroll(disable) metadata to disable future unrolling. 633 LLVMContext &Context = L->getHeader()->getContext(); 634 SmallVector<Metadata *, 1> DisableOperands; 635 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable")); 636 MDNode *DisableNode = MDNode::get(Context, DisableOperands); 637 MDs.push_back(DisableNode); 638 639 MDNode *NewLoopID = MDNode::get(Context, MDs); 640 // Set operand 0 to refer to the loop id itself. 641 NewLoopID->replaceOperandWith(0, NewLoopID); 642 L->setLoopID(NewLoopID); 643 } 644 645 bool LoopUnroll::canUnrollCompletely(Loop *L, unsigned Threshold, 646 unsigned PercentDynamicCostSavedThreshold, 647 unsigned DynamicCostSavingsDiscount, 648 uint64_t UnrolledCost, 649 uint64_t RolledDynamicCost) { 650 651 if (Threshold == NoThreshold) { 652 DEBUG(dbgs() << " Can fully unroll, because no threshold is set.\n"); 653 return true; 654 } 655 656 if (UnrolledCost <= Threshold) { 657 DEBUG(dbgs() << " Can fully unroll, because unrolled cost: " 658 << UnrolledCost << "<" << Threshold << "\n"); 659 return true; 660 } 661 662 assert(UnrolledCost && "UnrolledCost can't be 0 at this point."); 663 assert(RolledDynamicCost >= UnrolledCost && 664 "Cannot have a higher unrolled cost than a rolled cost!"); 665 666 // Compute the percentage of the dynamic cost in the rolled form that is 667 // saved when unrolled. If unrolling dramatically reduces the estimated 668 // dynamic cost of the loop, we use a higher threshold to allow more 669 // unrolling. 670 unsigned PercentDynamicCostSaved = 671 (uint64_t)(RolledDynamicCost - UnrolledCost) * 100ull / RolledDynamicCost; 672 673 if (PercentDynamicCostSaved >= PercentDynamicCostSavedThreshold && 674 (int64_t)UnrolledCost - (int64_t)DynamicCostSavingsDiscount <= 675 (int64_t)Threshold) { 676 DEBUG(dbgs() << " Can fully unroll, because unrolling will reduce the " 677 "expected dynamic cost by " << PercentDynamicCostSaved 678 << "% (threshold: " << PercentDynamicCostSavedThreshold 679 << "%)\n" 680 << " and the unrolled cost (" << UnrolledCost 681 << ") is less than the max threshold (" 682 << DynamicCostSavingsDiscount << ").\n"); 683 return true; 684 } 685 686 DEBUG(dbgs() << " Too large to fully unroll:\n"); 687 DEBUG(dbgs() << " Threshold: " << Threshold << "\n"); 688 DEBUG(dbgs() << " Max threshold: " << DynamicCostSavingsDiscount << "\n"); 689 DEBUG(dbgs() << " Percent cost saved threshold: " 690 << PercentDynamicCostSavedThreshold << "%\n"); 691 DEBUG(dbgs() << " Unrolled cost: " << UnrolledCost << "\n"); 692 DEBUG(dbgs() << " Rolled dynamic cost: " << RolledDynamicCost << "\n"); 693 DEBUG(dbgs() << " Percent cost saved: " << PercentDynamicCostSaved 694 << "\n"); 695 return false; 696 } 697 698 unsigned LoopUnroll::selectUnrollCount( 699 const Loop *L, unsigned TripCount, bool PragmaFullUnroll, 700 unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP, 701 bool &SetExplicitly) { 702 SetExplicitly = true; 703 704 // User-specified count (either as a command-line option or 705 // constructor parameter) has highest precedence. 706 unsigned Count = UserCount ? CurrentCount : 0; 707 708 // If there is no user-specified count, unroll pragmas have the next 709 // highest precendence. 710 if (Count == 0) { 711 if (PragmaCount) { 712 Count = PragmaCount; 713 } else if (PragmaFullUnroll) { 714 Count = TripCount; 715 } 716 } 717 718 if (Count == 0) 719 Count = UP.Count; 720 721 if (Count == 0) { 722 SetExplicitly = false; 723 if (TripCount == 0) 724 // Runtime trip count. 725 Count = UnrollRuntimeCount; 726 else 727 // Conservative heuristic: if we know the trip count, see if we can 728 // completely unroll (subject to the threshold, checked below); otherwise 729 // try to find greatest modulo of the trip count which is still under 730 // threshold value. 731 Count = TripCount; 732 } 733 if (TripCount && Count > TripCount) 734 return TripCount; 735 return Count; 736 } 737 738 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) { 739 if (skipOptnoneFunction(L)) 740 return false; 741 742 Function &F = *L->getHeader()->getParent(); 743 744 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 745 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>(); 746 const TargetTransformInfo &TTI = 747 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 748 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 749 750 BasicBlock *Header = L->getHeader(); 751 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName() 752 << "] Loop %" << Header->getName() << "\n"); 753 754 if (HasUnrollDisablePragma(L)) { 755 return false; 756 } 757 bool PragmaFullUnroll = HasUnrollFullPragma(L); 758 unsigned PragmaCount = UnrollCountPragmaValue(L); 759 bool HasPragma = PragmaFullUnroll || PragmaCount > 0; 760 761 TargetTransformInfo::UnrollingPreferences UP; 762 getUnrollingPreferences(L, TTI, UP); 763 764 // Find trip count and trip multiple if count is not available 765 unsigned TripCount = 0; 766 unsigned TripMultiple = 1; 767 // If there are multiple exiting blocks but one of them is the latch, use the 768 // latch for the trip count estimation. Otherwise insist on a single exiting 769 // block for the trip count estimation. 770 BasicBlock *ExitingBlock = L->getLoopLatch(); 771 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock)) 772 ExitingBlock = L->getExitingBlock(); 773 if (ExitingBlock) { 774 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock); 775 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock); 776 } 777 778 // Select an initial unroll count. This may be reduced later based 779 // on size thresholds. 780 bool CountSetExplicitly; 781 unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll, 782 PragmaCount, UP, CountSetExplicitly); 783 784 unsigned NumInlineCandidates; 785 bool notDuplicatable; 786 unsigned LoopSize = 787 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC); 788 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n"); 789 790 // When computing the unrolled size, note that the conditional branch on the 791 // backedge and the comparison feeding it are not replicated like the rest of 792 // the loop body (which is why 2 is subtracted). 793 uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2; 794 if (notDuplicatable) { 795 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable" 796 << " instructions.\n"); 797 return false; 798 } 799 if (NumInlineCandidates != 0) { 800 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n"); 801 return false; 802 } 803 804 unsigned Threshold, PartialThreshold; 805 unsigned PercentDynamicCostSavedThreshold; 806 unsigned DynamicCostSavingsDiscount; 807 selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold, 808 PercentDynamicCostSavedThreshold, 809 DynamicCostSavingsDiscount); 810 811 // Given Count, TripCount and thresholds determine the type of 812 // unrolling which is to be performed. 813 enum { Full = 0, Partial = 1, Runtime = 2 }; 814 int Unrolling; 815 if (TripCount && Count == TripCount) { 816 Unrolling = Partial; 817 // If the loop is really small, we don't need to run an expensive analysis. 818 if (canUnrollCompletely(L, Threshold, 100, DynamicCostSavingsDiscount, 819 UnrolledSize, UnrolledSize)) { 820 Unrolling = Full; 821 } else { 822 // The loop isn't that small, but we still can fully unroll it if that 823 // helps to remove a significant number of instructions. 824 // To check that, run additional analysis on the loop. 825 if (Optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost( 826 L, TripCount, *SE, TTI, Threshold + DynamicCostSavingsDiscount)) 827 if (canUnrollCompletely(L, Threshold, PercentDynamicCostSavedThreshold, 828 DynamicCostSavingsDiscount, Cost->UnrolledCost, 829 Cost->RolledDynamicCost)) { 830 Unrolling = Full; 831 } 832 } 833 } else if (TripCount && Count < TripCount) { 834 Unrolling = Partial; 835 } else { 836 Unrolling = Runtime; 837 } 838 839 // Reduce count based on the type of unrolling and the threshold values. 840 unsigned OriginalCount = Count; 841 bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime; 842 if (HasRuntimeUnrollDisablePragma(L)) { 843 AllowRuntime = false; 844 } 845 if (Unrolling == Partial) { 846 bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial; 847 if (!AllowPartial && !CountSetExplicitly) { 848 DEBUG(dbgs() << " will not try to unroll partially because " 849 << "-unroll-allow-partial not given\n"); 850 return false; 851 } 852 if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) { 853 // Reduce unroll count to be modulo of TripCount for partial unrolling. 854 Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2); 855 while (Count != 0 && TripCount % Count != 0) 856 Count--; 857 } 858 } else if (Unrolling == Runtime) { 859 if (!AllowRuntime && !CountSetExplicitly) { 860 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count " 861 << "-unroll-runtime not given\n"); 862 return false; 863 } 864 // Reduce unroll count to be the largest power-of-two factor of 865 // the original count which satisfies the threshold limit. 866 while (Count != 0 && UnrolledSize > PartialThreshold) { 867 Count >>= 1; 868 UnrolledSize = (LoopSize-2) * Count + 2; 869 } 870 if (Count > UP.MaxCount) 871 Count = UP.MaxCount; 872 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n"); 873 } 874 875 if (HasPragma) { 876 if (PragmaCount != 0) 877 // If loop has an unroll count pragma mark loop as unrolled to prevent 878 // unrolling beyond that requested by the pragma. 879 SetLoopAlreadyUnrolled(L); 880 881 // Emit optimization remarks if we are unable to unroll the loop 882 // as directed by a pragma. 883 DebugLoc LoopLoc = L->getStartLoc(); 884 Function *F = Header->getParent(); 885 LLVMContext &Ctx = F->getContext(); 886 if (PragmaFullUnroll && PragmaCount == 0) { 887 if (TripCount && Count != TripCount) { 888 emitOptimizationRemarkMissed( 889 Ctx, DEBUG_TYPE, *F, LoopLoc, 890 "Unable to fully unroll loop as directed by unroll(full) pragma " 891 "because unrolled size is too large."); 892 } else if (!TripCount) { 893 emitOptimizationRemarkMissed( 894 Ctx, DEBUG_TYPE, *F, LoopLoc, 895 "Unable to fully unroll loop as directed by unroll(full) pragma " 896 "because loop has a runtime trip count."); 897 } 898 } else if (PragmaCount > 0 && Count != OriginalCount) { 899 emitOptimizationRemarkMissed( 900 Ctx, DEBUG_TYPE, *F, LoopLoc, 901 "Unable to unroll loop the number of times directed by " 902 "unroll_count pragma because unrolled size is too large."); 903 } 904 } 905 906 if (Unrolling != Full && Count < 2) { 907 // Partial unrolling by 1 is a nop. For full unrolling, a factor 908 // of 1 makes sense because loop control can be eliminated. 909 return false; 910 } 911 912 // Unroll the loop. 913 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, UP.AllowExpensiveTripCount, 914 TripMultiple, LI, this, &LPM, &AC)) 915 return false; 916 917 return true; 918 } 919