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/FunctionTargetTransformInfo.h" 19 #include "llvm/Analysis/LoopPass.h" 20 #include "llvm/Analysis/ScalarEvolution.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 <climits> 32 33 using namespace llvm; 34 35 #define DEBUG_TYPE "loop-unroll" 36 37 static cl::opt<unsigned> 38 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden, 39 cl::desc("The cut-off point for automatic loop unrolling")); 40 41 static cl::opt<unsigned> 42 UnrollCount("unroll-count", cl::init(0), cl::Hidden, 43 cl::desc("Use this unroll count for all loops including those with " 44 "unroll_count pragma values, for testing purposes")); 45 46 static cl::opt<bool> 47 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden, 48 cl::desc("Allows loops to be partially unrolled until " 49 "-unroll-threshold loop size is reached.")); 50 51 static cl::opt<bool> 52 UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::init(false), cl::Hidden, 53 cl::desc("Unroll loops with run-time trip counts")); 54 55 static cl::opt<unsigned> 56 PragmaUnrollThreshold("pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden, 57 cl::desc("Unrolled size limit for loops with an unroll(full) or " 58 "unroll_count pragma.")); 59 60 namespace { 61 class LoopUnroll : public LoopPass { 62 public: 63 static char ID; // Pass ID, replacement for typeid 64 LoopUnroll(int T = -1, int C = -1, int P = -1, int R = -1) : LoopPass(ID) { 65 CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T); 66 CurrentCount = (C == -1) ? UnrollCount : unsigned(C); 67 CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P; 68 CurrentRuntime = (R == -1) ? UnrollRuntime : (bool)R; 69 70 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0); 71 UserAllowPartial = (P != -1) || 72 (UnrollAllowPartial.getNumOccurrences() > 0); 73 UserRuntime = (R != -1) || (UnrollRuntime.getNumOccurrences() > 0); 74 UserCount = (C != -1) || (UnrollCount.getNumOccurrences() > 0); 75 76 initializeLoopUnrollPass(*PassRegistry::getPassRegistry()); 77 } 78 79 /// A magic value for use with the Threshold parameter to indicate 80 /// that the loop unroll should be performed regardless of how much 81 /// code expansion would result. 82 static const unsigned NoThreshold = UINT_MAX; 83 84 // Threshold to use when optsize is specified (and there is no 85 // explicit -unroll-threshold). 86 static const unsigned OptSizeUnrollThreshold = 50; 87 88 // Default unroll count for loops with run-time trip count if 89 // -unroll-count is not set 90 static const unsigned UnrollRuntimeCount = 8; 91 92 unsigned CurrentCount; 93 unsigned CurrentThreshold; 94 bool CurrentAllowPartial; 95 bool CurrentRuntime; 96 bool UserCount; // CurrentCount is user-specified. 97 bool UserThreshold; // CurrentThreshold is user-specified. 98 bool UserAllowPartial; // CurrentAllowPartial is user-specified. 99 bool UserRuntime; // CurrentRuntime is user-specified. 100 101 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 102 103 /// This transformation requires natural loop information & requires that 104 /// loop preheaders be inserted into the CFG... 105 /// 106 void getAnalysisUsage(AnalysisUsage &AU) const override { 107 AU.addRequired<AssumptionCacheTracker>(); 108 AU.addRequired<LoopInfoWrapperPass>(); 109 AU.addPreserved<LoopInfoWrapperPass>(); 110 AU.addRequiredID(LoopSimplifyID); 111 AU.addPreservedID(LoopSimplifyID); 112 AU.addRequiredID(LCSSAID); 113 AU.addPreservedID(LCSSAID); 114 AU.addRequired<ScalarEvolution>(); 115 AU.addPreserved<ScalarEvolution>(); 116 AU.addRequired<TargetTransformInfoWrapperPass>(); 117 AU.addRequired<FunctionTargetTransformInfo>(); 118 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info. 119 // If loop unroll does not preserve dom info then LCSSA pass on next 120 // loop will receive invalid dom info. 121 // For now, recreate dom info, if loop is unrolled. 122 AU.addPreserved<DominatorTreeWrapperPass>(); 123 } 124 125 // Fill in the UnrollingPreferences parameter with values from the 126 // TargetTransformationInfo. 127 void getUnrollingPreferences(Loop *L, const FunctionTargetTransformInfo &FTTI, 128 TargetTransformInfo::UnrollingPreferences &UP) { 129 UP.Threshold = CurrentThreshold; 130 UP.OptSizeThreshold = OptSizeUnrollThreshold; 131 UP.PartialThreshold = CurrentThreshold; 132 UP.PartialOptSizeThreshold = OptSizeUnrollThreshold; 133 UP.Count = CurrentCount; 134 UP.MaxCount = UINT_MAX; 135 UP.Partial = CurrentAllowPartial; 136 UP.Runtime = CurrentRuntime; 137 FTTI.getUnrollingPreferences(L, UP); 138 } 139 140 // Select and return an unroll count based on parameters from 141 // user, unroll preferences, unroll pragmas, or a heuristic. 142 // SetExplicitly is set to true if the unroll count is is set by 143 // the user or a pragma rather than selected heuristically. 144 unsigned 145 selectUnrollCount(const Loop *L, unsigned TripCount, bool PragmaFullUnroll, 146 unsigned PragmaCount, 147 const TargetTransformInfo::UnrollingPreferences &UP, 148 bool &SetExplicitly); 149 150 // Select threshold values used to limit unrolling based on a 151 // total unrolled size. Parameters Threshold and PartialThreshold 152 // are set to the maximum unrolled size for fully and partially 153 // unrolled loops respectively. 154 void selectThresholds(const Loop *L, bool HasPragma, 155 const TargetTransformInfo::UnrollingPreferences &UP, 156 unsigned &Threshold, unsigned &PartialThreshold) { 157 // Determine the current unrolling threshold. While this is 158 // normally set from UnrollThreshold, it is overridden to a 159 // smaller value if the current function is marked as 160 // optimize-for-size, and the unroll threshold was not user 161 // specified. 162 Threshold = UserThreshold ? CurrentThreshold : UP.Threshold; 163 PartialThreshold = UserThreshold ? CurrentThreshold : UP.PartialThreshold; 164 if (!UserThreshold && 165 L->getHeader()->getParent()->getAttributes(). 166 hasAttribute(AttributeSet::FunctionIndex, 167 Attribute::OptimizeForSize)) { 168 Threshold = UP.OptSizeThreshold; 169 PartialThreshold = UP.PartialOptSizeThreshold; 170 } 171 if (HasPragma) { 172 // If the loop has an unrolling pragma, we want to be more 173 // aggressive with unrolling limits. Set thresholds to at 174 // least the PragmaTheshold value which is larger than the 175 // default limits. 176 if (Threshold != NoThreshold) 177 Threshold = std::max<unsigned>(Threshold, PragmaUnrollThreshold); 178 if (PartialThreshold != NoThreshold) 179 PartialThreshold = 180 std::max<unsigned>(PartialThreshold, PragmaUnrollThreshold); 181 } 182 } 183 }; 184 } 185 186 char LoopUnroll::ID = 0; 187 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false) 188 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 189 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 190 INITIALIZE_PASS_DEPENDENCY(FunctionTargetTransformInfo) 191 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 192 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 193 INITIALIZE_PASS_DEPENDENCY(LCSSA) 194 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution) 195 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false) 196 197 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial, 198 int Runtime) { 199 return new LoopUnroll(Threshold, Count, AllowPartial, Runtime); 200 } 201 202 Pass *llvm::createSimpleLoopUnrollPass() { 203 return llvm::createLoopUnrollPass(-1, -1, 0, 0); 204 } 205 206 /// ApproximateLoopSize - Approximate the size of the loop. 207 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls, 208 bool &NotDuplicatable, 209 const TargetTransformInfo &TTI, 210 AssumptionCache *AC) { 211 SmallPtrSet<const Value *, 32> EphValues; 212 CodeMetrics::collectEphemeralValues(L, AC, EphValues); 213 214 CodeMetrics Metrics; 215 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 216 I != E; ++I) 217 Metrics.analyzeBasicBlock(*I, TTI, EphValues); 218 NumCalls = Metrics.NumInlineCandidates; 219 NotDuplicatable = Metrics.notDuplicatable; 220 221 unsigned LoopSize = Metrics.NumInsts; 222 223 // Don't allow an estimate of size zero. This would allows unrolling of loops 224 // with huge iteration counts, which is a compile time problem even if it's 225 // not a problem for code quality. Also, the code using this size may assume 226 // that each loop has at least three instructions (likely a conditional 227 // branch, a comparison feeding that branch, and some kind of loop increment 228 // feeding that comparison instruction). 229 LoopSize = std::max(LoopSize, 3u); 230 231 return LoopSize; 232 } 233 234 // Returns the loop hint metadata node with the given name (for example, 235 // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is 236 // returned. 237 static const MDNode *GetUnrollMetadata(const Loop *L, StringRef Name) { 238 MDNode *LoopID = L->getLoopID(); 239 if (!LoopID) 240 return nullptr; 241 242 // First operand should refer to the loop id itself. 243 assert(LoopID->getNumOperands() > 0 && "requires at least one operand"); 244 assert(LoopID->getOperand(0) == LoopID && "invalid loop id"); 245 246 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) { 247 const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 248 if (!MD) 249 continue; 250 251 const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 252 if (!S) 253 continue; 254 255 if (Name.equals(S->getString())) 256 return MD; 257 } 258 return nullptr; 259 } 260 261 // Returns true if the loop has an unroll(full) pragma. 262 static bool HasUnrollFullPragma(const Loop *L) { 263 return GetUnrollMetadata(L, "llvm.loop.unroll.full"); 264 } 265 266 // Returns true if the loop has an unroll(disable) pragma. 267 static bool HasUnrollDisablePragma(const Loop *L) { 268 return GetUnrollMetadata(L, "llvm.loop.unroll.disable"); 269 } 270 271 // If loop has an unroll_count pragma return the (necessarily 272 // positive) value from the pragma. Otherwise return 0. 273 static unsigned UnrollCountPragmaValue(const Loop *L) { 274 const MDNode *MD = GetUnrollMetadata(L, "llvm.loop.unroll.count"); 275 if (MD) { 276 assert(MD->getNumOperands() == 2 && 277 "Unroll count hint metadata should have two operands."); 278 unsigned Count = 279 mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue(); 280 assert(Count >= 1 && "Unroll count must be positive."); 281 return Count; 282 } 283 return 0; 284 } 285 286 // Remove existing unroll metadata and add unroll disable metadata to 287 // indicate the loop has already been unrolled. This prevents a loop 288 // from being unrolled more than is directed by a pragma if the loop 289 // unrolling pass is run more than once (which it generally is). 290 static void SetLoopAlreadyUnrolled(Loop *L) { 291 MDNode *LoopID = L->getLoopID(); 292 if (!LoopID) return; 293 294 // First remove any existing loop unrolling metadata. 295 SmallVector<Metadata *, 4> MDs; 296 // Reserve first location for self reference to the LoopID metadata node. 297 MDs.push_back(nullptr); 298 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 299 bool IsUnrollMetadata = false; 300 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); 301 if (MD) { 302 const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); 303 IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll."); 304 } 305 if (!IsUnrollMetadata) 306 MDs.push_back(LoopID->getOperand(i)); 307 } 308 309 // Add unroll(disable) metadata to disable future unrolling. 310 LLVMContext &Context = L->getHeader()->getContext(); 311 SmallVector<Metadata *, 1> DisableOperands; 312 DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable")); 313 MDNode *DisableNode = MDNode::get(Context, DisableOperands); 314 MDs.push_back(DisableNode); 315 316 MDNode *NewLoopID = MDNode::get(Context, MDs); 317 // Set operand 0 to refer to the loop id itself. 318 NewLoopID->replaceOperandWith(0, NewLoopID); 319 L->setLoopID(NewLoopID); 320 } 321 322 unsigned LoopUnroll::selectUnrollCount( 323 const Loop *L, unsigned TripCount, bool PragmaFullUnroll, 324 unsigned PragmaCount, const TargetTransformInfo::UnrollingPreferences &UP, 325 bool &SetExplicitly) { 326 SetExplicitly = true; 327 328 // User-specified count (either as a command-line option or 329 // constructor parameter) has highest precedence. 330 unsigned Count = UserCount ? CurrentCount : 0; 331 332 // If there is no user-specified count, unroll pragmas have the next 333 // highest precendence. 334 if (Count == 0) { 335 if (PragmaCount) { 336 Count = PragmaCount; 337 } else if (PragmaFullUnroll) { 338 Count = TripCount; 339 } 340 } 341 342 if (Count == 0) 343 Count = UP.Count; 344 345 if (Count == 0) { 346 SetExplicitly = false; 347 if (TripCount == 0) 348 // Runtime trip count. 349 Count = UnrollRuntimeCount; 350 else 351 // Conservative heuristic: if we know the trip count, see if we can 352 // completely unroll (subject to the threshold, checked below); otherwise 353 // try to find greatest modulo of the trip count which is still under 354 // threshold value. 355 Count = TripCount; 356 } 357 if (TripCount && Count > TripCount) 358 return TripCount; 359 return Count; 360 } 361 362 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) { 363 if (skipOptnoneFunction(L)) 364 return false; 365 366 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 367 ScalarEvolution *SE = &getAnalysis<ScalarEvolution>(); 368 const TargetTransformInfo &TTI = 369 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(); 370 const FunctionTargetTransformInfo &FTTI = 371 getAnalysis<FunctionTargetTransformInfo>(); 372 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache( 373 *L->getHeader()->getParent()); 374 375 BasicBlock *Header = L->getHeader(); 376 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName() 377 << "] Loop %" << Header->getName() << "\n"); 378 379 if (HasUnrollDisablePragma(L)) { 380 return false; 381 } 382 bool PragmaFullUnroll = HasUnrollFullPragma(L); 383 unsigned PragmaCount = UnrollCountPragmaValue(L); 384 bool HasPragma = PragmaFullUnroll || PragmaCount > 0; 385 386 TargetTransformInfo::UnrollingPreferences UP; 387 getUnrollingPreferences(L, FTTI, UP); 388 389 // Find trip count and trip multiple if count is not available 390 unsigned TripCount = 0; 391 unsigned TripMultiple = 1; 392 // If there are multiple exiting blocks but one of them is the latch, use the 393 // latch for the trip count estimation. Otherwise insist on a single exiting 394 // block for the trip count estimation. 395 BasicBlock *ExitingBlock = L->getLoopLatch(); 396 if (!ExitingBlock || !L->isLoopExiting(ExitingBlock)) 397 ExitingBlock = L->getExitingBlock(); 398 if (ExitingBlock) { 399 TripCount = SE->getSmallConstantTripCount(L, ExitingBlock); 400 TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock); 401 } 402 403 // Select an initial unroll count. This may be reduced later based 404 // on size thresholds. 405 bool CountSetExplicitly; 406 unsigned Count = selectUnrollCount(L, TripCount, PragmaFullUnroll, 407 PragmaCount, UP, CountSetExplicitly); 408 409 unsigned NumInlineCandidates; 410 bool notDuplicatable; 411 unsigned LoopSize = 412 ApproximateLoopSize(L, NumInlineCandidates, notDuplicatable, TTI, &AC); 413 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n"); 414 415 // When computing the unrolled size, note that the conditional branch on the 416 // backedge and the comparison feeding it are not replicated like the rest of 417 // the loop body (which is why 2 is subtracted). 418 uint64_t UnrolledSize = (uint64_t)(LoopSize-2) * Count + 2; 419 if (notDuplicatable) { 420 DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable" 421 << " instructions.\n"); 422 return false; 423 } 424 if (NumInlineCandidates != 0) { 425 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n"); 426 return false; 427 } 428 429 unsigned Threshold, PartialThreshold; 430 selectThresholds(L, HasPragma, UP, Threshold, PartialThreshold); 431 432 // Given Count, TripCount and thresholds determine the type of 433 // unrolling which is to be performed. 434 enum { Full = 0, Partial = 1, Runtime = 2 }; 435 int Unrolling; 436 if (TripCount && Count == TripCount) { 437 if (Threshold != NoThreshold && UnrolledSize > Threshold) { 438 DEBUG(dbgs() << " Too large to fully unroll with count: " << Count 439 << " because size: " << UnrolledSize << ">" << Threshold 440 << "\n"); 441 Unrolling = Partial; 442 } else { 443 Unrolling = Full; 444 } 445 } else if (TripCount && Count < TripCount) { 446 Unrolling = Partial; 447 } else { 448 Unrolling = Runtime; 449 } 450 451 // Reduce count based on the type of unrolling and the threshold values. 452 unsigned OriginalCount = Count; 453 bool AllowRuntime = UserRuntime ? CurrentRuntime : UP.Runtime; 454 if (Unrolling == Partial) { 455 bool AllowPartial = UserAllowPartial ? CurrentAllowPartial : UP.Partial; 456 if (!AllowPartial && !CountSetExplicitly) { 457 DEBUG(dbgs() << " will not try to unroll partially because " 458 << "-unroll-allow-partial not given\n"); 459 return false; 460 } 461 if (PartialThreshold != NoThreshold && UnrolledSize > PartialThreshold) { 462 // Reduce unroll count to be modulo of TripCount for partial unrolling. 463 Count = (std::max(PartialThreshold, 3u)-2) / (LoopSize-2); 464 while (Count != 0 && TripCount % Count != 0) 465 Count--; 466 } 467 } else if (Unrolling == Runtime) { 468 if (!AllowRuntime && !CountSetExplicitly) { 469 DEBUG(dbgs() << " will not try to unroll loop with runtime trip count " 470 << "-unroll-runtime not given\n"); 471 return false; 472 } 473 // Reduce unroll count to be the largest power-of-two factor of 474 // the original count which satisfies the threshold limit. 475 while (Count != 0 && UnrolledSize > PartialThreshold) { 476 Count >>= 1; 477 UnrolledSize = (LoopSize-2) * Count + 2; 478 } 479 if (Count > UP.MaxCount) 480 Count = UP.MaxCount; 481 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n"); 482 } 483 484 if (HasPragma) { 485 if (PragmaCount != 0) 486 // If loop has an unroll count pragma mark loop as unrolled to prevent 487 // unrolling beyond that requested by the pragma. 488 SetLoopAlreadyUnrolled(L); 489 490 // Emit optimization remarks if we are unable to unroll the loop 491 // as directed by a pragma. 492 DebugLoc LoopLoc = L->getStartLoc(); 493 Function *F = Header->getParent(); 494 LLVMContext &Ctx = F->getContext(); 495 if (PragmaFullUnroll && PragmaCount == 0) { 496 if (TripCount && Count != TripCount) { 497 emitOptimizationRemarkMissed( 498 Ctx, DEBUG_TYPE, *F, LoopLoc, 499 "Unable to fully unroll loop as directed by unroll(full) pragma " 500 "because unrolled size is too large."); 501 } else if (!TripCount) { 502 emitOptimizationRemarkMissed( 503 Ctx, DEBUG_TYPE, *F, LoopLoc, 504 "Unable to fully unroll loop as directed by unroll(full) pragma " 505 "because loop has a runtime trip count."); 506 } 507 } else if (PragmaCount > 0 && Count != OriginalCount) { 508 emitOptimizationRemarkMissed( 509 Ctx, DEBUG_TYPE, *F, LoopLoc, 510 "Unable to unroll loop the number of times directed by " 511 "unroll_count pragma because unrolled size is too large."); 512 } 513 } 514 515 if (Unrolling != Full && Count < 2) { 516 // Partial unrolling by 1 is a nop. For full unrolling, a factor 517 // of 1 makes sense because loop control can be eliminated. 518 return false; 519 } 520 521 // Unroll the loop. 522 if (!UnrollLoop(L, Count, TripCount, AllowRuntime, TripMultiple, LI, this, 523 &LPM, &AC)) 524 return false; 525 526 return true; 527 } 528