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 unsigned UnrolledCost, unsigned 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 /// \brief SCEV expressions visitor used for finding expressions that would 255 /// become constants if the loop L is unrolled. 256 struct FindConstantPointers { 257 /// \brief Shows whether the expression is ConstAddress+Constant or not. 258 bool IndexIsConstant; 259 260 /// \brief Used for filtering out SCEV expressions with two or more AddRec 261 /// subexpressions. 262 /// 263 /// Used to filter out complicated SCEV expressions, having several AddRec 264 /// sub-expressions. We don't handle them, because unrolling one loop 265 /// would help to replace only one of these inductions with a constant, and 266 /// consequently, the expression would remain non-constant. 267 bool HaveSeenAR; 268 269 /// \brief If the SCEV expression becomes ConstAddress+Constant, this value 270 /// holds ConstAddress. Otherwise, it's nullptr. 271 Value *BaseAddress; 272 273 /// \brief The loop, which we try to completely unroll. 274 const Loop *L; 275 276 ScalarEvolution &SE; 277 278 FindConstantPointers(const Loop *L, ScalarEvolution &SE) 279 : IndexIsConstant(true), HaveSeenAR(false), BaseAddress(nullptr), 280 L(L), SE(SE) {} 281 282 /// Examine the given expression S and figure out, if it can be a part of an 283 /// expression, that could become a constant after the loop is unrolled. 284 /// The routine sets IndexIsConstant and HaveSeenAR according to the analysis 285 /// results. 286 /// \returns true if we need to examine subexpressions, and false otherwise. 287 bool follow(const SCEV *S) { 288 if (const SCEVUnknown *SC = dyn_cast<SCEVUnknown>(S)) { 289 // We've reached the leaf node of SCEV, it's most probably just a 290 // variable. 291 // If it's the only one SCEV-subexpression, then it might be a base 292 // address of an index expression. 293 // If we've already recorded base address, then just give up on this SCEV 294 // - it's too complicated. 295 if (BaseAddress) { 296 IndexIsConstant = false; 297 return false; 298 } 299 BaseAddress = SC->getValue(); 300 return false; 301 } 302 if (isa<SCEVConstant>(S)) 303 return false; 304 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { 305 // If the current SCEV expression is AddRec, and its loop isn't the loop 306 // we are about to unroll, then we won't get a constant address after 307 // unrolling, and thus, won't be able to eliminate the load. 308 if (AR->getLoop() != L) { 309 IndexIsConstant = false; 310 return false; 311 } 312 // We don't handle multiple AddRecs here, so give up in this case. 313 if (HaveSeenAR) { 314 IndexIsConstant = false; 315 return false; 316 } 317 HaveSeenAR = true; 318 } 319 320 // Continue traversal. 321 return true; 322 } 323 bool isDone() const { return !IndexIsConstant; } 324 }; 325 } // End anonymous namespace. 326 327 namespace { 328 /// \brief A cache of SCEV results used to optimize repeated queries to SCEV on 329 /// the same set of instructions. 330 /// 331 /// The primary cost this saves is the cost of checking the validity of a SCEV 332 /// every time it is looked up. However, in some cases we can provide a reduced 333 /// and especially useful model for an instruction based upon SCEV that is 334 /// non-trivial to compute but more useful to clients. 335 class SCEVCache { 336 public: 337 /// \brief Struct to represent a GEP whose start and step are known fixed 338 /// offsets from a base address due to SCEV's analysis. 339 struct GEPDescriptor { 340 Value *BaseAddr = nullptr; 341 unsigned Start = 0; 342 unsigned Step = 0; 343 }; 344 345 Optional<GEPDescriptor> getGEPDescriptor(GetElementPtrInst *GEP); 346 347 SCEVCache(const Loop &L, ScalarEvolution &SE) : L(L), SE(SE) {} 348 349 private: 350 const Loop &L; 351 ScalarEvolution &SE; 352 353 SmallDenseMap<GetElementPtrInst *, GEPDescriptor> GEPDescriptors; 354 }; 355 } // End anonymous namespace. 356 357 /// \brief Get a simplified descriptor for a GEP instruction. 358 /// 359 /// Where possible, this produces a simplified descriptor for a GEP instruction 360 /// using SCEV analysis of the containing loop. If this isn't possible, it 361 /// returns an empty optional. 362 /// 363 /// The model is a base address, an initial offset, and a per-iteration step. 364 /// This fits very common patterns of GEPs inside loops and is something we can 365 /// use to simulate the behavior of a particular iteration of a loop. 366 /// 367 /// This is a cached interface. The first call may do non-trivial work to 368 /// compute the result, but all subsequent calls will return a fast answer 369 /// based on a cached result. This includes caching negative results. 370 Optional<SCEVCache::GEPDescriptor> 371 SCEVCache::getGEPDescriptor(GetElementPtrInst *GEP) { 372 decltype(GEPDescriptors)::iterator It; 373 bool Inserted; 374 375 std::tie(It, Inserted) = GEPDescriptors.insert({GEP, {}}); 376 377 if (!Inserted) { 378 if (!It->second.BaseAddr) 379 return None; 380 381 return It->second; 382 } 383 384 // We've inserted a new record into the cache, so compute the GEP descriptor 385 // if possible. 386 Value *V = cast<Value>(GEP); 387 if (!SE.isSCEVable(V->getType())) 388 return None; 389 const SCEV *S = SE.getSCEV(V); 390 391 // FIXME: It'd be nice if the worklist and set used by the 392 // SCEVTraversal could be re-used between loop iterations, but the 393 // interface doesn't support that. There is no way to clear the visited 394 // sets between uses. 395 FindConstantPointers Visitor(&L, SE); 396 SCEVTraversal<FindConstantPointers> T(Visitor); 397 398 // Try to find (BaseAddress+Step+Offset) tuple. 399 // If succeeded, save it to the cache - it might help in folding 400 // loads. 401 T.visitAll(S); 402 if (!Visitor.IndexIsConstant || !Visitor.BaseAddress) 403 return None; 404 405 const SCEV *BaseAddrSE = SE.getSCEV(Visitor.BaseAddress); 406 if (BaseAddrSE->getType() != S->getType()) 407 return None; 408 const SCEV *OffSE = SE.getMinusSCEV(S, BaseAddrSE); 409 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OffSE); 410 411 if (!AR) 412 return None; 413 414 const SCEVConstant *StepSE = 415 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)); 416 const SCEVConstant *StartSE = dyn_cast<SCEVConstant>(AR->getStart()); 417 if (!StepSE || !StartSE) 418 return None; 419 420 // Check and skip caching if doing so would require lots of bits to 421 // avoid overflow. 422 APInt Start = StartSE->getValue()->getValue(); 423 APInt Step = StepSE->getValue()->getValue(); 424 if (Start.getActiveBits() > 32 || Step.getActiveBits() > 32) 425 return None; 426 427 // We found a cacheable SCEV model for the GEP. 428 It->second.BaseAddr = Visitor.BaseAddress; 429 It->second.Start = Start.getLimitedValue(); 430 It->second.Step = Step.getLimitedValue(); 431 return It->second; 432 } 433 434 namespace { 435 // This class is used to get an estimate of the optimization effects that we 436 // could get from complete loop unrolling. It comes from the fact that some 437 // loads might be replaced with concrete constant values and that could trigger 438 // a chain of instruction simplifications. 439 // 440 // E.g. we might have: 441 // int a[] = {0, 1, 0}; 442 // v = 0; 443 // for (i = 0; i < 3; i ++) 444 // v += b[i]*a[i]; 445 // If we completely unroll the loop, we would get: 446 // v = b[0]*a[0] + b[1]*a[1] + b[2]*a[2] 447 // Which then will be simplified to: 448 // v = b[0]* 0 + b[1]* 1 + b[2]* 0 449 // And finally: 450 // v = b[1] 451 class UnrolledInstAnalyzer : private InstVisitor<UnrolledInstAnalyzer, bool> { 452 typedef InstVisitor<UnrolledInstAnalyzer, bool> Base; 453 friend class InstVisitor<UnrolledInstAnalyzer, bool>; 454 455 public: 456 UnrolledInstAnalyzer(unsigned Iteration, 457 DenseMap<Value *, Constant *> &SimplifiedValues, 458 SCEVCache &SC) 459 : Iteration(Iteration), SimplifiedValues(SimplifiedValues), SC(SC) {} 460 461 // Allow access to the initial visit method. 462 using Base::visit; 463 464 private: 465 /// \brief Number of currently simulated iteration. 466 /// 467 /// If an expression is ConstAddress+Constant, then the Constant is 468 /// Start + Iteration*Step, where Start and Step could be obtained from 469 /// SCEVGEPCache. 470 unsigned Iteration; 471 472 // While we walk the loop instructions, we we build up and maintain a mapping 473 // of simplified values specific to this iteration. The idea is to propagate 474 // any special information we have about loads that can be replaced with 475 // constants after complete unrolling, and account for likely simplifications 476 // post-unrolling. 477 DenseMap<Value *, Constant *> &SimplifiedValues; 478 479 // We use a cache to wrap all our SCEV queries. 480 SCEVCache &SC; 481 482 /// Base case for the instruction visitor. 483 bool visitInstruction(Instruction &I) { return false; }; 484 485 /// TODO: Add visitors for other instruction types, e.g. ZExt, SExt. 486 487 /// Try to simplify binary operator I. 488 /// 489 /// TODO: Probaly it's worth to hoist the code for estimating the 490 /// simplifications effects to a separate class, since we have a very similar 491 /// code in InlineCost already. 492 bool visitBinaryOperator(BinaryOperator &I) { 493 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 494 if (!isa<Constant>(LHS)) 495 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS)) 496 LHS = SimpleLHS; 497 if (!isa<Constant>(RHS)) 498 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS)) 499 RHS = SimpleRHS; 500 Value *SimpleV = nullptr; 501 const DataLayout &DL = I.getModule()->getDataLayout(); 502 if (auto FI = dyn_cast<FPMathOperator>(&I)) 503 SimpleV = 504 SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL); 505 else 506 SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL); 507 508 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) 509 SimplifiedValues[&I] = C; 510 511 return SimpleV; 512 } 513 514 /// Try to fold load I. 515 bool visitLoad(LoadInst &I) { 516 Value *AddrOp = I.getPointerOperand(); 517 if (!isa<Constant>(AddrOp)) 518 if (Constant *SimplifiedAddrOp = SimplifiedValues.lookup(AddrOp)) 519 AddrOp = SimplifiedAddrOp; 520 521 auto *GEP = dyn_cast<GetElementPtrInst>(AddrOp); 522 if (!GEP) 523 return false; 524 auto OptionalGEPDesc = SC.getGEPDescriptor(GEP); 525 if (!OptionalGEPDesc) 526 return false; 527 528 auto GV = dyn_cast<GlobalVariable>(OptionalGEPDesc->BaseAddr); 529 // We're only interested in loads that can be completely folded to a 530 // constant. 531 if (!GV || !GV->hasInitializer()) 532 return false; 533 534 ConstantDataSequential *CDS = 535 dyn_cast<ConstantDataSequential>(GV->getInitializer()); 536 if (!CDS) 537 return false; 538 539 // This calculation should never overflow because we bound Iteration quite 540 // low and both the start and step are 32-bit integers. We use signed 541 // integers so that UBSan will catch if a bug sneaks into the code. 542 int ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U; 543 int64_t Index = ((int64_t)OptionalGEPDesc->Start + 544 (int64_t)OptionalGEPDesc->Step * (int64_t)Iteration) / 545 ElemSize; 546 if (Index >= CDS->getNumElements()) { 547 // FIXME: For now we conservatively ignore out of bound accesses, but 548 // we're allowed to perform the optimization in this case. 549 return false; 550 } 551 552 Constant *CV = CDS->getElementAsConstant(Index); 553 assert(CV && "Constant expected."); 554 SimplifiedValues[&I] = CV; 555 556 return true; 557 } 558 }; 559 } // namespace 560 561 562 namespace { 563 struct EstimatedUnrollCost { 564 /// \brief The estimated cost after unrolling. 565 unsigned UnrolledCost; 566 567 /// \brief The estimated dynamic cost of executing the instructions in the 568 /// rolled form. 569 unsigned RolledDynamicCost; 570 }; 571 } 572 573 /// \brief Figure out if the loop is worth full unrolling. 574 /// 575 /// Complete loop unrolling can make some loads constant, and we need to know 576 /// if that would expose any further optimization opportunities. This routine 577 /// estimates this optimization. It assigns computed number of instructions, 578 /// that potentially might be optimized away, to 579 /// NumberOfOptimizedInstructions, and total number of instructions to 580 /// UnrolledLoopSize (not counting blocks that won't be reached, if we were 581 /// able to compute the condition). 582 /// \returns false if we can't analyze the loop, or if we discovered that 583 /// unrolling won't give anything. Otherwise, returns true. 584 Optional<EstimatedUnrollCost> 585 analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, ScalarEvolution &SE, 586 const TargetTransformInfo &TTI, 587 unsigned MaxUnrolledLoopSize) { 588 // We want to be able to scale offsets by the trip count and add more offsets 589 // to them without checking for overflows, and we already don't want to 590 // analyze *massive* trip counts, so we force the max to be reasonably small. 591 assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) && 592 "The unroll iterations max is too large!"); 593 594 // Don't simulate loops with a big or unknown tripcount 595 if (!UnrollMaxIterationsCountToAnalyze || !TripCount || 596 TripCount > UnrollMaxIterationsCountToAnalyze) 597 return None; 598 599 SmallSetVector<BasicBlock *, 16> BBWorklist; 600 DenseMap<Value *, Constant *> SimplifiedValues; 601 602 // Use a cache to access SCEV expressions so that we don't pay the cost on 603 // each iteration. This cache is lazily self-populating. 604 SCEVCache SC(*L, SE); 605 606 // The estimated cost of the unrolled form of the loop. We try to estimate 607 // this by simplifying as much as we can while computing the estimate. 608 unsigned UnrolledCost = 0; 609 // We also track the estimated dynamic (that is, actually executed) cost in 610 // the rolled form. This helps identify cases when the savings from unrolling 611 // aren't just exposing dead control flows, but actual reduced dynamic 612 // instructions due to the simplifications which we expect to occur after 613 // unrolling. 614 unsigned RolledDynamicCost = 0; 615 616 // Simulate execution of each iteration of the loop counting instructions, 617 // which would be simplified. 618 // Since the same load will take different values on different iterations, 619 // we literally have to go through all loop's iterations. 620 for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) { 621 SimplifiedValues.clear(); 622 UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SC); 623 624 BBWorklist.clear(); 625 BBWorklist.insert(L->getHeader()); 626 // Note that we *must not* cache the size, this loop grows the worklist. 627 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) { 628 BasicBlock *BB = BBWorklist[Idx]; 629 630 // Visit all instructions in the given basic block and try to simplify 631 // it. We don't change the actual IR, just count optimization 632 // opportunities. 633 for (Instruction &I : *BB) { 634 unsigned InstCost = TTI.getUserCost(&I); 635 636 // Visit the instruction to analyze its loop cost after unrolling, 637 // and if the visitor returns false, include this instruction in the 638 // unrolled cost. 639 if (!Analyzer.visit(I)) 640 UnrolledCost += InstCost; 641 642 // Also track this instructions expected cost when executing the rolled 643 // loop form. 644 RolledDynamicCost += InstCost; 645 646 // If unrolled body turns out to be too big, bail out. 647 if (UnrolledCost > MaxUnrolledLoopSize) 648 return None; 649 } 650 651 // Add BB's successors to the worklist. 652 for (BasicBlock *Succ : successors(BB)) 653 if (L->contains(Succ)) 654 BBWorklist.insert(Succ); 655 } 656 657 // If we found no optimization opportunities on the first iteration, we 658 // won't find them on later ones too. 659 if (UnrolledCost == RolledDynamicCost) 660 return None; 661 } 662 return {{UnrolledCost, RolledDynamicCost}}; 663 } 664 665 /// ApproximateLoopSize - Approximate the size of the loop. 666 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls, 667 bool &NotDuplicatable, 668 const TargetTransformInfo &TTI, 669 AssumptionCache *AC) { 670 SmallPtrSet<const Value *, 32> EphValues; 671 CodeMetrics::collectEphemeralValues(L, AC, EphValues); 672 673 CodeMetrics Metrics; 674 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 675 I != E; ++I) 676 Metrics.analyzeBasicBlock(*I, TTI, EphValues); 677 NumCalls = Metrics.NumInlineCandidates; 678 NotDuplicatable = Metrics.notDuplicatable; 679 680 unsigned LoopSize = Metrics.NumInsts; 681 682 // Don't allow an estimate of size zero. This would allows unrolling of loops 683 // with huge iteration counts, which is a compile time problem even if it's 684 // not a problem for code quality. Also, the code using this size may assume 685 // that each loop has at least three instructions (likely a conditional 686 // branch, a comparison feeding that branch, and some kind of loop increment 687 // feeding that comparison instruction). 688 LoopSize = std::max(LoopSize, 3u); 689 690 return LoopSize; 691 } 692 693 // Returns the loop hint metadata node with the given name (for example, 694 // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is 695 // returned. 696 static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) { 697 if (MDNode *LoopID = L->getLoopID()) 698 return GetUnrollMetadata(LoopID, Name); 699 return nullptr; 700 } 701 702 // Returns true if the loop has an unroll(full) pragma. 703 static bool HasUnrollFullPragma(const Loop *L) { 704 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full"); 705 } 706 707 // Returns true if the loop has an unroll(disable) pragma. 708 static bool HasUnrollDisablePragma(const Loop *L) { 709 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable"); 710 } 711 712 // Returns true if the loop has an runtime unroll(disable) pragma. 713 static bool HasRuntimeUnrollDisablePragma(const Loop *L) { 714 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable"); 715 } 716 717 // If loop has an unroll_count pragma return the (necessarily 718 // positive) value from the pragma. Otherwise return 0. 719 static unsigned UnrollCountPragmaValue(const Loop *L) { 720 MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count"); 721 if (MD) { 722 assert(MD->getNumOperands() == 2 && 723 "Unroll count hint metadata should have two operands."); 724 unsigned Count = 725 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue(); 726 assert(Count >= 1 && "Unroll count must be positive."); 727 return Count; 728 } 729 return 0; 730 } 731 732 // Remove existing unroll metadata and add unroll disable metadata to 733 // indicate the loop has already been unrolled. This prevents a loop 734 // from being unrolled more than is directed by a pragma if the loop 735 // unrolling pass is run more than once (which it generally is). 736 static void SetLoopAlreadyUnrolled(Loop *L) { 737 MDNode *LoopID = L->getLoopID(); 738 if (!LoopID) return; 739 740 // First remove any existing loop unrolling metadata. 741 SmallVector<Metadata *, 4> MDs; 742 // Reserve first location for self reference to the LoopID metadata node. 743 MDs.push_back(nullptr); 744 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 745 bool IsUnrollMetadata = false; 746 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 747 if (MD) { 748 const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 749 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll."); 750 } 751 if (!IsUnrollMetadata) 752 MDs.push_back(LoopID->getOperand(i)); 753 } 754 755 // Add unroll(disable) metadata to disable future unrolling. 756 LLVMContext &Context = L->getHeader()->getContext(); 757 SmallVector<Metadata *, 1> DisableOperands; 758 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable")); 759 MDNode *DisableNode = MDNode::get(Context, DisableOperands); 760 MDs.push_back(DisableNode); 761 762 MDNode *NewLoopID = MDNode::get(Context, MDs); 763 // Set operand 0 to refer to the loop id itself. 764 NewLoopID->replaceOperandWith(0, NewLoopID); 765 L->setLoopID(NewLoopID); 766 } 767 768 bool LoopUnroll::canUnrollCompletely(Loop *L, unsigned Threshold, 769 unsigned PercentDynamicCostSavedThreshold, 770 unsigned DynamicCostSavingsDiscount, 771 unsigned UnrolledCost, 772 unsigned RolledDynamicCost) { 773 774 if (Threshold == NoThreshold) { 775 DEBUG(dbgs() << " Can fully unroll, because no threshold is set.\n"); 776 return true; 777 } 778 779 if (UnrolledCost <= Threshold) { 780 DEBUG(dbgs() << " Can fully unroll, because unrolled cost: " 781 << UnrolledCost << "<" << Threshold << "\n"); 782 return true; 783 } 784 785 assert(UnrolledCost && "UnrolledCost can't be 0 at this point."); 786 assert(RolledDynamicCost >= UnrolledCost && 787 "Cannot have a higher unrolled cost than a rolled cost!"); 788 789 // Compute the percentage of the dynamic cost in the rolled form that is 790 // saved when unrolled. If unrolling dramatically reduces the estimated 791 // dynamic cost of the loop, we use a higher threshold to allow more 792 // unrolling. 793 unsigned PercentDynamicCostSaved = 794 (uint64_t)(RolledDynamicCost - UnrolledCost) * 100ull / RolledDynamicCost; 795 796 if (PercentDynamicCostSaved >= PercentDynamicCostSavedThreshold && 797 (int64_t)UnrolledCost - (int64_t)DynamicCostSavingsDiscount <= 798 (int64_t)Threshold) { 799 DEBUG(dbgs() << " Can fully unroll, because unrolling will reduce the " 800 "expected dynamic cost by " << PercentDynamicCostSaved 801 << "% (threshold: " << PercentDynamicCostSavedThreshold 802 << "%)\n" 803 << " and the unrolled cost (" << UnrolledCost 804 << ") is less than the max threshold (" 805 << DynamicCostSavingsDiscount << ").\n"); 806 return true; 807 } 808 809 DEBUG(dbgs() << " Too large to fully unroll:\n"); 810 DEBUG(dbgs() << " Threshold: " << Threshold << "\n"); 811 DEBUG(dbgs() << " Max threshold: " << DynamicCostSavingsDiscount << "\n"); 812 DEBUG(dbgs() << " Percent cost saved threshold: " 813 << PercentDynamicCostSavedThreshold << "%\n"); 814 DEBUG(dbgs() << " Unrolled cost: " << UnrolledCost << "\n"); 815 DEBUG(dbgs() << " Rolled dynamic cost: " << RolledDynamicCost << "\n"); 816 DEBUG(dbgs() << " Percent cost saved: " << PercentDynamicCostSaved 817 << "\n"); 818 return false; 819 } 820 821 unsigned LoopUnroll::selectUnrollCount( 822 const Loop *L, unsigned TripCount, bool PragmaFullUnroll, 823 unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP, 824 bool &SetExplicitly) { 825 SetExplicitly = true; 826 827 // User-specified count (either as a command-line option or 828 // constructor parameter) has highest precedence. 829 unsigned Count = UserCount ? CurrentCount : 0; 830 831 // If there is no user-specified count, unroll pragmas have the next 832 // highest precendence. 833 if (Count == 0) { 834 if (PragmaCount) { 835 Count = PragmaCount; 836 } else if (PragmaFullUnroll) { 837 Count = TripCount; 838 } 839 } 840 841 if (Count == 0) 842 Count = UP.Count; 843 844 if (Count == 0) { 845 SetExplicitly = false; 846 if (TripCount == 0) 847 // Runtime trip count. 848 Count = UnrollRuntimeCount; 849 else 850 // Conservative heuristic: if we know the trip count, see if we can 851 // completely unroll (subject to the threshold, checked below); otherwise 852 // try to find greatest modulo of the trip count which is still under 853 // threshold value. 854 Count = TripCount; 855 } 856 if (TripCount && Count > TripCount) 857 return TripCount; 858 return Count; 859 } 860 861 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) { 862 if (skipOptnoneFunction(L)) 863 return false; 864 865 Function &F = *L->getHeader()->getParent(); 866 867 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 868 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>(); 869 const TargetTransformInfo &TTI = 870 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 871 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 872 873 BasicBlock *Header = L->getHeader(); 874 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName() 875 << "] Loop %" << Header->getName() << "\n"); 876 877 if (HasUnrollDisablePragma(L)) { 878 return false; 879 } 880 bool PragmaFullUnroll = HasUnrollFullPragma(L); 881 unsigned PragmaCount = UnrollCountPragmaValue(L); 882 bool HasPragma = PragmaFullUnroll || PragmaCount > 0; 883 884 TargetTransformInfo::UnrollingPreferences UP; 885 getUnrollingPreferences(L, TTI, UP); 886 887 // Find trip count and trip multiple if count is not available 888 unsigned TripCount = 0; 889 unsigned TripMultiple = 1; 890 // If there are multiple exiting blocks but one of them is the latch, use the 891 // latch for the trip count estimation. Otherwise insist on a single exiting 892 // block for the trip count estimation. 893 BasicBlock *ExitingBlock = L->getLoopLatch(); 894 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock)) 895 ExitingBlock = L->getExitingBlock(); 896 if (ExitingBlock) { 897 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock); 898 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock); 899 } 900 901 // Select an initial unroll count. This may be reduced later based 902 // on size thresholds. 903 bool CountSetExplicitly; 904 unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll, 905 PragmaCount, UP, CountSetExplicitly); 906 907 unsigned NumInlineCandidates; 908 bool notDuplicatable; 909 unsigned LoopSize = 910 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC); 911 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n"); 912 913 // When computing the unrolled size, note that the conditional branch on the 914 // backedge and the comparison feeding it are not replicated like the rest of 915 // the loop body (which is why 2 is subtracted). 916 uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2; 917 if (notDuplicatable) { 918 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable" 919 << " instructions.\n"); 920 return false; 921 } 922 if (NumInlineCandidates != 0) { 923 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n"); 924 return false; 925 } 926 927 unsigned Threshold, PartialThreshold; 928 unsigned PercentDynamicCostSavedThreshold; 929 unsigned DynamicCostSavingsDiscount; 930 selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold, 931 PercentDynamicCostSavedThreshold, 932 DynamicCostSavingsDiscount); 933 934 // Given Count, TripCount and thresholds determine the type of 935 // unrolling which is to be performed. 936 enum { Full = 0, Partial = 1, Runtime = 2 }; 937 int Unrolling; 938 if (TripCount && Count == TripCount) { 939 Unrolling = Partial; 940 // If the loop is really small, we don't need to run an expensive analysis. 941 if (canUnrollCompletely(L, Threshold, 100, DynamicCostSavingsDiscount, 942 UnrolledSize, UnrolledSize)) { 943 Unrolling = Full; 944 } else { 945 // The loop isn't that small, but we still can fully unroll it if that 946 // helps to remove a significant number of instructions. 947 // To check that, run additional analysis on the loop. 948 if (Optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost( 949 L, TripCount, *SE, TTI, Threshold + DynamicCostSavingsDiscount)) 950 if (canUnrollCompletely(L, Threshold, PercentDynamicCostSavedThreshold, 951 DynamicCostSavingsDiscount, Cost->UnrolledCost, 952 Cost->RolledDynamicCost)) { 953 Unrolling = Full; 954 } 955 } 956 } else if (TripCount && Count < TripCount) { 957 Unrolling = Partial; 958 } else { 959 Unrolling = Runtime; 960 } 961 962 // Reduce count based on the type of unrolling and the threshold values. 963 unsigned OriginalCount = Count; 964 bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime; 965 if (HasRuntimeUnrollDisablePragma(L)) { 966 AllowRuntime = false; 967 } 968 if (Unrolling == Partial) { 969 bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial; 970 if (!AllowPartial && !CountSetExplicitly) { 971 DEBUG(dbgs() << " will not try to unroll partially because " 972 << "-unroll-allow-partial not given\n"); 973 return false; 974 } 975 if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) { 976 // Reduce unroll count to be modulo of TripCount for partial unrolling. 977 Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2); 978 while (Count != 0 && TripCount % Count != 0) 979 Count--; 980 } 981 } else if (Unrolling == Runtime) { 982 if (!AllowRuntime && !CountSetExplicitly) { 983 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count " 984 << "-unroll-runtime not given\n"); 985 return false; 986 } 987 // Reduce unroll count to be the largest power-of-two factor of 988 // the original count which satisfies the threshold limit. 989 while (Count != 0 && UnrolledSize > PartialThreshold) { 990 Count >>= 1; 991 UnrolledSize = (LoopSize-2) * Count + 2; 992 } 993 if (Count > UP.MaxCount) 994 Count = UP.MaxCount; 995 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n"); 996 } 997 998 if (HasPragma) { 999 if (PragmaCount != 0) 1000 // If loop has an unroll count pragma mark loop as unrolled to prevent 1001 // unrolling beyond that requested by the pragma. 1002 SetLoopAlreadyUnrolled(L); 1003 1004 // Emit optimization remarks if we are unable to unroll the loop 1005 // as directed by a pragma. 1006 DebugLoc LoopLoc = L->getStartLoc(); 1007 Function *F = Header->getParent(); 1008 LLVMContext &Ctx = F->getContext(); 1009 if (PragmaFullUnroll && PragmaCount == 0) { 1010 if (TripCount && Count != TripCount) { 1011 emitOptimizationRemarkMissed( 1012 Ctx, DEBUG_TYPE, *F, LoopLoc, 1013 "Unable to fully unroll loop as directed by unroll(full) pragma " 1014 "because unrolled size is too large."); 1015 } else if (!TripCount) { 1016 emitOptimizationRemarkMissed( 1017 Ctx, DEBUG_TYPE, *F, LoopLoc, 1018 "Unable to fully unroll loop as directed by unroll(full) pragma " 1019 "because loop has a runtime trip count."); 1020 } 1021 } else if (PragmaCount > 0 && Count != OriginalCount) { 1022 emitOptimizationRemarkMissed( 1023 Ctx, DEBUG_TYPE, *F, LoopLoc, 1024 "Unable to unroll loop the number of times directed by " 1025 "unroll_count pragma because unrolled size is too large."); 1026 } 1027 } 1028 1029 if (Unrolling != Full && Count < 2) { 1030 // Partial unrolling by 1 is a nop. For full unrolling, a factor 1031 // of 1 makes sense because loop control can be eliminated. 1032 return false; 1033 } 1034 1035 // Unroll the loop. 1036 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, UP.AllowExpensiveTripCount, 1037 TripMultiple, LI, this, &LPM, &AC)) 1038 return false; 1039 1040 return true; 1041 } 1042