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