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