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 #define DEBUG_TYPE "loop-unroll" 16 #include "llvm/IntrinsicInst.h" 17 #include "llvm/Transforms/Scalar.h" 18 #include "llvm/Analysis/LoopPass.h" 19 #include "llvm/Analysis/CodeMetrics.h" 20 #include "llvm/Analysis/ScalarEvolution.h" 21 #include "llvm/Support/CommandLine.h" 22 #include "llvm/Support/Debug.h" 23 #include "llvm/Support/raw_ostream.h" 24 #include "llvm/Transforms/Utils/UnrollLoop.h" 25 #include <climits> 26 27 using namespace llvm; 28 29 static cl::opt<unsigned> 30 UnrollThreshold("unroll-threshold", cl::init(150), cl::Hidden, 31 cl::desc("The cut-off point for automatic loop unrolling")); 32 33 static cl::opt<unsigned> 34 UnrollCount("unroll-count", cl::init(0), cl::Hidden, 35 cl::desc("Use this unroll count for all loops, for testing purposes")); 36 37 static cl::opt<bool> 38 UnrollAllowPartial("unroll-allow-partial", cl::init(false), cl::Hidden, 39 cl::desc("Allows loops to be partially unrolled until " 40 "-unroll-threshold loop size is reached.")); 41 42 namespace { 43 class LoopUnroll : public LoopPass { 44 public: 45 static char ID; // Pass ID, replacement for typeid 46 LoopUnroll(int T = -1, int C = -1, int P = -1) : LoopPass(ID) { 47 CurrentThreshold = (T == -1) ? UnrollThreshold : unsigned(T); 48 CurrentCount = (C == -1) ? UnrollCount : unsigned(C); 49 CurrentAllowPartial = (P == -1) ? UnrollAllowPartial : (bool)P; 50 51 UserThreshold = (T != -1) || (UnrollThreshold.getNumOccurrences() > 0); 52 53 initializeLoopUnrollPass(*PassRegistry::getPassRegistry()); 54 } 55 56 /// A magic value for use with the Threshold parameter to indicate 57 /// that the loop unroll should be performed regardless of how much 58 /// code expansion would result. 59 static const unsigned NoThreshold = UINT_MAX; 60 61 // Threshold to use when optsize is specified (and there is no 62 // explicit -unroll-threshold). 63 static const unsigned OptSizeUnrollThreshold = 50; 64 65 unsigned CurrentCount; 66 unsigned CurrentThreshold; 67 bool CurrentAllowPartial; 68 bool UserThreshold; // CurrentThreshold is user-specified. 69 70 bool runOnLoop(Loop *L, LPPassManager &LPM); 71 72 /// This transformation requires natural loop information & requires that 73 /// loop preheaders be inserted into the CFG... 74 /// 75 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 76 AU.addRequired<LoopInfo>(); 77 AU.addPreserved<LoopInfo>(); 78 AU.addRequiredID(LoopSimplifyID); 79 AU.addPreservedID(LoopSimplifyID); 80 AU.addRequiredID(LCSSAID); 81 AU.addPreservedID(LCSSAID); 82 AU.addRequired<ScalarEvolution>(); 83 AU.addPreserved<ScalarEvolution>(); 84 // FIXME: Loop unroll requires LCSSA. And LCSSA requires dom info. 85 // If loop unroll does not preserve dom info then LCSSA pass on next 86 // loop will receive invalid dom info. 87 // For now, recreate dom info, if loop is unrolled. 88 AU.addPreserved<DominatorTree>(); 89 } 90 }; 91 } 92 93 char LoopUnroll::ID = 0; 94 INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false) 95 INITIALIZE_PASS_DEPENDENCY(LoopInfo) 96 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 97 INITIALIZE_PASS_DEPENDENCY(LCSSA) 98 INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false) 99 100 Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial) { 101 return new LoopUnroll(Threshold, Count, AllowPartial); 102 } 103 104 /// ApproximateLoopSize - Approximate the size of the loop. 105 static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls) { 106 CodeMetrics Metrics; 107 for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 108 I != E; ++I) 109 Metrics.analyzeBasicBlock(*I); 110 NumCalls = Metrics.NumInlineCandidates; 111 112 unsigned LoopSize = Metrics.NumInsts; 113 114 // Don't allow an estimate of size zero. This would allows unrolling of loops 115 // with huge iteration counts, which is a compile time problem even if it's 116 // not a problem for code quality. 117 if (LoopSize == 0) LoopSize = 1; 118 119 return LoopSize; 120 } 121 122 bool LoopUnroll::runOnLoop(Loop *L, LPPassManager &LPM) { 123 LoopInfo *LI = &getAnalysis<LoopInfo>(); 124 125 BasicBlock *Header = L->getHeader(); 126 DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName() 127 << "] Loop %" << Header->getName() << "\n"); 128 (void)Header; 129 130 // Determine the current unrolling threshold. While this is normally set 131 // from UnrollThreshold, it is overridden to a smaller value if the current 132 // function is marked as optimize-for-size, and the unroll threshold was 133 // not user specified. 134 unsigned Threshold = CurrentThreshold; 135 if (!UserThreshold && 136 Header->getParent()->hasFnAttr(Attribute::OptimizeForSize)) 137 Threshold = OptSizeUnrollThreshold; 138 139 // Find trip count 140 unsigned TripCount = L->getSmallConstantTripCount(); 141 142 // Find trip multiple if count is not available 143 unsigned TripMultiple = 1; 144 if (TripCount == 0) 145 TripMultiple = L->getSmallConstantTripMultiple(); 146 147 // Automatically select an unroll count. 148 unsigned Count = CurrentCount; 149 if (Count == 0) { 150 // Conservative heuristic: if we know the trip count, see if we can 151 // completely unroll (subject to the threshold, checked below); otherwise 152 // try to find greatest modulo of the trip count which is still under 153 // threshold value. 154 if (TripCount == 0) 155 return false; 156 Count = TripCount; 157 } 158 159 // Enforce the threshold. 160 if (Threshold != NoThreshold) { 161 unsigned NumInlineCandidates; 162 unsigned LoopSize = ApproximateLoopSize(L, NumInlineCandidates); 163 DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n"); 164 if (NumInlineCandidates != 0) { 165 DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n"); 166 return false; 167 } 168 uint64_t Size = (uint64_t)LoopSize*Count; 169 if (TripCount != 1 && Size > Threshold) { 170 DEBUG(dbgs() << " Too large to fully unroll with count: " << Count 171 << " because size: " << Size << ">" << Threshold << "\n"); 172 if (!CurrentAllowPartial) { 173 DEBUG(dbgs() << " will not try to unroll partially because " 174 << "-unroll-allow-partial not given\n"); 175 return false; 176 } 177 // Reduce unroll count to be modulo of TripCount for partial unrolling 178 Count = Threshold / LoopSize; 179 while (Count != 0 && TripCount%Count != 0) { 180 Count--; 181 } 182 if (Count < 2) { 183 DEBUG(dbgs() << " could not unroll partially\n"); 184 return false; 185 } 186 DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n"); 187 } 188 } 189 190 // Unroll the loop. 191 if (!UnrollLoop(L, Count, TripCount, TripMultiple, LI, &LPM)) 192 return false; 193 194 return true; 195 } 196