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<DominatorTreeWrapperPass>(); 141 AU.addRequired<LoopInfoWrapperPass>(); 142 AU.addPreserved<LoopInfoWrapperPass>(); 143 AU.addRequiredID(LoopSimplifyID); 144 AU.addPreservedID(LoopSimplifyID); 145 AU.addRequiredID(LCSSAID); 146 AU.addPreservedID(LCSSAID); 147 AU.addRequired<ScalarEvolution>(); 148 AU.addPreserved<ScalarEvolution>(); 149 AU.addRequired<TargetTransformInfoWrapperPass>(); 150 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info. 151 // If loop unroll does not preserve dom info then LCSSA pass on next 152 // loop will receive invalid dom info. 153 // For now, recreate dom info, if loop is unrolled. 154 AU.addPreserved<DominatorTreeWrapperPass>(); 155 } 156 157 // Fill in the UnrollingPreferences parameter with values from the 158 // TargetTransformationInfo. 159 void getUnrollingPreferences(Loop *L, const TargetTransformInfo &TTI, 160 TargetTransformInfo::UnrollingPreferences &UP) { 161 UP.Threshold = CurrentThreshold; 162 UP.PercentDynamicCostSavedThreshold = 163 CurrentPercentDynamicCostSavedThreshold; 164 UP.DynamicCostSavingsDiscount = CurrentDynamicCostSavingsDiscount; 165 UP.OptSizeThreshold = OptSizeUnrollThreshold; 166 UP.PartialThreshold = CurrentThreshold; 167 UP.PartialOptSizeThreshold = OptSizeUnrollThreshold; 168 UP.Count = CurrentCount; 169 UP.MaxCount = UINT_MAX; 170 UP.Partial = CurrentAllowPartial; 171 UP.Runtime = CurrentRuntime; 172 UP.AllowExpensiveTripCount = false; 173 TTI.getUnrollingPreferences(L, UP); 174 } 175 176 // Select and return an unroll count based on parameters from 177 // user, unroll preferences, unroll pragmas, or a heuristic. 178 // SetExplicitly is set to true if the unroll count is is set by 179 // the user or a pragma rather than selected heuristically. 180 unsigned 181 selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll, 182 unsigned PragmaCount, 183 const TargetTransformInfo::UnrollingPreferences &UP, 184 bool &SetExplicitly); 185 186 // Select threshold values used to limit unrolling based on a 187 // total unrolled size. Parameters Threshold and PartialThreshold 188 // are set to the maximum unrolled size for fully and partially 189 // unrolled loops respectively. 190 void selectThresholds(const Loop *L, bool HasPragma, 191 const TargetTransformInfo::UnrollingPreferences &UP, 192 unsigned &Threshold, unsigned &PartialThreshold, 193 unsigned &PercentDynamicCostSavedThreshold, 194 unsigned &DynamicCostSavingsDiscount) { 195 // Determine the current unrolling threshold. While this is 196 // normally set from UnrollThreshold, it is overridden to a 197 // smaller value if the current function is marked as 198 // optimize-for-size, and the unroll threshold was not user 199 // specified. 200 Threshold = UserThreshold ? CurrentThreshold : UP.Threshold; 201 PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold; 202 PercentDynamicCostSavedThreshold = 203 UserPercentDynamicCostSavedThreshold 204 ? CurrentPercentDynamicCostSavedThreshold 205 : UP.PercentDynamicCostSavedThreshold; 206 DynamicCostSavingsDiscount = UserDynamicCostSavingsDiscount 207 ? CurrentDynamicCostSavingsDiscount 208 : UP.DynamicCostSavingsDiscount; 209 210 if (!UserThreshold && 211 L->getHeader()->getParent()->hasFnAttribute( 212 Attribute::OptimizeForSize)) { 213 Threshold = UP.OptSizeThreshold; 214 PartialThreshold = UP.PartialOptSizeThreshold; 215 } 216 if (HasPragma) { 217 // If the loop has an unrolling pragma, we want to be more 218 // aggressive with unrolling limits. Set thresholds to at 219 // least the PragmaTheshold value which is larger than the 220 // default limits. 221 if (Threshold != NoThreshold) 222 Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold); 223 if (PartialThreshold != NoThreshold) 224 PartialThreshold = 225 std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold); 226 } 227 } 228 bool canUnrollCompletely(Loop *L, unsigned Threshold, 229 unsigned PercentDynamicCostSavedThreshold, 230 unsigned DynamicCostSavingsDiscount, 231 uint64_t UnrolledCost, uint64_t RolledDynamicCost); 232 }; 233 } 234 235 char LoopUnroll::ID = 0; 236 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false) 237 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 238 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 239 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 240 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 241 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 242 INITIALIZE_PASS_DEPENDENCY(LCSSA) 243 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) 244 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false) 245 246 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial, 247 int Runtime) { 248 return new LoopUnroll(Threshold, Count, AllowPartial, Runtime); 249 } 250 251 Pass *llvm::createSimpleLoopUnrollPass() { 252 return llvm::createLoopUnrollPass(-1, -1, 0, 0); 253 } 254 255 namespace { 256 // This class is used to get an estimate of the optimization effects that we 257 // could get from complete loop unrolling. It comes from the fact that some 258 // loads might be replaced with concrete constant values and that could trigger 259 // a chain of instruction simplifications. 260 // 261 // E.g. we might have: 262 // int a[] = {0, 1, 0}; 263 // v = 0; 264 // for (i = 0; i < 3; i ++) 265 // v += b[i]*a[i]; 266 // If we completely unroll the loop, we would get: 267 // v = b[0]*a[0] + b[1]*a[1] + b[2]*a[2] 268 // Which then will be simplified to: 269 // v = b[0]* 0 + b[1]* 1 + b[2]* 0 270 // And finally: 271 // v = b[1] 272 class UnrolledInstAnalyzer : private InstVisitor<UnrolledInstAnalyzer, bool> { 273 typedef InstVisitor<UnrolledInstAnalyzer, bool> Base; 274 friend class InstVisitor<UnrolledInstAnalyzer, bool>; 275 struct SimplifiedAddress { 276 Value *Base = nullptr; 277 ConstantInt *Offset = nullptr; 278 }; 279 280 public: 281 UnrolledInstAnalyzer(unsigned Iteration, 282 DenseMap<Value *, Constant *> &SimplifiedValues, 283 const Loop *L, ScalarEvolution &SE) 284 : Iteration(Iteration), SimplifiedValues(SimplifiedValues), L(L), SE(SE) { 285 IterationNumber = SE.getConstant(APInt(64, Iteration)); 286 } 287 288 // Allow access to the initial visit method. 289 using Base::visit; 290 291 private: 292 /// \brief A cache of pointer bases and constant-folded offsets corresponding 293 /// to GEP (or derived from GEP) instructions. 294 /// 295 /// In order to find the base pointer one needs to perform non-trivial 296 /// traversal of the corresponding SCEV expression, so it's good to have the 297 /// results saved. 298 DenseMap<Value *, SimplifiedAddress> SimplifiedAddresses; 299 300 /// \brief Number of currently simulated iteration. 301 /// 302 /// If an expression is ConstAddress+Constant, then the Constant is 303 /// Start + Iteration*Step, where Start and Step could be obtained from 304 /// SCEVGEPCache. 305 unsigned Iteration; 306 307 /// \brief SCEV expression corresponding to number of currently simulated 308 /// iteration. 309 const SCEV *IterationNumber; 310 311 /// \brief A Value->Constant map for keeping values that we managed to 312 /// constant-fold on the given iteration. 313 /// 314 /// While we walk the loop instructions, we build up and maintain a mapping 315 /// of simplified values specific to this iteration. The idea is to propagate 316 /// any special information we have about loads that can be replaced with 317 /// constants after complete unrolling, and account for likely simplifications 318 /// post-unrolling. 319 DenseMap<Value *, Constant *> &SimplifiedValues; 320 321 const Loop *L; 322 ScalarEvolution &SE; 323 324 /// \brief Try to simplify instruction \param I using its SCEV expression. 325 /// 326 /// The idea is that some AddRec expressions become constants, which then 327 /// could trigger folding of other instructions. However, that only happens 328 /// for expressions whose start value is also constant, which isn't always the 329 /// case. In another common and important case the start value is just some 330 /// address (i.e. SCEVUnknown) - in this case we compute the offset and save 331 /// it along with the base address instead. 332 bool simplifyInstWithSCEV(Instruction *I) { 333 if (!SE.isSCEVable(I->getType())) 334 return false; 335 336 const SCEV *S = SE.getSCEV(I); 337 if (auto *SC = dyn_cast<SCEVConstant>(S)) { 338 SimplifiedValues[I] = SC->getValue(); 339 return true; 340 } 341 342 auto *AR = dyn_cast<SCEVAddRecExpr>(S); 343 if (!AR) 344 return false; 345 346 const SCEV *ValueAtIteration = AR->evaluateAtIteration(IterationNumber, SE); 347 // Check if the AddRec expression becomes a constant. 348 if (auto *SC = dyn_cast<SCEVConstant>(ValueAtIteration)) { 349 SimplifiedValues[I] = SC->getValue(); 350 return true; 351 } 352 353 // Check if the offset from the base address becomes a constant. 354 auto *Base = dyn_cast<SCEVUnknown>(SE.getPointerBase(S)); 355 if (!Base) 356 return false; 357 auto *Offset = 358 dyn_cast<SCEVConstant>(SE.getMinusSCEV(ValueAtIteration, Base)); 359 if (!Offset) 360 return false; 361 SimplifiedAddress Address; 362 Address.Base = Base->getValue(); 363 Address.Offset = Offset->getValue(); 364 SimplifiedAddresses[I] = Address; 365 return true; 366 } 367 368 /// Base case for the instruction visitor. 369 bool visitInstruction(Instruction &I) { 370 return simplifyInstWithSCEV(&I); 371 } 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 bool visitCastInst(CastInst &I) { 441 // Propagate constants through casts. 442 Constant *COp = dyn_cast<Constant>(I.getOperand(0)); 443 if (!COp) 444 COp = SimplifiedValues.lookup(I.getOperand(0)); 445 if (COp) 446 if (Constant *C = 447 ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) { 448 SimplifiedValues[&I] = C; 449 return true; 450 } 451 452 return Base::visitCastInst(I); 453 } 454 455 bool visitCmpInst(CmpInst &I) { 456 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 457 458 // First try to handle simplified comparisons. 459 if (!isa<Constant>(LHS)) 460 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS)) 461 LHS = SimpleLHS; 462 if (!isa<Constant>(RHS)) 463 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS)) 464 RHS = SimpleRHS; 465 466 if (!isa<Constant>(LHS) && !isa<Constant>(RHS)) { 467 auto SimplifiedLHS = SimplifiedAddresses.find(LHS); 468 if (SimplifiedLHS != SimplifiedAddresses.end()) { 469 auto SimplifiedRHS = SimplifiedAddresses.find(RHS); 470 if (SimplifiedRHS != SimplifiedAddresses.end()) { 471 SimplifiedAddress &LHSAddr = SimplifiedLHS->second; 472 SimplifiedAddress &RHSAddr = SimplifiedRHS->second; 473 if (LHSAddr.Base == RHSAddr.Base) { 474 LHS = LHSAddr.Offset; 475 RHS = RHSAddr.Offset; 476 } 477 } 478 } 479 } 480 481 if (Constant *CLHS = dyn_cast<Constant>(LHS)) { 482 if (Constant *CRHS = dyn_cast<Constant>(RHS)) { 483 if (Constant *C = ConstantExpr::getCompare(I.getPredicate(), CLHS, CRHS)) { 484 SimplifiedValues[&I] = C; 485 return true; 486 } 487 } 488 } 489 490 return Base::visitCmpInst(I); 491 } 492 }; 493 } // namespace 494 495 496 namespace { 497 struct EstimatedUnrollCost { 498 /// \brief The estimated cost after unrolling. 499 unsigned UnrolledCost; 500 501 /// \brief The estimated dynamic cost of executing the instructions in the 502 /// rolled form. 503 unsigned RolledDynamicCost; 504 }; 505 } 506 507 /// \brief Figure out if the loop is worth full unrolling. 508 /// 509 /// Complete loop unrolling can make some loads constant, and we need to know 510 /// if that would expose any further optimization opportunities. This routine 511 /// estimates this optimization. It computes cost of unrolled loop 512 /// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By 513 /// dynamic cost we mean that we won't count costs of blocks that are known not 514 /// to be executed (i.e. if we have a branch in the loop and we know that at the 515 /// given iteration its condition would be resolved to true, we won't add up the 516 /// cost of the 'false'-block). 517 /// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If 518 /// the analysis failed (no benefits expected from the unrolling, or the loop is 519 /// too big to analyze), the returned value is None. 520 Optional<EstimatedUnrollCost> 521 analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, DominatorTree &DT, 522 ScalarEvolution &SE, const TargetTransformInfo &TTI, 523 unsigned MaxUnrolledLoopSize) { 524 // We want to be able to scale offsets by the trip count and add more offsets 525 // to them without checking for overflows, and we already don't want to 526 // analyze *massive* trip counts, so we force the max to be reasonably small. 527 assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) && 528 "The unroll iterations max is too large!"); 529 530 // Don't simulate loops with a big or unknown tripcount 531 if (!UnrollMaxIterationsCountToAnalyze || !TripCount || 532 TripCount > UnrollMaxIterationsCountToAnalyze) 533 return None; 534 535 SmallSetVector<BasicBlock *, 16> BBWorklist; 536 DenseMap<Value *, Constant *> SimplifiedValues; 537 SmallVector<std::pair<Value *, Constant *>, 4> SimplifiedInputValues; 538 539 // The estimated cost of the unrolled form of the loop. We try to estimate 540 // this by simplifying as much as we can while computing the estimate. 541 unsigned UnrolledCost = 0; 542 // We also track the estimated dynamic (that is, actually executed) cost in 543 // the rolled form. This helps identify cases when the savings from unrolling 544 // aren't just exposing dead control flows, but actual reduced dynamic 545 // instructions due to the simplifications which we expect to occur after 546 // unrolling. 547 unsigned RolledDynamicCost = 0; 548 549 // Ensure that we don't violate the loop structure invariants relied on by 550 // this analysis. 551 assert(L->isLoopSimplifyForm() && "Must put loop into normal form first."); 552 assert(L->isLCSSAForm(DT) && 553 "Must have loops in LCSSA form to track live-out values."); 554 555 DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n"); 556 557 // Simulate execution of each iteration of the loop counting instructions, 558 // which would be simplified. 559 // Since the same load will take different values on different iterations, 560 // we literally have to go through all loop's iterations. 561 for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) { 562 DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n"); 563 564 // Prepare for the iteration by collecting any simplified entry or backedge 565 // inputs. 566 for (Instruction &I : *L->getHeader()) { 567 auto *PHI = dyn_cast<PHINode>(&I); 568 if (!PHI) 569 break; 570 571 // The loop header PHI nodes must have exactly two input: one from the 572 // loop preheader and one from the loop latch. 573 assert( 574 PHI->getNumIncomingValues() == 2 && 575 "Must have an incoming value only for the preheader and the latch."); 576 577 Value *V = PHI->getIncomingValueForBlock( 578 Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch()); 579 Constant *C = dyn_cast<Constant>(V); 580 if (Iteration != 0 && !C) 581 C = SimplifiedValues.lookup(V); 582 if (C) 583 SimplifiedInputValues.push_back({PHI, C}); 584 } 585 586 // Now clear and re-populate the map for the next iteration. 587 SimplifiedValues.clear(); 588 while (!SimplifiedInputValues.empty()) 589 SimplifiedValues.insert(SimplifiedInputValues.pop_back_val()); 590 591 UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, L, SE); 592 593 BBWorklist.clear(); 594 BBWorklist.insert(L->getHeader()); 595 // Note that we *must not* cache the size, this loop grows the worklist. 596 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) { 597 BasicBlock *BB = BBWorklist[Idx]; 598 599 // Visit all instructions in the given basic block and try to simplify 600 // it. We don't change the actual IR, just count optimization 601 // opportunities. 602 for (Instruction &I : *BB) { 603 unsigned InstCost = TTI.getUserCost(&I); 604 605 // Visit the instruction to analyze its loop cost after unrolling, 606 // and if the visitor returns false, include this instruction in the 607 // unrolled cost. 608 if (!Analyzer.visit(I)) 609 UnrolledCost += InstCost; 610 else { 611 DEBUG(dbgs() << " " << I 612 << " would be simplified if loop is unrolled.\n"); 613 (void)0; 614 } 615 616 // Also track this instructions expected cost when executing the rolled 617 // loop form. 618 RolledDynamicCost += InstCost; 619 620 // If unrolled body turns out to be too big, bail out. 621 if (UnrolledCost > MaxUnrolledLoopSize) { 622 DEBUG(dbgs() << " Exceeded threshold.. exiting.\n" 623 << " UnrolledCost: " << UnrolledCost 624 << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize 625 << "\n"); 626 return None; 627 } 628 } 629 630 TerminatorInst *TI = BB->getTerminator(); 631 632 // Add in the live successors by first checking whether we have terminator 633 // that may be simplified based on the values simplified by this call. 634 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { 635 if (BI->isConditional()) { 636 if (Constant *SimpleCond = 637 SimplifiedValues.lookup(BI->getCondition())) { 638 BasicBlock *Succ = nullptr; 639 // Just take the first successor if condition is undef 640 if (isa<UndefValue>(SimpleCond)) 641 Succ = BI->getSuccessor(0); 642 else 643 Succ = BI->getSuccessor( 644 cast<ConstantInt>(SimpleCond)->isZero() ? 1 : 0); 645 if (L->contains(Succ)) 646 BBWorklist.insert(Succ); 647 continue; 648 } 649 } 650 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { 651 if (Constant *SimpleCond = 652 SimplifiedValues.lookup(SI->getCondition())) { 653 BasicBlock *Succ = nullptr; 654 // Just take the first successor if condition is undef 655 if (isa<UndefValue>(SimpleCond)) 656 Succ = SI->getSuccessor(0); 657 else 658 Succ = SI->findCaseValue(cast<ConstantInt>(SimpleCond)) 659 .getCaseSuccessor(); 660 if (L->contains(Succ)) 661 BBWorklist.insert(Succ); 662 continue; 663 } 664 } 665 666 // Add BB's successors to the worklist. 667 for (BasicBlock *Succ : successors(BB)) 668 if (L->contains(Succ)) 669 BBWorklist.insert(Succ); 670 } 671 672 // If we found no optimization opportunities on the first iteration, we 673 // won't find them on later ones too. 674 if (UnrolledCost == RolledDynamicCost) { 675 DEBUG(dbgs() << " No opportunities found.. exiting.\n" 676 << " UnrolledCost: " << UnrolledCost << "\n"); 677 return None; 678 } 679 } 680 DEBUG(dbgs() << "Analysis finished:\n" 681 << "UnrolledCost: " << UnrolledCost << ", " 682 << "RolledDynamicCost: " << RolledDynamicCost << "\n"); 683 return {{UnrolledCost, RolledDynamicCost}}; 684 } 685 686 /// ApproximateLoopSize - Approximate the size of the loop. 687 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls, 688 bool &NotDuplicatable, 689 const TargetTransformInfo &TTI, 690 AssumptionCache *AC) { 691 SmallPtrSet<const Value *, 32> EphValues; 692 CodeMetrics::collectEphemeralValues(L, AC, EphValues); 693 694 CodeMetrics Metrics; 695 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 696 I != E; ++I) 697 Metrics.analyzeBasicBlock(*I, TTI, EphValues); 698 NumCalls = Metrics.NumInlineCandidates; 699 NotDuplicatable = Metrics.notDuplicatable; 700 701 unsigned LoopSize = Metrics.NumInsts; 702 703 // Don't allow an estimate of size zero. This would allows unrolling of loops 704 // with huge iteration counts, which is a compile time problem even if it's 705 // not a problem for code quality. Also, the code using this size may assume 706 // that each loop has at least three instructions (likely a conditional 707 // branch, a comparison feeding that branch, and some kind of loop increment 708 // feeding that comparison instruction). 709 LoopSize = std::max(LoopSize, 3u); 710 711 return LoopSize; 712 } 713 714 // Returns the loop hint metadata node with the given name (for example, 715 // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is 716 // returned. 717 static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) { 718 if (MDNode *LoopID = L->getLoopID()) 719 return GetUnrollMetadata(LoopID, Name); 720 return nullptr; 721 } 722 723 // Returns true if the loop has an unroll(full) pragma. 724 static bool HasUnrollFullPragma(const Loop *L) { 725 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full"); 726 } 727 728 // Returns true if the loop has an unroll(disable) pragma. 729 static bool HasUnrollDisablePragma(const Loop *L) { 730 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable"); 731 } 732 733 // Returns true if the loop has an runtime unroll(disable) pragma. 734 static bool HasRuntimeUnrollDisablePragma(const Loop *L) { 735 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable"); 736 } 737 738 // If loop has an unroll_count pragma return the (necessarily 739 // positive) value from the pragma. Otherwise return 0. 740 static unsigned UnrollCountPragmaValue(const Loop *L) { 741 MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count"); 742 if (MD) { 743 assert(MD->getNumOperands() == 2 && 744 "Unroll count hint metadata should have two operands."); 745 unsigned Count = 746 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue(); 747 assert(Count >= 1 && "Unroll count must be positive."); 748 return Count; 749 } 750 return 0; 751 } 752 753 // Remove existing unroll metadata and add unroll disable metadata to 754 // indicate the loop has already been unrolled. This prevents a loop 755 // from being unrolled more than is directed by a pragma if the loop 756 // unrolling pass is run more than once (which it generally is). 757 static void SetLoopAlreadyUnrolled(Loop *L) { 758 MDNode *LoopID = L->getLoopID(); 759 if (!LoopID) return; 760 761 // First remove any existing loop unrolling metadata. 762 SmallVector<Metadata *, 4> MDs; 763 // Reserve first location for self reference to the LoopID metadata node. 764 MDs.push_back(nullptr); 765 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 766 bool IsUnrollMetadata = false; 767 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 768 if (MD) { 769 const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 770 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll."); 771 } 772 if (!IsUnrollMetadata) 773 MDs.push_back(LoopID->getOperand(i)); 774 } 775 776 // Add unroll(disable) metadata to disable future unrolling. 777 LLVMContext &Context = L->getHeader()->getContext(); 778 SmallVector<Metadata *, 1> DisableOperands; 779 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable")); 780 MDNode *DisableNode = MDNode::get(Context, DisableOperands); 781 MDs.push_back(DisableNode); 782 783 MDNode *NewLoopID = MDNode::get(Context, MDs); 784 // Set operand 0 to refer to the loop id itself. 785 NewLoopID->replaceOperandWith(0, NewLoopID); 786 L->setLoopID(NewLoopID); 787 } 788 789 bool LoopUnroll::canUnrollCompletely(Loop *L, unsigned Threshold, 790 unsigned PercentDynamicCostSavedThreshold, 791 unsigned DynamicCostSavingsDiscount, 792 uint64_t UnrolledCost, 793 uint64_t RolledDynamicCost) { 794 795 if (Threshold == NoThreshold) { 796 DEBUG(dbgs() << " Can fully unroll, because no threshold is set.\n"); 797 return true; 798 } 799 800 if (UnrolledCost <= Threshold) { 801 DEBUG(dbgs() << " Can fully unroll, because unrolled cost: " 802 << UnrolledCost << "<" << Threshold << "\n"); 803 return true; 804 } 805 806 assert(UnrolledCost && "UnrolledCost can't be 0 at this point."); 807 assert(RolledDynamicCost >= UnrolledCost && 808 "Cannot have a higher unrolled cost than a rolled cost!"); 809 810 // Compute the percentage of the dynamic cost in the rolled form that is 811 // saved when unrolled. If unrolling dramatically reduces the estimated 812 // dynamic cost of the loop, we use a higher threshold to allow more 813 // unrolling. 814 unsigned PercentDynamicCostSaved = 815 (uint64_t)(RolledDynamicCost - UnrolledCost) * 100ull / RolledDynamicCost; 816 817 if (PercentDynamicCostSaved >= PercentDynamicCostSavedThreshold && 818 (int64_t)UnrolledCost - (int64_t)DynamicCostSavingsDiscount <= 819 (int64_t)Threshold) { 820 DEBUG(dbgs() << " Can fully unroll, because unrolling will reduce the " 821 "expected dynamic cost by " << PercentDynamicCostSaved 822 << "% (threshold: " << PercentDynamicCostSavedThreshold 823 << "%)\n" 824 << " and the unrolled cost (" << UnrolledCost 825 << ") is less than the max threshold (" 826 << DynamicCostSavingsDiscount << ").\n"); 827 return true; 828 } 829 830 DEBUG(dbgs() << " Too large to fully unroll:\n"); 831 DEBUG(dbgs() << " Threshold: " << Threshold << "\n"); 832 DEBUG(dbgs() << " Max threshold: " << DynamicCostSavingsDiscount << "\n"); 833 DEBUG(dbgs() << " Percent cost saved threshold: " 834 << PercentDynamicCostSavedThreshold << "%\n"); 835 DEBUG(dbgs() << " Unrolled cost: " << UnrolledCost << "\n"); 836 DEBUG(dbgs() << " Rolled dynamic cost: " << RolledDynamicCost << "\n"); 837 DEBUG(dbgs() << " Percent cost saved: " << PercentDynamicCostSaved 838 << "\n"); 839 return false; 840 } 841 842 unsigned LoopUnroll::selectUnrollCount( 843 const Loop *L, unsigned TripCount, bool PragmaFullUnroll, 844 unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP, 845 bool &SetExplicitly) { 846 SetExplicitly = true; 847 848 // User-specified count (either as a command-line option or 849 // constructor parameter) has highest precedence. 850 unsigned Count = UserCount ? CurrentCount : 0; 851 852 // If there is no user-specified count, unroll pragmas have the next 853 // highest precendence. 854 if (Count == 0) { 855 if (PragmaCount) { 856 Count = PragmaCount; 857 } else if (PragmaFullUnroll) { 858 Count = TripCount; 859 } 860 } 861 862 if (Count == 0) 863 Count = UP.Count; 864 865 if (Count == 0) { 866 SetExplicitly = false; 867 if (TripCount == 0) 868 // Runtime trip count. 869 Count = UnrollRuntimeCount; 870 else 871 // Conservative heuristic: if we know the trip count, see if we can 872 // completely unroll (subject to the threshold, checked below); otherwise 873 // try to find greatest modulo of the trip count which is still under 874 // threshold value. 875 Count = TripCount; 876 } 877 if (TripCount && Count > TripCount) 878 return TripCount; 879 return Count; 880 } 881 882 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) { 883 if (skipOptnoneFunction(L)) 884 return false; 885 886 Function &F = *L->getHeader()->getParent(); 887 888 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 889 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 890 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>(); 891 const TargetTransformInfo &TTI = 892 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 893 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 894 895 BasicBlock *Header = L->getHeader(); 896 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName() 897 << "] Loop %" << Header->getName() << "\n"); 898 899 if (HasUnrollDisablePragma(L)) { 900 return false; 901 } 902 bool PragmaFullUnroll = HasUnrollFullPragma(L); 903 unsigned PragmaCount = UnrollCountPragmaValue(L); 904 bool HasPragma = PragmaFullUnroll || PragmaCount > 0; 905 906 TargetTransformInfo::UnrollingPreferences UP; 907 getUnrollingPreferences(L, TTI, UP); 908 909 // Find trip count and trip multiple if count is not available 910 unsigned TripCount = 0; 911 unsigned TripMultiple = 1; 912 // If there are multiple exiting blocks but one of them is the latch, use the 913 // latch for the trip count estimation. Otherwise insist on a single exiting 914 // block for the trip count estimation. 915 BasicBlock *ExitingBlock = L->getLoopLatch(); 916 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock)) 917 ExitingBlock = L->getExitingBlock(); 918 if (ExitingBlock) { 919 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock); 920 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock); 921 } 922 923 // Select an initial unroll count. This may be reduced later based 924 // on size thresholds. 925 bool CountSetExplicitly; 926 unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll, 927 PragmaCount, UP, CountSetExplicitly); 928 929 unsigned NumInlineCandidates; 930 bool notDuplicatable; 931 unsigned LoopSize = 932 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC); 933 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n"); 934 935 // When computing the unrolled size, note that the conditional branch on the 936 // backedge and the comparison feeding it are not replicated like the rest of 937 // the loop body (which is why 2 is subtracted). 938 uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2; 939 if (notDuplicatable) { 940 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable" 941 << " instructions.\n"); 942 return false; 943 } 944 if (NumInlineCandidates != 0) { 945 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n"); 946 return false; 947 } 948 949 unsigned Threshold, PartialThreshold; 950 unsigned PercentDynamicCostSavedThreshold; 951 unsigned DynamicCostSavingsDiscount; 952 selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold, 953 PercentDynamicCostSavedThreshold, 954 DynamicCostSavingsDiscount); 955 956 // Given Count, TripCount and thresholds determine the type of 957 // unrolling which is to be performed. 958 enum { Full = 0, Partial = 1, Runtime = 2 }; 959 int Unrolling; 960 if (TripCount && Count == TripCount) { 961 Unrolling = Partial; 962 // If the loop is really small, we don't need to run an expensive analysis. 963 if (canUnrollCompletely(L, Threshold, 100, DynamicCostSavingsDiscount, 964 UnrolledSize, UnrolledSize)) { 965 Unrolling = Full; 966 } else { 967 // The loop isn't that small, but we still can fully unroll it if that 968 // helps to remove a significant number of instructions. 969 // To check that, run additional analysis on the loop. 970 if (Optional<EstimatedUnrollCost> Cost = 971 analyzeLoopUnrollCost(L, TripCount, DT, *SE, TTI, 972 Threshold + DynamicCostSavingsDiscount)) 973 if (canUnrollCompletely(L, Threshold, PercentDynamicCostSavedThreshold, 974 DynamicCostSavingsDiscount, Cost->UnrolledCost, 975 Cost->RolledDynamicCost)) { 976 Unrolling = Full; 977 } 978 } 979 } else if (TripCount && Count < TripCount) { 980 Unrolling = Partial; 981 } else { 982 Unrolling = Runtime; 983 } 984 985 // Reduce count based on the type of unrolling and the threshold values. 986 unsigned OriginalCount = Count; 987 bool AllowRuntime = 988 (PragmaCount > 0) || (UserRuntime ? CurrentRuntime : UP.Runtime); 989 // Don't unroll a runtime trip count loop with unroll full pragma. 990 if (HasRuntimeUnrollDisablePragma(L) || PragmaFullUnroll) { 991 AllowRuntime = false; 992 } 993 if (Unrolling == Partial) { 994 bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial; 995 if (!AllowPartial && !CountSetExplicitly) { 996 DEBUG(dbgs() << " will not try to unroll partially because " 997 << "-unroll-allow-partial not given\n"); 998 return false; 999 } 1000 if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) { 1001 // Reduce unroll count to be modulo of TripCount for partial unrolling. 1002 Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2); 1003 while (Count != 0 && TripCount % Count != 0) 1004 Count--; 1005 } 1006 } else if (Unrolling == Runtime) { 1007 if (!AllowRuntime && !CountSetExplicitly) { 1008 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count " 1009 << "-unroll-runtime not given\n"); 1010 return false; 1011 } 1012 // Reduce unroll count to be the largest power-of-two factor of 1013 // the original count which satisfies the threshold limit. 1014 while (Count != 0 && UnrolledSize > PartialThreshold) { 1015 Count >>= 1; 1016 UnrolledSize = (LoopSize-2) * Count + 2; 1017 } 1018 if (Count > UP.MaxCount) 1019 Count = UP.MaxCount; 1020 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n"); 1021 } 1022 1023 if (HasPragma) { 1024 if (PragmaCount != 0) 1025 // If loop has an unroll count pragma mark loop as unrolled to prevent 1026 // unrolling beyond that requested by the pragma. 1027 SetLoopAlreadyUnrolled(L); 1028 1029 // Emit optimization remarks if we are unable to unroll the loop 1030 // as directed by a pragma. 1031 DebugLoc LoopLoc = L->getStartLoc(); 1032 Function *F = Header->getParent(); 1033 LLVMContext &Ctx = F->getContext(); 1034 if (PragmaFullUnroll && PragmaCount == 0) { 1035 if (TripCount && Count != TripCount) { 1036 emitOptimizationRemarkMissed( 1037 Ctx, DEBUG_TYPE, *F, LoopLoc, 1038 "Unable to fully unroll loop as directed by unroll(full) pragma " 1039 "because unrolled size is too large."); 1040 } else if (!TripCount) { 1041 emitOptimizationRemarkMissed( 1042 Ctx, DEBUG_TYPE, *F, LoopLoc, 1043 "Unable to fully unroll loop as directed by unroll(full) pragma " 1044 "because loop has a runtime trip count."); 1045 } 1046 } else if (PragmaCount > 0 && Count != OriginalCount) { 1047 emitOptimizationRemarkMissed( 1048 Ctx, DEBUG_TYPE, *F, LoopLoc, 1049 "Unable to unroll loop the number of times directed by " 1050 "unroll_count pragma because unrolled size is too large."); 1051 } 1052 } 1053 1054 if (Unrolling != Full && Count < 2) { 1055 // Partial unrolling by 1 is a nop. For full unrolling, a factor 1056 // of 1 makes sense because loop control can be eliminated. 1057 return false; 1058 } 1059 1060 // Unroll the loop. 1061 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, UP.AllowExpensiveTripCount, 1062 TripMultiple, LI, this, &LPM, &AC)) 1063 return false; 1064 1065 return true; 1066 } 1067