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/LoopPass.h" 20 #include "llvm/Analysis/ScalarEvolution.h" 21 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 22 #include "llvm/Analysis/TargetTransformInfo.h" 23 #include "llvm/IR/DataLayout.h" 24 #include "llvm/IR/DiagnosticInfo.h" 25 #include "llvm/IR/Dominators.h" 26 #include "llvm/IR/IntrinsicInst.h" 27 #include "llvm/IR/Metadata.h" 28 #include "llvm/Support/CommandLine.h" 29 #include "llvm/Support/Debug.h" 30 #include "llvm/Support/raw_ostream.h" 31 #include "llvm/Transforms/Utils/UnrollLoop.h" 32 #include "llvm/IR/InstVisitor.h" 33 #include "llvm/Analysis/InstructionSimplify.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 cut-off point for automatic loop unrolling")); 43 44 static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze( 45 "unroll-max-iteration-count-to-analyze", cl::init(1000), cl::Hidden, 46 cl::desc("Don't allow loop unrolling to simulate more than this number of" 47 "iterations when checking full unroll profitability")); 48 49 static cl::opt<unsigned> UnrollMinPercentOfOptimized( 50 "unroll-percent-of-optimized-for-complete-unroll", cl::init(20), cl::Hidden, 51 cl::desc("If complete unrolling could trigger further optimizations, and, " 52 "by that, remove the given percent of instructions, perform the " 53 "complete unroll even if it's beyond the threshold")); 54 55 static cl::opt<unsigned> UnrollAbsoluteThreshold( 56 "unroll-absolute-threshold", cl::init(2000), cl::Hidden, 57 cl::desc("Don't unroll if the unrolled size is bigger than this threshold," 58 " even if we can remove big portion of instructions later.")); 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 CurrentAbsoluteThreshold = UnrollAbsoluteThreshold; 86 CurrentMinPercentOfOptimized = UnrollMinPercentOfOptimized; 87 CurrentCount = (C == -1) ? UnrollCount : unsigned(C); 88 CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P; 89 CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R; 90 91 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0); 92 UserAbsoluteThreshold = (UnrollAbsoluteThreshold.getNumOccurrences() > 0); 93 UserPercentOfOptimized = 94 (UnrollMinPercentOfOptimized.getNumOccurrences() > 0); 95 UserAllowPartial = (P != -1) || 96 (UnrollAllowPartial.getNumOccurrences() > 0); 97 UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0); 98 UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0); 99 100 initializeLoopUnrollPass(*PassRegistry::getPassRegistry()); 101 } 102 103 /// A magic value for use with the Threshold parameter to indicate 104 /// that the loop unroll should be performed regardless of how much 105 /// code expansion would result. 106 static const unsigned NoThreshold = UINT_MAX; 107 108 // Threshold to use when optsize is specified (and there is no 109 // explicit -unroll-threshold). 110 static const unsigned OptSizeUnrollThreshold = 50; 111 112 // Default unroll count for loops with run-time trip count if 113 // -unroll-count is not set 114 static const unsigned UnrollRuntimeCount = 8; 115 116 unsigned CurrentCount; 117 unsigned CurrentThreshold; 118 unsigned CurrentAbsoluteThreshold; 119 unsigned CurrentMinPercentOfOptimized; 120 bool CurrentAllowPartial; 121 bool CurrentRuntime; 122 bool UserCount; // CurrentCount is user-specified. 123 bool UserThreshold; // CurrentThreshold is user-specified. 124 bool UserAbsoluteThreshold; // CurrentAbsoluteThreshold is 125 // user-specified. 126 bool UserPercentOfOptimized; // CurrentMinPercentOfOptimized is 127 // user-specified. 128 bool UserAllowPartial; // CurrentAllowPartial is user-specified. 129 bool UserRuntime; // CurrentRuntime is user-specified. 130 131 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 132 133 /// This transformation requires natural loop information & requires that 134 /// loop preheaders be inserted into the CFG... 135 /// 136 void getAnalysisUsage(AnalysisUsage &AU) const override { 137 AU.addRequired<AssumptionCacheTracker>(); 138 AU.addRequired<LoopInfoWrapperPass>(); 139 AU.addPreserved<LoopInfoWrapperPass>(); 140 AU.addRequiredID(LoopSimplifyID); 141 AU.addPreservedID(LoopSimplifyID); 142 AU.addRequiredID(LCSSAID); 143 AU.addPreservedID(LCSSAID); 144 AU.addRequired<ScalarEvolution>(); 145 AU.addPreserved<ScalarEvolution>(); 146 AU.addRequired<TargetTransformInfoWrapperPass>(); 147 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info. 148 // If loop unroll does not preserve dom info then LCSSA pass on next 149 // loop will receive invalid dom info. 150 // For now, recreate dom info, if loop is unrolled. 151 AU.addPreserved<DominatorTreeWrapperPass>(); 152 } 153 154 // Fill in the UnrollingPreferences parameter with values from the 155 // TargetTransformationInfo. 156 void getUnrollingPreferences(Loop *L, const TargetTransformInfo &TTI, 157 TargetTransformInfo::UnrollingPreferences &UP) { 158 UP.Threshold = CurrentThreshold; 159 UP.AbsoluteThreshold = CurrentAbsoluteThreshold; 160 UP.MinPercentOfOptimized = CurrentMinPercentOfOptimized; 161 UP.OptSizeThreshold = OptSizeUnrollThreshold; 162 UP.PartialThreshold = CurrentThreshold; 163 UP.PartialOptSizeThreshold = OptSizeUnrollThreshold; 164 UP.Count = CurrentCount; 165 UP.MaxCount = UINT_MAX; 166 UP.Partial = CurrentAllowPartial; 167 UP.Runtime = CurrentRuntime; 168 TTI.getUnrollingPreferences(L, UP); 169 } 170 171 // Select and return an unroll count based on parameters from 172 // user, unroll preferences, unroll pragmas, or a heuristic. 173 // SetExplicitly is set to true if the unroll count is is set by 174 // the user or a pragma rather than selected heuristically. 175 unsigned 176 selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll, 177 unsigned PragmaCount, 178 const TargetTransformInfo::UnrollingPreferences &UP, 179 bool &SetExplicitly); 180 181 // Select threshold values used to limit unrolling based on a 182 // total unrolled size. Parameters Threshold and PartialThreshold 183 // are set to the maximum unrolled size for fully and partially 184 // unrolled loops respectively. 185 void selectThresholds(const Loop *L, bool HasPragma, 186 const TargetTransformInfo::UnrollingPreferences &UP, 187 unsigned &Threshold, unsigned &PartialThreshold, 188 unsigned NumberOfOptimizedInstructions) { 189 // Determine the current unrolling threshold. While this is 190 // normally set from UnrollThreshold, it is overridden to a 191 // smaller value if the current function is marked as 192 // optimize-for-size, and the unroll threshold was not user 193 // specified. 194 Threshold = UserThreshold ? CurrentThreshold : UP.Threshold; 195 196 // If we are allowed to completely unroll if we can remove M% of 197 // instructions, and we know that with complete unrolling we'll be able 198 // to kill N instructions, then we can afford to completely unroll loops 199 // with unrolled size up to N*100/M. 200 // Adjust the threshold according to that: 201 unsigned PercentOfOptimizedForCompleteUnroll = 202 UserPercentOfOptimized ? CurrentMinPercentOfOptimized 203 : UP.MinPercentOfOptimized; 204 unsigned AbsoluteThreshold = UserAbsoluteThreshold 205 ? CurrentAbsoluteThreshold 206 : UP.AbsoluteThreshold; 207 if (PercentOfOptimizedForCompleteUnroll) 208 Threshold = std::max<unsigned>(Threshold, 209 NumberOfOptimizedInstructions * 100 / 210 PercentOfOptimizedForCompleteUnroll); 211 // But don't allow unrolling loops bigger than absolute threshold. 212 Threshold = std::min<unsigned>(Threshold, AbsoluteThreshold); 213 214 PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold; 215 if (!UserThreshold && 216 L->getHeader()->getParent()->getAttributes(). 217 hasAttribute(AttributeSet::FunctionIndex, 218 Attribute::OptimizeForSize)) { 219 Threshold = UP.OptSizeThreshold; 220 PartialThreshold = UP.PartialOptSizeThreshold; 221 } 222 if (HasPragma) { 223 // If the loop has an unrolling pragma, we want to be more 224 // aggressive with unrolling limits. Set thresholds to at 225 // least the PragmaTheshold value which is larger than the 226 // default limits. 227 if (Threshold != NoThreshold) 228 Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold); 229 if (PartialThreshold != NoThreshold) 230 PartialThreshold = 231 std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold); 232 } 233 } 234 }; 235 } 236 237 char LoopUnroll::ID = 0; 238 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false) 239 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 240 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 241 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 242 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 243 INITIALIZE_PASS_DEPENDENCY(LCSSA) 244 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) 245 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false) 246 247 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial, 248 int Runtime) { 249 return new LoopUnroll(Threshold, Count, AllowPartial, Runtime); 250 } 251 252 Pass *llvm::createSimpleLoopUnrollPass() { 253 return llvm::createLoopUnrollPass(-1, -1, 0, 0); 254 } 255 256 static bool isLoadFromConstantInitializer(Value *V) { 257 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) 258 if (GV->isConstant() && GV->hasDefinitiveInitializer()) 259 return GV->getInitializer(); 260 return false; 261 } 262 263 struct FindConstantPointers { 264 bool LoadCanBeConstantFolded; 265 bool IndexIsConstant; 266 APInt Step; 267 APInt StartValue; 268 Value *BaseAddress; 269 const Loop *L; 270 ScalarEvolution &SE; 271 FindConstantPointers(const Loop *loop, ScalarEvolution &SE) 272 : LoadCanBeConstantFolded(true), IndexIsConstant(true), L(loop), SE(SE) {} 273 274 bool follow(const SCEV *S) { 275 if (const SCEVUnknown *SC = dyn_cast<SCEVUnknown>(S)) { 276 // We've reached the leaf node of SCEV, it's most probably just a 277 // variable. Now it's time to see if it corresponds to a global constant 278 // global (in which case we can eliminate the load), or not. 279 BaseAddress = SC->getValue(); 280 LoadCanBeConstantFolded = 281 IndexIsConstant && isLoadFromConstantInitializer(BaseAddress); 282 return false; 283 } 284 if (isa<SCEVConstant>(S)) 285 return true; 286 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { 287 // If the current SCEV expression is AddRec, and its loop isn't the loop 288 // we are about to unroll, then we won't get a constant address after 289 // unrolling, and thus, won't be able to eliminate the load. 290 if (AR->getLoop() != L) 291 return IndexIsConstant = false; 292 // If the step isn't constant, we won't get constant addresses in unrolled 293 // version. Bail out. 294 if (const SCEVConstant *StepSE = 295 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 296 Step = StepSE->getValue()->getValue(); 297 else 298 return IndexIsConstant = false; 299 300 return IndexIsConstant; 301 } 302 // If Result is true, continue traversal. 303 // Otherwise, we have found something that prevents us from (possible) load 304 // elimination. 305 return IndexIsConstant; 306 } 307 bool isDone() const { return !IndexIsConstant; } 308 }; 309 310 // This class is used to get an estimate of the optimization effects that we 311 // could get from complete loop unrolling. It comes from the fact that some 312 // loads might be replaced with concrete constant values and that could trigger 313 // a chain of instruction simplifications. 314 // 315 // E.g. we might have: 316 // int a[] = {0, 1, 0}; 317 // v = 0; 318 // for (i = 0; i < 3; i ++) 319 // v += b[i]*a[i]; 320 // If we completely unroll the loop, we would get: 321 // v = b[0]*a[0] + b[1]*a[1] + b[2]*a[2] 322 // Which then will be simplified to: 323 // v = b[0]* 0 + b[1]* 1 + b[2]* 0 324 // And finally: 325 // v = b[1] 326 class UnrollAnalyzer : public InstVisitor<UnrollAnalyzer, bool> { 327 typedef InstVisitor<UnrollAnalyzer, bool> Base; 328 friend class InstVisitor<UnrollAnalyzer, bool>; 329 330 const Loop *L; 331 unsigned TripCount; 332 ScalarEvolution &SE; 333 const TargetTransformInfo &TTI; 334 335 DenseMap<Value *, Constant *> SimplifiedValues; 336 DenseMap<LoadInst *, Value *> LoadBaseAddresses; 337 SmallPtrSet<Instruction *, 32> CountedInstructions; 338 339 /// \brief Count the number of optimized instructions. 340 unsigned NumberOfOptimizedInstructions; 341 342 // Provide base case for our instruction visit. 343 bool visitInstruction(Instruction &I) { return false; }; 344 // TODO: We should also visit ICmp, FCmp, GetElementPtr, Trunc, ZExt, SExt, 345 // FPTrunc, FPExt, FPToUI, FPToSI, UIToFP, SIToFP, BitCast, Select, 346 // ExtractElement, InsertElement, ShuffleVector, ExtractValue, InsertValue. 347 // 348 // Probaly it's worth to hoist the code for estimating the simplifications 349 // effects to a separate class, since we have a very similar code in 350 // InlineCost already. 351 bool visitBinaryOperator(BinaryOperator &I) { 352 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); 353 if (!isa<Constant>(LHS)) 354 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS)) 355 LHS = SimpleLHS; 356 if (!isa<Constant>(RHS)) 357 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS)) 358 RHS = SimpleRHS; 359 Value *SimpleV = nullptr; 360 if (auto FI = dyn_cast<FPMathOperator>(&I)) 361 SimpleV = 362 SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags()); 363 else 364 SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS); 365 366 if (SimpleV && CountedInstructions.insert(&I).second) 367 NumberOfOptimizedInstructions += TTI.getUserCost(&I); 368 369 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) { 370 SimplifiedValues[&I] = C; 371 return true; 372 } 373 return false; 374 } 375 376 Constant *computeLoadValue(LoadInst *LI, unsigned Iteration) { 377 if (!LI) 378 return nullptr; 379 Value *BaseAddr = LoadBaseAddresses[LI]; 380 if (!BaseAddr) 381 return nullptr; 382 383 auto GV = dyn_cast<GlobalVariable>(BaseAddr); 384 if (!GV) 385 return nullptr; 386 387 ConstantDataSequential *CDS = 388 dyn_cast<ConstantDataSequential>(GV->getInitializer()); 389 if (!CDS) 390 return nullptr; 391 392 const SCEV *BaseAddrSE = SE.getSCEV(BaseAddr); 393 const SCEV *S = SE.getSCEV(LI->getPointerOperand()); 394 const SCEV *OffSE = SE.getMinusSCEV(S, BaseAddrSE); 395 396 APInt StepC, StartC; 397 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(OffSE); 398 if (!AR) 399 return nullptr; 400 401 if (const SCEVConstant *StepSE = 402 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) 403 StepC = StepSE->getValue()->getValue(); 404 else 405 return nullptr; 406 407 if (const SCEVConstant *StartSE = dyn_cast<SCEVConstant>(AR->getStart())) 408 StartC = StartSE->getValue()->getValue(); 409 else 410 return nullptr; 411 412 unsigned ElemSize = CDS->getElementType()->getPrimitiveSizeInBits() / 8U; 413 unsigned Start = StartC.getLimitedValue(); 414 unsigned Step = StepC.getLimitedValue(); 415 416 unsigned Index = (Start + Step * Iteration) / ElemSize; 417 if (Index >= CDS->getNumElements()) 418 return nullptr; 419 420 Constant *CV = CDS->getElementAsConstant(Index); 421 422 return CV; 423 } 424 425 public: 426 UnrollAnalyzer(const Loop *L, unsigned TripCount, ScalarEvolution &SE, 427 const TargetTransformInfo &TTI) 428 : L(L), TripCount(TripCount), SE(SE), TTI(TTI), 429 NumberOfOptimizedInstructions(0) {} 430 431 // Visit all loads the loop L, and for those that, after complete loop 432 // unrolling, would have a constant address and it will point to a known 433 // constant initializer, record its base address for future use. It is used 434 // when we estimate number of potentially simplified instructions. 435 void findConstFoldableLoads() { 436 for (auto BB : L->getBlocks()) { 437 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { 438 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 439 if (!LI->isSimple()) 440 continue; 441 Value *AddrOp = LI->getPointerOperand(); 442 const SCEV *S = SE.getSCEV(AddrOp); 443 FindConstantPointers Visitor(L, SE); 444 SCEVTraversal<FindConstantPointers> T(Visitor); 445 T.visitAll(S); 446 if (Visitor.IndexIsConstant && Visitor.LoadCanBeConstantFolded) { 447 LoadBaseAddresses[LI] = Visitor.BaseAddress; 448 } 449 } 450 } 451 } 452 } 453 454 // Given a list of loads that could be constant-folded (LoadBaseAddresses), 455 // estimate number of optimized instructions after substituting the concrete 456 // values for the given Iteration. 457 // Fill in SimplifiedValues map for future use in DCE-estimation. 458 unsigned estimateNumberOfSimplifiedInstructions(unsigned Iteration) { 459 SmallVector<Instruction *, 8> Worklist; 460 SimplifiedValues.clear(); 461 CountedInstructions.clear(); 462 NumberOfOptimizedInstructions = 0; 463 464 // We start by adding all loads to the worklist. 465 for (auto &LoadDescr : LoadBaseAddresses) { 466 LoadInst *LI = LoadDescr.first; 467 SimplifiedValues[LI] = computeLoadValue(LI, Iteration); 468 if (CountedInstructions.insert(LI).second) 469 NumberOfOptimizedInstructions += TTI.getUserCost(LI); 470 471 for (User *U : LI->users()) { 472 Instruction *UI = dyn_cast<Instruction>(U); 473 if (!UI) 474 continue; 475 if (!L->contains(UI)) 476 continue; 477 Worklist.push_back(UI); 478 } 479 } 480 481 // And then we try to simplify every user of every instruction from the 482 // worklist. If we do simplify a user, add it to the worklist to process 483 // its users as well. 484 while (!Worklist.empty()) { 485 Instruction *I = Worklist.pop_back_val(); 486 if (!visit(I)) 487 continue; 488 for (User *U : I->users()) { 489 Instruction *UI = dyn_cast<Instruction>(U); 490 if (!UI) 491 continue; 492 if (!L->contains(UI)) 493 continue; 494 Worklist.push_back(UI); 495 } 496 } 497 return NumberOfOptimizedInstructions; 498 } 499 500 // Given a list of potentially simplifed instructions, estimate number of 501 // instructions that would become dead if we do perform the simplification. 502 unsigned estimateNumberOfDeadInstructions() { 503 NumberOfOptimizedInstructions = 0; 504 505 // We keep a set vector for the worklist so that we don't wast space in the 506 // worklist queuing up the same instruction repeatedly. This can happen due 507 // to multiple operands being the same instruction or due to the same 508 // instruction being an operand of lots of things that end up dead or 509 // simplified. 510 SmallSetVector<Instruction *, 8> Worklist; 511 512 // The dead instructions are held in a separate set. This is used to 513 // prevent us from re-examining instructions and make sure we only count 514 // the benifit once. The worklist's internal set handles insertion 515 // deduplication. 516 SmallPtrSet<Instruction *, 16> DeadInstructions; 517 518 // Lambda to enque operands onto the worklist. 519 auto EnqueueOperands = [&](Instruction &I) { 520 for (auto *Op : I.operand_values()) 521 if (auto *OpI = dyn_cast<Instruction>(Op)) 522 if (!OpI->use_empty()) 523 Worklist.insert(OpI); 524 }; 525 526 // Start by initializing worklist with simplified instructions. 527 for (auto &FoldedKeyValue : SimplifiedValues) 528 if (auto *FoldedInst = dyn_cast<Instruction>(FoldedKeyValue.first)) { 529 DeadInstructions.insert(FoldedInst); 530 531 // Add each instruction operand of this dead instruction to the 532 // worklist. 533 EnqueueOperands(*FoldedInst); 534 } 535 536 // If a definition of an insn is only used by simplified or dead 537 // instructions, it's also dead. Check defs of all instructions from the 538 // worklist. 539 while (!Worklist.empty()) { 540 Instruction *I = Worklist.pop_back_val(); 541 if (!L->contains(I)) 542 continue; 543 if (DeadInstructions.count(I)) 544 continue; 545 bool AllUsersFolded = true; 546 for (User *U : I->users()) { 547 Instruction *UI = dyn_cast<Instruction>(U); 548 if (!SimplifiedValues[UI] && !DeadInstructions.count(UI)) { 549 AllUsersFolded = false; 550 break; 551 } 552 } 553 if (AllUsersFolded) { 554 NumberOfOptimizedInstructions += TTI.getUserCost(I); 555 DeadInstructions.insert(I); 556 EnqueueOperands(*I); 557 } 558 } 559 return NumberOfOptimizedInstructions; 560 } 561 }; 562 563 // Complete loop unrolling can make some loads constant, and we need to know if 564 // that would expose any further optimization opportunities. 565 // This routine estimates this optimization effect and returns the number of 566 // instructions, that potentially might be optimized away. 567 static unsigned 568 approximateNumberOfOptimizedInstructions(const Loop *L, ScalarEvolution &SE, 569 unsigned TripCount, 570 const TargetTransformInfo &TTI) { 571 if (!TripCount || !UnrollMaxIterationsCountToAnalyze) 572 return 0; 573 574 UnrollAnalyzer UA(L, TripCount, SE, TTI); 575 UA.findConstFoldableLoads(); 576 577 // Estimate number of instructions, that could be simplified if we replace a 578 // load with the corresponding constant. Since the same load will take 579 // different values on different iterations, we have to go through all loop's 580 // iterations here. To limit ourselves here, we check only first N 581 // iterations, and then scale the found number, if necessary. 582 unsigned IterationsNumberForEstimate = 583 std::min<unsigned>(UnrollMaxIterationsCountToAnalyze, TripCount); 584 unsigned NumberOfOptimizedInstructions = 0; 585 for (unsigned i = 0; i < IterationsNumberForEstimate; ++i) { 586 NumberOfOptimizedInstructions += 587 UA.estimateNumberOfSimplifiedInstructions(i); 588 NumberOfOptimizedInstructions += UA.estimateNumberOfDeadInstructions(); 589 } 590 NumberOfOptimizedInstructions *= TripCount / IterationsNumberForEstimate; 591 592 return NumberOfOptimizedInstructions; 593 } 594 595 /// ApproximateLoopSize - Approximate the size of the loop. 596 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls, 597 bool &NotDuplicatable, 598 const TargetTransformInfo &TTI, 599 AssumptionCache *AC) { 600 SmallPtrSet<const Value *, 32> EphValues; 601 CodeMetrics::collectEphemeralValues(L, AC, EphValues); 602 603 CodeMetrics Metrics; 604 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 605 I != E; ++I) 606 Metrics.analyzeBasicBlock(*I, TTI, EphValues); 607 NumCalls = Metrics.NumInlineCandidates; 608 NotDuplicatable = Metrics.notDuplicatable; 609 610 unsigned LoopSize = Metrics.NumInsts; 611 612 // Don't allow an estimate of size zero. This would allows unrolling of loops 613 // with huge iteration counts, which is a compile time problem even if it's 614 // not a problem for code quality. Also, the code using this size may assume 615 // that each loop has at least three instructions (likely a conditional 616 // branch, a comparison feeding that branch, and some kind of loop increment 617 // feeding that comparison instruction). 618 LoopSize = std::max(LoopSize, 3u); 619 620 return LoopSize; 621 } 622 623 // Returns the loop hint metadata node with the given name (for example, 624 // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is 625 // returned. 626 static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) { 627 if (MDNode *LoopID = L->getLoopID()) 628 return GetUnrollMetadata(LoopID, Name); 629 return nullptr; 630 } 631 632 // Returns true if the loop has an unroll(full) pragma. 633 static bool HasUnrollFullPragma(const Loop *L) { 634 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full"); 635 } 636 637 // Returns true if the loop has an unroll(disable) pragma. 638 static bool HasUnrollDisablePragma(const Loop *L) { 639 return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable"); 640 } 641 642 // If loop has an unroll_count pragma return the (necessarily 643 // positive) value from the pragma. Otherwise return 0. 644 static unsigned UnrollCountPragmaValue(const Loop *L) { 645 MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count"); 646 if (MD) { 647 assert(MD->getNumOperands() == 2 && 648 "Unroll count hint metadata should have two operands."); 649 unsigned Count = 650 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue(); 651 assert(Count >= 1 && "Unroll count must be positive."); 652 return Count; 653 } 654 return 0; 655 } 656 657 // Remove existing unroll metadata and add unroll disable metadata to 658 // indicate the loop has already been unrolled. This prevents a loop 659 // from being unrolled more than is directed by a pragma if the loop 660 // unrolling pass is run more than once (which it generally is). 661 static void SetLoopAlreadyUnrolled(Loop *L) { 662 MDNode *LoopID = L->getLoopID(); 663 if (!LoopID) return; 664 665 // First remove any existing loop unrolling metadata. 666 SmallVector<Metadata *, 4> MDs; 667 // Reserve first location for self reference to the LoopID metadata node. 668 MDs.push_back(nullptr); 669 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 670 bool IsUnrollMetadata = false; 671 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 672 if (MD) { 673 const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 674 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll."); 675 } 676 if (!IsUnrollMetadata) 677 MDs.push_back(LoopID->getOperand(i)); 678 } 679 680 // Add unroll(disable) metadata to disable future unrolling. 681 LLVMContext &Context = L->getHeader()->getContext(); 682 SmallVector<Metadata *, 1> DisableOperands; 683 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable")); 684 MDNode *DisableNode = MDNode::get(Context, DisableOperands); 685 MDs.push_back(DisableNode); 686 687 MDNode *NewLoopID = MDNode::get(Context, MDs); 688 // Set operand 0 to refer to the loop id itself. 689 NewLoopID->replaceOperandWith(0, NewLoopID); 690 L->setLoopID(NewLoopID); 691 } 692 693 unsigned LoopUnroll::selectUnrollCount( 694 const Loop *L, unsigned TripCount, bool PragmaFullUnroll, 695 unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP, 696 bool &SetExplicitly) { 697 SetExplicitly = true; 698 699 // User-specified count (either as a command-line option or 700 // constructor parameter) has highest precedence. 701 unsigned Count = UserCount ? CurrentCount : 0; 702 703 // If there is no user-specified count, unroll pragmas have the next 704 // highest precendence. 705 if (Count == 0) { 706 if (PragmaCount) { 707 Count = PragmaCount; 708 } else if (PragmaFullUnroll) { 709 Count = TripCount; 710 } 711 } 712 713 if (Count == 0) 714 Count = UP.Count; 715 716 if (Count == 0) { 717 SetExplicitly = false; 718 if (TripCount == 0) 719 // Runtime trip count. 720 Count = UnrollRuntimeCount; 721 else 722 // Conservative heuristic: if we know the trip count, see if we can 723 // completely unroll (subject to the threshold, checked below); otherwise 724 // try to find greatest modulo of the trip count which is still under 725 // threshold value. 726 Count = TripCount; 727 } 728 if (TripCount && Count > TripCount) 729 return TripCount; 730 return Count; 731 } 732 733 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) { 734 if (skipOptnoneFunction(L)) 735 return false; 736 737 Function &F = *L->getHeader()->getParent(); 738 739 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 740 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>(); 741 const TargetTransformInfo &TTI = 742 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 743 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 744 745 BasicBlock *Header = L->getHeader(); 746 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName() 747 << "] Loop %" << Header->getName() << "\n"); 748 749 if (HasUnrollDisablePragma(L)) { 750 return false; 751 } 752 bool PragmaFullUnroll = HasUnrollFullPragma(L); 753 unsigned PragmaCount = UnrollCountPragmaValue(L); 754 bool HasPragma = PragmaFullUnroll || PragmaCount > 0; 755 756 TargetTransformInfo::UnrollingPreferences UP; 757 getUnrollingPreferences(L, TTI, UP); 758 759 // Find trip count and trip multiple if count is not available 760 unsigned TripCount = 0; 761 unsigned TripMultiple = 1; 762 // If there are multiple exiting blocks but one of them is the latch, use the 763 // latch for the trip count estimation. Otherwise insist on a single exiting 764 // block for the trip count estimation. 765 BasicBlock *ExitingBlock = L->getLoopLatch(); 766 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock)) 767 ExitingBlock = L->getExitingBlock(); 768 if (ExitingBlock) { 769 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock); 770 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock); 771 } 772 773 // Select an initial unroll count. This may be reduced later based 774 // on size thresholds. 775 bool CountSetExplicitly; 776 unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll, 777 PragmaCount, UP, CountSetExplicitly); 778 779 unsigned NumInlineCandidates; 780 bool notDuplicatable; 781 unsigned LoopSize = 782 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC); 783 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n"); 784 785 // When computing the unrolled size, note that the conditional branch on the 786 // backedge and the comparison feeding it are not replicated like the rest of 787 // the loop body (which is why 2 is subtracted). 788 uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2; 789 if (notDuplicatable) { 790 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable" 791 << " instructions.\n"); 792 return false; 793 } 794 if (NumInlineCandidates != 0) { 795 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n"); 796 return false; 797 } 798 799 unsigned NumberOfOptimizedInstructions = 800 approximateNumberOfOptimizedInstructions(L, *SE, TripCount, TTI); 801 DEBUG(dbgs() << " Complete unrolling could save: " 802 << NumberOfOptimizedInstructions << "\n"); 803 804 unsigned Threshold, PartialThreshold; 805 selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold, 806 NumberOfOptimizedInstructions); 807 808 // Given Count, TripCount and thresholds determine the type of 809 // unrolling which is to be performed. 810 enum { Full = 0, Partial = 1, Runtime = 2 }; 811 int Unrolling; 812 if (TripCount && Count == TripCount) { 813 if (Threshold != NoThreshold && UnrolledSize > Threshold) { 814 DEBUG(dbgs() << " Too large to fully unroll with count: " << Count 815 << " because size: " << UnrolledSize << ">" << Threshold 816 << "\n"); 817 Unrolling = Partial; 818 } else { 819 Unrolling = Full; 820 } 821 } else if (TripCount && Count < TripCount) { 822 Unrolling = Partial; 823 } else { 824 Unrolling = Runtime; 825 } 826 827 // Reduce count based on the type of unrolling and the threshold values. 828 unsigned OriginalCount = Count; 829 bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime; 830 if (Unrolling == Partial) { 831 bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial; 832 if (!AllowPartial && !CountSetExplicitly) { 833 DEBUG(dbgs() << " will not try to unroll partially because " 834 << "-unroll-allow-partial not given\n"); 835 return false; 836 } 837 if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) { 838 // Reduce unroll count to be modulo of TripCount for partial unrolling. 839 Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2); 840 while (Count != 0 && TripCount % Count != 0) 841 Count--; 842 } 843 } else if (Unrolling == Runtime) { 844 if (!AllowRuntime && !CountSetExplicitly) { 845 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count " 846 << "-unroll-runtime not given\n"); 847 return false; 848 } 849 // Reduce unroll count to be the largest power-of-two factor of 850 // the original count which satisfies the threshold limit. 851 while (Count != 0 && UnrolledSize > PartialThreshold) { 852 Count >>= 1; 853 UnrolledSize = (LoopSize-2) * Count + 2; 854 } 855 if (Count > UP.MaxCount) 856 Count = UP.MaxCount; 857 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n"); 858 } 859 860 if (HasPragma) { 861 if (PragmaCount != 0) 862 // If loop has an unroll count pragma mark loop as unrolled to prevent 863 // unrolling beyond that requested by the pragma. 864 SetLoopAlreadyUnrolled(L); 865 866 // Emit optimization remarks if we are unable to unroll the loop 867 // as directed by a pragma. 868 DebugLoc LoopLoc = L->getStartLoc(); 869 Function *F = Header->getParent(); 870 LLVMContext &Ctx = F->getContext(); 871 if (PragmaFullUnroll && PragmaCount == 0) { 872 if (TripCount && Count != TripCount) { 873 emitOptimizationRemarkMissed( 874 Ctx, DEBUG_TYPE, *F, LoopLoc, 875 "Unable to fully unroll loop as directed by unroll(full) pragma " 876 "because unrolled size is too large."); 877 } else if (!TripCount) { 878 emitOptimizationRemarkMissed( 879 Ctx, DEBUG_TYPE, *F, LoopLoc, 880 "Unable to fully unroll loop as directed by unroll(full) pragma " 881 "because loop has a runtime trip count."); 882 } 883 } else if (PragmaCount > 0 && Count != OriginalCount) { 884 emitOptimizationRemarkMissed( 885 Ctx, DEBUG_TYPE, *F, LoopLoc, 886 "Unable to unroll loop the number of times directed by " 887 "unroll_count pragma because unrolled size is too large."); 888 } 889 } 890 891 if (Unrolling != Full && Count < 2) { 892 // Partial unrolling by 1 is a nop. For full unrolling, a factor 893 // of 1 makes sense because loop control can be eliminated. 894 return false; 895 } 896 897 // Unroll the loop. 898 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, TripMultiple, LI, this, 899 &LPM, &AC)) 900 return false; 901 902 return true; 903 } 904