Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 1 | //===-- LoopUnroll.cpp - Loop unroller pass -------------------------------===// |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 2 | // |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
Chris Lattner | f3ebc3f | 2007-12-29 20:36:04 +0000 | [diff] [blame] | 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 7 | // |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 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. |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 13 | //===----------------------------------------------------------------------===// |
| 14 | |
Chandler Carruth | 3b057b3 | 2015-02-13 03:57:40 +0000 | [diff] [blame] | 15 | #include "llvm/ADT/SetVector.h" |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 16 | #include "llvm/Analysis/AssumptionCache.h" |
Chris Lattner | 679572e | 2011-01-02 07:35:53 +0000 | [diff] [blame] | 17 | #include "llvm/Analysis/CodeMetrics.h" |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 18 | #include "llvm/Analysis/GlobalsModRef.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 19 | #include "llvm/Analysis/InstructionSimplify.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 20 | #include "llvm/Analysis/LoopPass.h" |
Michael Zolotukhin | 1da4afd | 2016-02-08 23:03:59 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/LoopUnrollAnalyzer.h" |
Dan Gohman | 0141c13 | 2010-07-26 18:11:16 +0000 | [diff] [blame] | 22 | #include "llvm/Analysis/ScalarEvolution.h" |
Michael Zolotukhin | a9aadd2 | 2015-02-05 02:34:00 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Chandler Carruth | bb9caa9 | 2013-01-21 13:04:33 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/TargetTransformInfo.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 25 | #include "llvm/IR/DataLayout.h" |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 26 | #include "llvm/IR/DiagnosticInfo.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 27 | #include "llvm/IR/Dominators.h" |
Benjamin Kramer | 799003b | 2015-03-23 19:32:43 +0000 | [diff] [blame] | 28 | #include "llvm/IR/InstVisitor.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 29 | #include "llvm/IR/IntrinsicInst.h" |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 30 | #include "llvm/IR/Metadata.h" |
Reid Spencer | 7c16caa | 2004-09-01 22:55:40 +0000 | [diff] [blame] | 31 | #include "llvm/Support/CommandLine.h" |
| 32 | #include "llvm/Support/Debug.h" |
Daniel Dunbar | 0dd5e1e | 2009-07-25 00:23:56 +0000 | [diff] [blame] | 33 | #include "llvm/Support/raw_ostream.h" |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 34 | #include "llvm/Transforms/Scalar.h" |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 35 | #include "llvm/Transforms/Utils/LoopUtils.h" |
Dan Gohman | 3dc2d92 | 2008-05-14 00:24:14 +0000 | [diff] [blame] | 36 | #include "llvm/Transforms/Utils/UnrollLoop.h" |
Duncan Sands | 67933e6 | 2008-05-16 09:30:00 +0000 | [diff] [blame] | 37 | #include <climits> |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 38 | |
Dan Gohman | 3dc2d92 | 2008-05-14 00:24:14 +0000 | [diff] [blame] | 39 | using namespace llvm; |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 40 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 41 | #define DEBUG_TYPE "loop-unroll" |
| 42 | |
Dan Gohman | d78c400 | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 43 | static cl::opt<unsigned> |
Justin Bogner | a1dd493 | 2016-01-12 00:55:26 +0000 | [diff] [blame] | 44 | UnrollThreshold("unroll-threshold", cl::Hidden, |
Chandler Carruth | 9dabd14 | 2015-06-05 17:01:43 +0000 | [diff] [blame] | 45 | cl::desc("The baseline cost threshold for loop unrolling")); |
| 46 | |
| 47 | static cl::opt<unsigned> UnrollPercentDynamicCostSavedThreshold( |
Michael Zolotukhin | 8f7a242 | 2016-05-24 23:00:05 +0000 | [diff] [blame] | 48 | "unroll-percent-dynamic-cost-saved-threshold", cl::init(50), cl::Hidden, |
Chandler Carruth | 9dabd14 | 2015-06-05 17:01:43 +0000 | [diff] [blame] | 49 | cl::desc("The percentage of estimated dynamic cost which must be saved by " |
| 50 | "unrolling to allow unrolling up to the max threshold.")); |
| 51 | |
| 52 | static cl::opt<unsigned> UnrollDynamicCostSavingsDiscount( |
Michael Zolotukhin | 8f7a242 | 2016-05-24 23:00:05 +0000 | [diff] [blame] | 53 | "unroll-dynamic-cost-savings-discount", cl::init(100), cl::Hidden, |
Chandler Carruth | 9dabd14 | 2015-06-05 17:01:43 +0000 | [diff] [blame] | 54 | cl::desc("This is the amount discounted from the total unroll cost when " |
| 55 | "the unrolled form has a high dynamic cost savings (triggered by " |
| 56 | "the '-unroll-perecent-dynamic-cost-saved-threshold' flag).")); |
Dan Gohman | d78c400 | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 57 | |
Michael Zolotukhin | a9aadd2 | 2015-02-05 02:34:00 +0000 | [diff] [blame] | 58 | static cl::opt<unsigned> UnrollMaxIterationsCountToAnalyze( |
Michael Zolotukhin | 8f7a242 | 2016-05-24 23:00:05 +0000 | [diff] [blame] | 59 | "unroll-max-iteration-count-to-analyze", cl::init(10), cl::Hidden, |
Michael Zolotukhin | a9aadd2 | 2015-02-05 02:34:00 +0000 | [diff] [blame] | 60 | cl::desc("Don't allow loop unrolling to simulate more than this number of" |
| 61 | "iterations when checking full unroll profitability")); |
| 62 | |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 63 | static cl::opt<unsigned> UnrollCount( |
| 64 | "unroll-count", cl::Hidden, |
| 65 | cl::desc("Use this unroll count for all loops including those with " |
| 66 | "unroll_count pragma values, for testing purposes")); |
Dan Gohman | d78c400 | 2008-05-13 00:00:25 +0000 | [diff] [blame] | 67 | |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 68 | static cl::opt<unsigned> UnrollMaxCount( |
| 69 | "unroll-max-count", cl::Hidden, |
| 70 | cl::desc("Set the max unroll count for partial and runtime unrolling, for" |
| 71 | "testing purposes")); |
Fiona Glaser | 045afc4 | 2016-04-06 16:57:25 +0000 | [diff] [blame] | 72 | |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 73 | static cl::opt<unsigned> UnrollFullMaxCount( |
| 74 | "unroll-full-max-count", cl::Hidden, |
| 75 | cl::desc( |
| 76 | "Set the max unroll count for full unrolling, for testing purposes")); |
Fiona Glaser | 045afc4 | 2016-04-06 16:57:25 +0000 | [diff] [blame] | 77 | |
Matthijs Kooijman | 98b5c16 | 2008-07-29 13:21:23 +0000 | [diff] [blame] | 78 | static cl::opt<bool> |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 79 | UnrollAllowPartial("unroll-allow-partial", cl::Hidden, |
| 80 | cl::desc("Allows loops to be partially unrolled until " |
| 81 | "-unroll-threshold loop size is reached.")); |
Matthijs Kooijman | 98b5c16 | 2008-07-29 13:21:23 +0000 | [diff] [blame] | 82 | |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 83 | static cl::opt<bool> |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 84 | UnrollRuntime("unroll-runtime", cl::ZeroOrMore, cl::Hidden, |
| 85 | cl::desc("Unroll loops with run-time trip counts")); |
Andrew Trick | d04d1529 | 2011-12-09 06:19:40 +0000 | [diff] [blame] | 86 | |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 87 | static cl::opt<unsigned> PragmaUnrollThreshold( |
| 88 | "pragma-unroll-threshold", cl::init(16 * 1024), cl::Hidden, |
| 89 | cl::desc("Unrolled size limit for loops with an unroll(full) or " |
| 90 | "unroll_count pragma.")); |
Justin Bogner | a1dd493 | 2016-01-12 00:55:26 +0000 | [diff] [blame] | 91 | |
| 92 | /// A magic value for use with the Threshold parameter to indicate |
| 93 | /// that the loop unroll should be performed regardless of how much |
| 94 | /// code expansion would result. |
| 95 | static const unsigned NoThreshold = UINT_MAX; |
| 96 | |
| 97 | /// Default unroll count for loops with run-time trip count if |
| 98 | /// -unroll-count is not set |
| 99 | static const unsigned DefaultUnrollRuntimeCount = 8; |
| 100 | |
| 101 | /// Gather the various unrolling parameters based on the defaults, compiler |
| 102 | /// flags, TTI overrides, pragmas, and user specified parameters. |
| 103 | static TargetTransformInfo::UnrollingPreferences gatherUnrollingPreferences( |
| 104 | Loop *L, const TargetTransformInfo &TTI, Optional<unsigned> UserThreshold, |
| 105 | Optional<unsigned> UserCount, Optional<bool> UserAllowPartial, |
| 106 | Optional<bool> UserRuntime, unsigned PragmaCount, bool PragmaFullUnroll, |
| 107 | bool PragmaEnableUnroll, unsigned TripCount) { |
| 108 | TargetTransformInfo::UnrollingPreferences UP; |
| 109 | |
| 110 | // Set up the defaults |
| 111 | UP.Threshold = 150; |
| 112 | UP.PercentDynamicCostSavedThreshold = 20; |
| 113 | UP.DynamicCostSavingsDiscount = 2000; |
Hans Wennborg | 719b26b | 2016-05-10 21:45:55 +0000 | [diff] [blame] | 114 | UP.OptSizeThreshold = 0; |
Justin Bogner | a1dd493 | 2016-01-12 00:55:26 +0000 | [diff] [blame] | 115 | UP.PartialThreshold = UP.Threshold; |
Hans Wennborg | 719b26b | 2016-05-10 21:45:55 +0000 | [diff] [blame] | 116 | UP.PartialOptSizeThreshold = 0; |
Justin Bogner | a1dd493 | 2016-01-12 00:55:26 +0000 | [diff] [blame] | 117 | UP.Count = 0; |
| 118 | UP.MaxCount = UINT_MAX; |
Fiona Glaser | 045afc4 | 2016-04-06 16:57:25 +0000 | [diff] [blame] | 119 | UP.FullUnrollMaxCount = UINT_MAX; |
Justin Bogner | a1dd493 | 2016-01-12 00:55:26 +0000 | [diff] [blame] | 120 | UP.Partial = false; |
| 121 | UP.Runtime = false; |
| 122 | UP.AllowExpensiveTripCount = false; |
| 123 | |
| 124 | // Override with any target specific settings |
| 125 | TTI.getUnrollingPreferences(L, UP); |
| 126 | |
| 127 | // Apply size attributes |
| 128 | if (L->getHeader()->getParent()->optForSize()) { |
| 129 | UP.Threshold = UP.OptSizeThreshold; |
| 130 | UP.PartialThreshold = UP.PartialOptSizeThreshold; |
| 131 | } |
| 132 | |
| 133 | // Apply unroll count pragmas |
| 134 | if (PragmaCount) |
| 135 | UP.Count = PragmaCount; |
| 136 | else if (PragmaFullUnroll) |
| 137 | UP.Count = TripCount; |
| 138 | |
| 139 | // Apply any user values specified by cl::opt |
| 140 | if (UnrollThreshold.getNumOccurrences() > 0) { |
| 141 | UP.Threshold = UnrollThreshold; |
| 142 | UP.PartialThreshold = UnrollThreshold; |
| 143 | } |
| 144 | if (UnrollPercentDynamicCostSavedThreshold.getNumOccurrences() > 0) |
| 145 | UP.PercentDynamicCostSavedThreshold = |
| 146 | UnrollPercentDynamicCostSavedThreshold; |
| 147 | if (UnrollDynamicCostSavingsDiscount.getNumOccurrences() > 0) |
| 148 | UP.DynamicCostSavingsDiscount = UnrollDynamicCostSavingsDiscount; |
| 149 | if (UnrollCount.getNumOccurrences() > 0) |
| 150 | UP.Count = UnrollCount; |
Fiona Glaser | 045afc4 | 2016-04-06 16:57:25 +0000 | [diff] [blame] | 151 | if (UnrollMaxCount.getNumOccurrences() > 0) |
| 152 | UP.MaxCount = UnrollMaxCount; |
| 153 | if (UnrollFullMaxCount.getNumOccurrences() > 0) |
| 154 | UP.FullUnrollMaxCount = UnrollFullMaxCount; |
Justin Bogner | a1dd493 | 2016-01-12 00:55:26 +0000 | [diff] [blame] | 155 | if (UnrollAllowPartial.getNumOccurrences() > 0) |
| 156 | UP.Partial = UnrollAllowPartial; |
| 157 | if (UnrollRuntime.getNumOccurrences() > 0) |
| 158 | UP.Runtime = UnrollRuntime; |
| 159 | |
| 160 | // Apply user values provided by argument |
| 161 | if (UserThreshold.hasValue()) { |
| 162 | UP.Threshold = *UserThreshold; |
| 163 | UP.PartialThreshold = *UserThreshold; |
| 164 | } |
| 165 | if (UserCount.hasValue()) |
| 166 | UP.Count = *UserCount; |
| 167 | if (UserAllowPartial.hasValue()) |
| 168 | UP.Partial = *UserAllowPartial; |
| 169 | if (UserRuntime.hasValue()) |
| 170 | UP.Runtime = *UserRuntime; |
| 171 | |
| 172 | if (PragmaCount > 0 || |
| 173 | ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount != 0)) { |
| 174 | // If the loop has an unrolling pragma, we want to be more aggressive with |
| 175 | // unrolling limits. Set thresholds to at least the PragmaTheshold value |
| 176 | // which is larger than the default limits. |
| 177 | if (UP.Threshold != NoThreshold) |
| 178 | UP.Threshold = std::max<unsigned>(UP.Threshold, PragmaUnrollThreshold); |
| 179 | if (UP.PartialThreshold != NoThreshold) |
| 180 | UP.PartialThreshold = |
| 181 | std::max<unsigned>(UP.PartialThreshold, PragmaUnrollThreshold); |
| 182 | } |
| 183 | |
| 184 | return UP; |
| 185 | } |
| 186 | |
Chris Lattner | 79a42ac | 2006-12-19 21:40:18 +0000 | [diff] [blame] | 187 | namespace { |
Michael Zolotukhin | 963a6d9 | 2016-05-13 21:23:25 +0000 | [diff] [blame] | 188 | /// A struct to densely store the state of an instruction after unrolling at |
| 189 | /// each iteration. |
| 190 | /// |
| 191 | /// This is designed to work like a tuple of <Instruction *, int> for the |
| 192 | /// purposes of hashing and lookup, but to be able to associate two boolean |
| 193 | /// states with each key. |
| 194 | struct UnrolledInstState { |
| 195 | Instruction *I; |
| 196 | int Iteration : 30; |
| 197 | unsigned IsFree : 1; |
| 198 | unsigned IsCounted : 1; |
| 199 | }; |
| 200 | |
| 201 | /// Hashing and equality testing for a set of the instruction states. |
| 202 | struct UnrolledInstStateKeyInfo { |
| 203 | typedef DenseMapInfo<Instruction *> PtrInfo; |
| 204 | typedef DenseMapInfo<std::pair<Instruction *, int>> PairInfo; |
| 205 | static inline UnrolledInstState getEmptyKey() { |
| 206 | return {PtrInfo::getEmptyKey(), 0, 0, 0}; |
| 207 | } |
| 208 | static inline UnrolledInstState getTombstoneKey() { |
| 209 | return {PtrInfo::getTombstoneKey(), 0, 0, 0}; |
| 210 | } |
| 211 | static inline unsigned getHashValue(const UnrolledInstState &S) { |
| 212 | return PairInfo::getHashValue({S.I, S.Iteration}); |
| 213 | } |
| 214 | static inline bool isEqual(const UnrolledInstState &LHS, |
| 215 | const UnrolledInstState &RHS) { |
| 216 | return PairInfo::isEqual({LHS.I, LHS.Iteration}, {RHS.I, RHS.Iteration}); |
| 217 | } |
| 218 | }; |
| 219 | } |
| 220 | |
| 221 | namespace { |
Chandler Carruth | 0215608 | 2015-05-22 17:41:35 +0000 | [diff] [blame] | 222 | struct EstimatedUnrollCost { |
Chandler Carruth | 9dabd14 | 2015-06-05 17:01:43 +0000 | [diff] [blame] | 223 | /// \brief The estimated cost after unrolling. |
Chandler Carruth | b2fda0d | 2015-08-05 18:46:21 +0000 | [diff] [blame] | 224 | int UnrolledCost; |
Chandler Carruth | 302a133 | 2015-02-13 02:10:56 +0000 | [diff] [blame] | 225 | |
Chandler Carruth | 9dabd14 | 2015-06-05 17:01:43 +0000 | [diff] [blame] | 226 | /// \brief The estimated dynamic cost of executing the instructions in the |
| 227 | /// rolled form. |
Chandler Carruth | b2fda0d | 2015-08-05 18:46:21 +0000 | [diff] [blame] | 228 | int RolledDynamicCost; |
Chandler Carruth | 0215608 | 2015-05-22 17:41:35 +0000 | [diff] [blame] | 229 | }; |
| 230 | } |
Michael Zolotukhin | a9aadd2 | 2015-02-05 02:34:00 +0000 | [diff] [blame] | 231 | |
Chandler Carruth | 0215608 | 2015-05-22 17:41:35 +0000 | [diff] [blame] | 232 | /// \brief Figure out if the loop is worth full unrolling. |
| 233 | /// |
| 234 | /// Complete loop unrolling can make some loads constant, and we need to know |
| 235 | /// if that would expose any further optimization opportunities. This routine |
Michael Zolotukhin | c4e4f33 | 2015-06-11 22:17:39 +0000 | [diff] [blame] | 236 | /// estimates this optimization. It computes cost of unrolled loop |
| 237 | /// (UnrolledCost) and dynamic cost of the original loop (RolledDynamicCost). By |
| 238 | /// dynamic cost we mean that we won't count costs of blocks that are known not |
| 239 | /// to be executed (i.e. if we have a branch in the loop and we know that at the |
| 240 | /// given iteration its condition would be resolved to true, we won't add up the |
| 241 | /// cost of the 'false'-block). |
| 242 | /// \returns Optional value, holding the RolledDynamicCost and UnrolledCost. If |
| 243 | /// the analysis failed (no benefits expected from the unrolling, or the loop is |
| 244 | /// too big to analyze), the returned value is None. |
Benjamin Kramer | fcdb1c1 | 2015-08-20 09:57:22 +0000 | [diff] [blame] | 245 | static Optional<EstimatedUnrollCost> |
Chandler Carruth | 87adb7a | 2015-08-03 20:32:27 +0000 | [diff] [blame] | 246 | analyzeLoopUnrollCost(const Loop *L, unsigned TripCount, DominatorTree &DT, |
| 247 | ScalarEvolution &SE, const TargetTransformInfo &TTI, |
Chandler Carruth | b2fda0d | 2015-08-05 18:46:21 +0000 | [diff] [blame] | 248 | int MaxUnrolledLoopSize) { |
Chandler Carruth | 0215608 | 2015-05-22 17:41:35 +0000 | [diff] [blame] | 249 | // We want to be able to scale offsets by the trip count and add more offsets |
| 250 | // to them without checking for overflows, and we already don't want to |
| 251 | // analyze *massive* trip counts, so we force the max to be reasonably small. |
| 252 | assert(UnrollMaxIterationsCountToAnalyze < (INT_MAX / 2) && |
| 253 | "The unroll iterations max is too large!"); |
Michael Zolotukhin | a9aadd2 | 2015-02-05 02:34:00 +0000 | [diff] [blame] | 254 | |
Michael Zolotukhin | 963a6d9 | 2016-05-13 21:23:25 +0000 | [diff] [blame] | 255 | // Only analyze inner loops. We can't properly estimate cost of nested loops |
| 256 | // and we won't visit inner loops again anyway. |
| 257 | if (!L->empty()) |
| 258 | return None; |
| 259 | |
Chandler Carruth | 0215608 | 2015-05-22 17:41:35 +0000 | [diff] [blame] | 260 | // Don't simulate loops with a big or unknown tripcount |
| 261 | if (!UnrollMaxIterationsCountToAnalyze || !TripCount || |
| 262 | TripCount > UnrollMaxIterationsCountToAnalyze) |
| 263 | return None; |
Chandler Carruth | a6ae877 | 2015-05-12 23:32:56 +0000 | [diff] [blame] | 264 | |
Chandler Carruth | 0215608 | 2015-05-22 17:41:35 +0000 | [diff] [blame] | 265 | SmallSetVector<BasicBlock *, 16> BBWorklist; |
Michael Zolotukhin | 963a6d9 | 2016-05-13 21:23:25 +0000 | [diff] [blame] | 266 | SmallSetVector<std::pair<BasicBlock *, BasicBlock *>, 4> ExitWorklist; |
Chandler Carruth | 0215608 | 2015-05-22 17:41:35 +0000 | [diff] [blame] | 267 | DenseMap<Value *, Constant *> SimplifiedValues; |
Chandler Carruth | 87adb7a | 2015-08-03 20:32:27 +0000 | [diff] [blame] | 268 | SmallVector<std::pair<Value *, Constant *>, 4> SimplifiedInputValues; |
Chandler Carruth | 3b057b3 | 2015-02-13 03:57:40 +0000 | [diff] [blame] | 269 | |
Chandler Carruth | 9dabd14 | 2015-06-05 17:01:43 +0000 | [diff] [blame] | 270 | // The estimated cost of the unrolled form of the loop. We try to estimate |
| 271 | // this by simplifying as much as we can while computing the estimate. |
Chandler Carruth | b2fda0d | 2015-08-05 18:46:21 +0000 | [diff] [blame] | 272 | int UnrolledCost = 0; |
Michael Zolotukhin | 963a6d9 | 2016-05-13 21:23:25 +0000 | [diff] [blame] | 273 | |
Chandler Carruth | 9dabd14 | 2015-06-05 17:01:43 +0000 | [diff] [blame] | 274 | // We also track the estimated dynamic (that is, actually executed) cost in |
| 275 | // the rolled form. This helps identify cases when the savings from unrolling |
| 276 | // aren't just exposing dead control flows, but actual reduced dynamic |
| 277 | // instructions due to the simplifications which we expect to occur after |
| 278 | // unrolling. |
Chandler Carruth | b2fda0d | 2015-08-05 18:46:21 +0000 | [diff] [blame] | 279 | int RolledDynamicCost = 0; |
Chandler Carruth | 8c86375 | 2015-02-13 03:48:38 +0000 | [diff] [blame] | 280 | |
Michael Zolotukhin | 963a6d9 | 2016-05-13 21:23:25 +0000 | [diff] [blame] | 281 | // We track the simplification of each instruction in each iteration. We use |
| 282 | // this to recursively merge costs into the unrolled cost on-demand so that |
| 283 | // we don't count the cost of any dead code. This is essentially a map from |
| 284 | // <instruction, int> to <bool, bool>, but stored as a densely packed struct. |
| 285 | DenseSet<UnrolledInstState, UnrolledInstStateKeyInfo> InstCostMap; |
| 286 | |
| 287 | // A small worklist used to accumulate cost of instructions from each |
| 288 | // observable and reached root in the loop. |
| 289 | SmallVector<Instruction *, 16> CostWorklist; |
| 290 | |
| 291 | // PHI-used worklist used between iterations while accumulating cost. |
| 292 | SmallVector<Instruction *, 4> PHIUsedList; |
| 293 | |
| 294 | // Helper function to accumulate cost for instructions in the loop. |
| 295 | auto AddCostRecursively = [&](Instruction &RootI, int Iteration) { |
| 296 | assert(Iteration >= 0 && "Cannot have a negative iteration!"); |
| 297 | assert(CostWorklist.empty() && "Must start with an empty cost list"); |
| 298 | assert(PHIUsedList.empty() && "Must start with an empty phi used list"); |
| 299 | CostWorklist.push_back(&RootI); |
| 300 | for (;; --Iteration) { |
| 301 | do { |
| 302 | Instruction *I = CostWorklist.pop_back_val(); |
| 303 | |
| 304 | // InstCostMap only uses I and Iteration as a key, the other two values |
| 305 | // don't matter here. |
| 306 | auto CostIter = InstCostMap.find({I, Iteration, 0, 0}); |
| 307 | if (CostIter == InstCostMap.end()) |
| 308 | // If an input to a PHI node comes from a dead path through the loop |
| 309 | // we may have no cost data for it here. What that actually means is |
| 310 | // that it is free. |
| 311 | continue; |
| 312 | auto &Cost = *CostIter; |
| 313 | if (Cost.IsCounted) |
| 314 | // Already counted this instruction. |
| 315 | continue; |
| 316 | |
| 317 | // Mark that we are counting the cost of this instruction now. |
| 318 | Cost.IsCounted = true; |
| 319 | |
| 320 | // If this is a PHI node in the loop header, just add it to the PHI set. |
| 321 | if (auto *PhiI = dyn_cast<PHINode>(I)) |
| 322 | if (PhiI->getParent() == L->getHeader()) { |
| 323 | assert(Cost.IsFree && "Loop PHIs shouldn't be evaluated as they " |
| 324 | "inherently simplify during unrolling."); |
| 325 | if (Iteration == 0) |
| 326 | continue; |
| 327 | |
| 328 | // Push the incoming value from the backedge into the PHI used list |
| 329 | // if it is an in-loop instruction. We'll use this to populate the |
| 330 | // cost worklist for the next iteration (as we count backwards). |
| 331 | if (auto *OpI = dyn_cast<Instruction>( |
| 332 | PhiI->getIncomingValueForBlock(L->getLoopLatch()))) |
| 333 | if (L->contains(OpI)) |
| 334 | PHIUsedList.push_back(OpI); |
| 335 | continue; |
| 336 | } |
| 337 | |
| 338 | // First accumulate the cost of this instruction. |
| 339 | if (!Cost.IsFree) { |
| 340 | UnrolledCost += TTI.getUserCost(I); |
| 341 | DEBUG(dbgs() << "Adding cost of instruction (iteration " << Iteration |
| 342 | << "): "); |
| 343 | DEBUG(I->dump()); |
| 344 | } |
| 345 | |
| 346 | // We must count the cost of every operand which is not free, |
| 347 | // recursively. If we reach a loop PHI node, simply add it to the set |
| 348 | // to be considered on the next iteration (backwards!). |
| 349 | for (Value *Op : I->operands()) { |
| 350 | // Check whether this operand is free due to being a constant or |
| 351 | // outside the loop. |
| 352 | auto *OpI = dyn_cast<Instruction>(Op); |
| 353 | if (!OpI || !L->contains(OpI)) |
| 354 | continue; |
| 355 | |
| 356 | // Otherwise accumulate its cost. |
| 357 | CostWorklist.push_back(OpI); |
| 358 | } |
| 359 | } while (!CostWorklist.empty()); |
| 360 | |
| 361 | if (PHIUsedList.empty()) |
| 362 | // We've exhausted the search. |
| 363 | break; |
| 364 | |
| 365 | assert(Iteration > 0 && |
| 366 | "Cannot track PHI-used values past the first iteration!"); |
| 367 | CostWorklist.append(PHIUsedList.begin(), PHIUsedList.end()); |
| 368 | PHIUsedList.clear(); |
| 369 | } |
| 370 | }; |
| 371 | |
Chandler Carruth | 87adb7a | 2015-08-03 20:32:27 +0000 | [diff] [blame] | 372 | // Ensure that we don't violate the loop structure invariants relied on by |
| 373 | // this analysis. |
| 374 | assert(L->isLoopSimplifyForm() && "Must put loop into normal form first."); |
| 375 | assert(L->isLCSSAForm(DT) && |
| 376 | "Must have loops in LCSSA form to track live-out values."); |
| 377 | |
Michael Zolotukhin | 80d13ba | 2015-07-28 20:07:29 +0000 | [diff] [blame] | 378 | DEBUG(dbgs() << "Starting LoopUnroll profitability analysis...\n"); |
| 379 | |
Chandler Carruth | 0215608 | 2015-05-22 17:41:35 +0000 | [diff] [blame] | 380 | // Simulate execution of each iteration of the loop counting instructions, |
| 381 | // which would be simplified. |
| 382 | // Since the same load will take different values on different iterations, |
| 383 | // we literally have to go through all loop's iterations. |
| 384 | for (unsigned Iteration = 0; Iteration < TripCount; ++Iteration) { |
Michael Zolotukhin | 80d13ba | 2015-07-28 20:07:29 +0000 | [diff] [blame] | 385 | DEBUG(dbgs() << " Analyzing iteration " << Iteration << "\n"); |
Chandler Carruth | 87adb7a | 2015-08-03 20:32:27 +0000 | [diff] [blame] | 386 | |
| 387 | // Prepare for the iteration by collecting any simplified entry or backedge |
| 388 | // inputs. |
| 389 | for (Instruction &I : *L->getHeader()) { |
| 390 | auto *PHI = dyn_cast<PHINode>(&I); |
| 391 | if (!PHI) |
| 392 | break; |
| 393 | |
| 394 | // The loop header PHI nodes must have exactly two input: one from the |
| 395 | // loop preheader and one from the loop latch. |
| 396 | assert( |
| 397 | PHI->getNumIncomingValues() == 2 && |
| 398 | "Must have an incoming value only for the preheader and the latch."); |
| 399 | |
| 400 | Value *V = PHI->getIncomingValueForBlock( |
| 401 | Iteration == 0 ? L->getLoopPreheader() : L->getLoopLatch()); |
| 402 | Constant *C = dyn_cast<Constant>(V); |
| 403 | if (Iteration != 0 && !C) |
| 404 | C = SimplifiedValues.lookup(V); |
| 405 | if (C) |
| 406 | SimplifiedInputValues.push_back({PHI, C}); |
| 407 | } |
| 408 | |
| 409 | // Now clear and re-populate the map for the next iteration. |
Chandler Carruth | 0215608 | 2015-05-22 17:41:35 +0000 | [diff] [blame] | 410 | SimplifiedValues.clear(); |
Chandler Carruth | 87adb7a | 2015-08-03 20:32:27 +0000 | [diff] [blame] | 411 | while (!SimplifiedInputValues.empty()) |
| 412 | SimplifiedValues.insert(SimplifiedInputValues.pop_back_val()); |
| 413 | |
Michael Zolotukhin | 9f520eb | 2016-02-26 02:57:05 +0000 | [diff] [blame] | 414 | UnrolledInstAnalyzer Analyzer(Iteration, SimplifiedValues, SE, L); |
Chandler Carruth | f174a15 | 2015-05-22 02:47:29 +0000 | [diff] [blame] | 415 | |
Chandler Carruth | 0215608 | 2015-05-22 17:41:35 +0000 | [diff] [blame] | 416 | BBWorklist.clear(); |
| 417 | BBWorklist.insert(L->getHeader()); |
| 418 | // Note that we *must not* cache the size, this loop grows the worklist. |
| 419 | for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) { |
| 420 | BasicBlock *BB = BBWorklist[Idx]; |
Chandler Carruth | f174a15 | 2015-05-22 02:47:29 +0000 | [diff] [blame] | 421 | |
Chandler Carruth | 0215608 | 2015-05-22 17:41:35 +0000 | [diff] [blame] | 422 | // Visit all instructions in the given basic block and try to simplify |
| 423 | // it. We don't change the actual IR, just count optimization |
| 424 | // opportunities. |
| 425 | for (Instruction &I : *BB) { |
Michael Zolotukhin | 963a6d9 | 2016-05-13 21:23:25 +0000 | [diff] [blame] | 426 | // Track this instruction's expected baseline cost when executing the |
| 427 | // rolled loop form. |
| 428 | RolledDynamicCost += TTI.getUserCost(&I); |
Chandler Carruth | 17a0496 | 2015-02-13 03:49:41 +0000 | [diff] [blame] | 429 | |
Chandler Carruth | 0215608 | 2015-05-22 17:41:35 +0000 | [diff] [blame] | 430 | // Visit the instruction to analyze its loop cost after unrolling, |
Michael Zolotukhin | 963a6d9 | 2016-05-13 21:23:25 +0000 | [diff] [blame] | 431 | // and if the visitor returns true, mark the instruction as free after |
| 432 | // unrolling and continue. |
| 433 | bool IsFree = Analyzer.visit(I); |
| 434 | bool Inserted = InstCostMap.insert({&I, (int)Iteration, |
| 435 | (unsigned)IsFree, |
| 436 | /*IsCounted*/ false}).second; |
| 437 | (void)Inserted; |
| 438 | assert(Inserted && "Cannot have a state for an unvisited instruction!"); |
Chandler Carruth | 9dabd14 | 2015-06-05 17:01:43 +0000 | [diff] [blame] | 439 | |
Michael Zolotukhin | 963a6d9 | 2016-05-13 21:23:25 +0000 | [diff] [blame] | 440 | if (IsFree) |
| 441 | continue; |
| 442 | |
| 443 | // If the instruction might have a side-effect recursively account for |
| 444 | // the cost of it and all the instructions leading up to it. |
| 445 | if (I.mayHaveSideEffects()) |
| 446 | AddCostRecursively(I, Iteration); |
| 447 | |
| 448 | // Can't properly model a cost of a call. |
| 449 | // FIXME: With a proper cost model we should be able to do it. |
| 450 | if(isa<CallInst>(&I)) |
| 451 | return None; |
Chandler Carruth | 0215608 | 2015-05-22 17:41:35 +0000 | [diff] [blame] | 452 | |
| 453 | // If unrolled body turns out to be too big, bail out. |
Michael Zolotukhin | 80d13ba | 2015-07-28 20:07:29 +0000 | [diff] [blame] | 454 | if (UnrolledCost > MaxUnrolledLoopSize) { |
| 455 | DEBUG(dbgs() << " Exceeded threshold.. exiting.\n" |
| 456 | << " UnrolledCost: " << UnrolledCost |
| 457 | << ", MaxUnrolledLoopSize: " << MaxUnrolledLoopSize |
| 458 | << "\n"); |
Chandler Carruth | 0215608 | 2015-05-22 17:41:35 +0000 | [diff] [blame] | 459 | return None; |
Michael Zolotukhin | 80d13ba | 2015-07-28 20:07:29 +0000 | [diff] [blame] | 460 | } |
Michael Zolotukhin | a9aadd2 | 2015-02-05 02:34:00 +0000 | [diff] [blame] | 461 | } |
Chandler Carruth | 415f412 | 2015-02-13 02:17:39 +0000 | [diff] [blame] | 462 | |
Michael Zolotukhin | 57776b8 | 2015-07-24 01:53:04 +0000 | [diff] [blame] | 463 | TerminatorInst *TI = BB->getTerminator(); |
| 464 | |
| 465 | // Add in the live successors by first checking whether we have terminator |
| 466 | // that may be simplified based on the values simplified by this call. |
Michael Zolotukhin | 1ecdeda | 2016-05-26 21:42:51 +0000 | [diff] [blame^] | 467 | BasicBlock *KnownSucc = nullptr; |
Michael Zolotukhin | 57776b8 | 2015-07-24 01:53:04 +0000 | [diff] [blame] | 468 | if (BranchInst *BI = dyn_cast<BranchInst>(TI)) { |
| 469 | if (BI->isConditional()) { |
| 470 | if (Constant *SimpleCond = |
| 471 | SimplifiedValues.lookup(BI->getCondition())) { |
Michael Zolotukhin | 3a7d55b | 2015-07-29 18:10:29 +0000 | [diff] [blame] | 472 | // Just take the first successor if condition is undef |
| 473 | if (isa<UndefValue>(SimpleCond)) |
Michael Zolotukhin | 1ecdeda | 2016-05-26 21:42:51 +0000 | [diff] [blame^] | 474 | KnownSucc = BI->getSuccessor(0); |
| 475 | else if (ConstantInt *SimpleCondVal = |
| 476 | dyn_cast<ConstantInt>(SimpleCond)) |
| 477 | KnownSucc = BI->getSuccessor(SimpleCondVal->isZero() ? 1 : 0); |
Michael Zolotukhin | 57776b8 | 2015-07-24 01:53:04 +0000 | [diff] [blame] | 478 | } |
| 479 | } |
| 480 | } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) { |
| 481 | if (Constant *SimpleCond = |
| 482 | SimplifiedValues.lookup(SI->getCondition())) { |
Michael Zolotukhin | 3a7d55b | 2015-07-29 18:10:29 +0000 | [diff] [blame] | 483 | // Just take the first successor if condition is undef |
| 484 | if (isa<UndefValue>(SimpleCond)) |
Michael Zolotukhin | 1ecdeda | 2016-05-26 21:42:51 +0000 | [diff] [blame^] | 485 | KnownSucc = SI->getSuccessor(0); |
| 486 | else if (ConstantInt *SimpleCondVal = |
| 487 | dyn_cast<ConstantInt>(SimpleCond)) |
| 488 | KnownSucc = SI->findCaseValue(SimpleCondVal).getCaseSuccessor(); |
Michael Zolotukhin | 57776b8 | 2015-07-24 01:53:04 +0000 | [diff] [blame] | 489 | } |
| 490 | } |
Michael Zolotukhin | 1ecdeda | 2016-05-26 21:42:51 +0000 | [diff] [blame^] | 491 | if (KnownSucc) { |
| 492 | if (L->contains(KnownSucc)) |
| 493 | BBWorklist.insert(KnownSucc); |
| 494 | else |
| 495 | ExitWorklist.insert({BB, KnownSucc}); |
| 496 | continue; |
| 497 | } |
Michael Zolotukhin | 57776b8 | 2015-07-24 01:53:04 +0000 | [diff] [blame] | 498 | |
Chandler Carruth | 0215608 | 2015-05-22 17:41:35 +0000 | [diff] [blame] | 499 | // Add BB's successors to the worklist. |
| 500 | for (BasicBlock *Succ : successors(BB)) |
| 501 | if (L->contains(Succ)) |
| 502 | BBWorklist.insert(Succ); |
Michael Zolotukhin | 963a6d9 | 2016-05-13 21:23:25 +0000 | [diff] [blame] | 503 | else |
| 504 | ExitWorklist.insert({BB, Succ}); |
Michael Zolotukhin | d2268a7 | 2016-05-18 21:20:12 +0000 | [diff] [blame] | 505 | AddCostRecursively(*TI, Iteration); |
Michael Zolotukhin | a9aadd2 | 2015-02-05 02:34:00 +0000 | [diff] [blame] | 506 | } |
Chandler Carruth | 0215608 | 2015-05-22 17:41:35 +0000 | [diff] [blame] | 507 | |
| 508 | // If we found no optimization opportunities on the first iteration, we |
| 509 | // won't find them on later ones too. |
Michael Zolotukhin | 80d13ba | 2015-07-28 20:07:29 +0000 | [diff] [blame] | 510 | if (UnrolledCost == RolledDynamicCost) { |
| 511 | DEBUG(dbgs() << " No opportunities found.. exiting.\n" |
| 512 | << " UnrolledCost: " << UnrolledCost << "\n"); |
Chandler Carruth | 0215608 | 2015-05-22 17:41:35 +0000 | [diff] [blame] | 513 | return None; |
Michael Zolotukhin | 80d13ba | 2015-07-28 20:07:29 +0000 | [diff] [blame] | 514 | } |
Michael Zolotukhin | a9aadd2 | 2015-02-05 02:34:00 +0000 | [diff] [blame] | 515 | } |
Michael Zolotukhin | 963a6d9 | 2016-05-13 21:23:25 +0000 | [diff] [blame] | 516 | |
| 517 | while (!ExitWorklist.empty()) { |
| 518 | BasicBlock *ExitingBB, *ExitBB; |
| 519 | std::tie(ExitingBB, ExitBB) = ExitWorklist.pop_back_val(); |
| 520 | |
| 521 | for (Instruction &I : *ExitBB) { |
| 522 | auto *PN = dyn_cast<PHINode>(&I); |
| 523 | if (!PN) |
| 524 | break; |
| 525 | |
| 526 | Value *Op = PN->getIncomingValueForBlock(ExitingBB); |
| 527 | if (auto *OpI = dyn_cast<Instruction>(Op)) |
| 528 | if (L->contains(OpI)) |
| 529 | AddCostRecursively(*OpI, TripCount - 1); |
| 530 | } |
| 531 | } |
| 532 | |
Michael Zolotukhin | 80d13ba | 2015-07-28 20:07:29 +0000 | [diff] [blame] | 533 | DEBUG(dbgs() << "Analysis finished:\n" |
| 534 | << "UnrolledCost: " << UnrolledCost << ", " |
| 535 | << "RolledDynamicCost: " << RolledDynamicCost << "\n"); |
Chandler Carruth | 9dabd14 | 2015-06-05 17:01:43 +0000 | [diff] [blame] | 536 | return {{UnrolledCost, RolledDynamicCost}}; |
Chandler Carruth | 0215608 | 2015-05-22 17:41:35 +0000 | [diff] [blame] | 537 | } |
Michael Zolotukhin | a9aadd2 | 2015-02-05 02:34:00 +0000 | [diff] [blame] | 538 | |
Dan Gohman | 49d08a5 | 2007-05-08 15:14:19 +0000 | [diff] [blame] | 539 | /// ApproximateLoopSize - Approximate the size of the loop. |
Andrew Trick | f765601 | 2011-10-01 01:39:05 +0000 | [diff] [blame] | 540 | static unsigned ApproximateLoopSize(const Loop *L, unsigned &NumCalls, |
Justin Lebar | 6827de1 | 2016-03-14 23:15:34 +0000 | [diff] [blame] | 541 | bool &NotDuplicatable, bool &Convergent, |
Hal Finkel | 57f03dd | 2014-09-07 13:49:57 +0000 | [diff] [blame] | 542 | const TargetTransformInfo &TTI, |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 543 | AssumptionCache *AC) { |
Hal Finkel | 57f03dd | 2014-09-07 13:49:57 +0000 | [diff] [blame] | 544 | SmallPtrSet<const Value *, 32> EphValues; |
Chandler Carruth | 66b3130 | 2015-01-04 12:03:27 +0000 | [diff] [blame] | 545 | CodeMetrics::collectEphemeralValues(L, AC, EphValues); |
Hal Finkel | 57f03dd | 2014-09-07 13:49:57 +0000 | [diff] [blame] | 546 | |
Dan Gohman | 969e83a | 2009-10-31 14:54:17 +0000 | [diff] [blame] | 547 | CodeMetrics Metrics; |
Sanjay Patel | 5c96723 | 2016-03-08 19:06:12 +0000 | [diff] [blame] | 548 | for (BasicBlock *BB : L->blocks()) |
| 549 | Metrics.analyzeBasicBlock(BB, TTI, EphValues); |
Owen Anderson | 04cf3fd | 2010-09-09 20:32:23 +0000 | [diff] [blame] | 550 | NumCalls = Metrics.NumInlineCandidates; |
James Molloy | 4f6fb95 | 2012-12-20 16:04:27 +0000 | [diff] [blame] | 551 | NotDuplicatable = Metrics.notDuplicatable; |
Justin Lebar | 6827de1 | 2016-03-14 23:15:34 +0000 | [diff] [blame] | 552 | Convergent = Metrics.convergent; |
Andrew Trick | 279e7a6 | 2011-07-23 00:29:16 +0000 | [diff] [blame] | 553 | |
Owen Anderson | 62ea1b7 | 2010-09-09 19:07:31 +0000 | [diff] [blame] | 554 | unsigned LoopSize = Metrics.NumInsts; |
Andrew Trick | 279e7a6 | 2011-07-23 00:29:16 +0000 | [diff] [blame] | 555 | |
Owen Anderson | 62ea1b7 | 2010-09-09 19:07:31 +0000 | [diff] [blame] | 556 | // Don't allow an estimate of size zero. This would allows unrolling of loops |
| 557 | // with huge iteration counts, which is a compile time problem even if it's |
Hal Finkel | 38dd590 | 2015-01-10 00:30:55 +0000 | [diff] [blame] | 558 | // not a problem for code quality. Also, the code using this size may assume |
| 559 | // that each loop has at least three instructions (likely a conditional |
| 560 | // branch, a comparison feeding that branch, and some kind of loop increment |
| 561 | // feeding that comparison instruction). |
| 562 | LoopSize = std::max(LoopSize, 3u); |
Andrew Trick | 279e7a6 | 2011-07-23 00:29:16 +0000 | [diff] [blame] | 563 | |
Owen Anderson | 62ea1b7 | 2010-09-09 19:07:31 +0000 | [diff] [blame] | 564 | return LoopSize; |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 565 | } |
| 566 | |
Mark Heffernan | e6b4ba1 | 2014-07-23 17:31:37 +0000 | [diff] [blame] | 567 | // Returns the loop hint metadata node with the given name (for example, |
| 568 | // "llvm.loop.unroll.count"). If no such metadata node exists, then nullptr is |
| 569 | // returned. |
Jingyue Wu | 49a766e | 2015-02-02 20:41:11 +0000 | [diff] [blame] | 570 | static MDNode *GetUnrollMetadataForLoop(const Loop *L, StringRef Name) { |
| 571 | if (MDNode *LoopID = L->getLoopID()) |
| 572 | return GetUnrollMetadata(LoopID, Name); |
| 573 | return nullptr; |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 574 | } |
| 575 | |
Mark Heffernan | e6b4ba1 | 2014-07-23 17:31:37 +0000 | [diff] [blame] | 576 | // Returns true if the loop has an unroll(full) pragma. |
| 577 | static bool HasUnrollFullPragma(const Loop *L) { |
Jingyue Wu | 0220df0 | 2015-02-01 02:27:45 +0000 | [diff] [blame] | 578 | return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.full"); |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 579 | } |
| 580 | |
Mark Heffernan | 8939154 | 2015-08-10 17:28:08 +0000 | [diff] [blame] | 581 | // Returns true if the loop has an unroll(enable) pragma. This metadata is used |
| 582 | // for both "#pragma unroll" and "#pragma clang loop unroll(enable)" directives. |
| 583 | static bool HasUnrollEnablePragma(const Loop *L) { |
| 584 | return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.enable"); |
| 585 | } |
| 586 | |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 587 | // Returns true if the loop has an unroll(disable) pragma. |
| 588 | static bool HasUnrollDisablePragma(const Loop *L) { |
Jingyue Wu | 0220df0 | 2015-02-01 02:27:45 +0000 | [diff] [blame] | 589 | return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.disable"); |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 590 | } |
| 591 | |
Kevin Qin | 715b01e | 2015-03-09 06:14:18 +0000 | [diff] [blame] | 592 | // Returns true if the loop has an runtime unroll(disable) pragma. |
| 593 | static bool HasRuntimeUnrollDisablePragma(const Loop *L) { |
| 594 | return GetUnrollMetadataForLoop(L, "llvm.loop.unroll.runtime.disable"); |
| 595 | } |
| 596 | |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 597 | // If loop has an unroll_count pragma return the (necessarily |
| 598 | // positive) value from the pragma. Otherwise return 0. |
| 599 | static unsigned UnrollCountPragmaValue(const Loop *L) { |
Jingyue Wu | 49a766e | 2015-02-02 20:41:11 +0000 | [diff] [blame] | 600 | MDNode *MD = GetUnrollMetadataForLoop(L, "llvm.loop.unroll.count"); |
Mark Heffernan | e6b4ba1 | 2014-07-23 17:31:37 +0000 | [diff] [blame] | 601 | if (MD) { |
| 602 | assert(MD->getNumOperands() == 2 && |
| 603 | "Unroll count hint metadata should have two operands."); |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 604 | unsigned Count = |
| 605 | mdconst::extract<ConstantInt>(MD->getOperand(1))->getZExtValue(); |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 606 | assert(Count >= 1 && "Unroll count must be positive."); |
| 607 | return Count; |
| 608 | } |
| 609 | return 0; |
| 610 | } |
| 611 | |
Mark Heffernan | 053a686 | 2014-07-18 21:04:33 +0000 | [diff] [blame] | 612 | // Remove existing unroll metadata and add unroll disable metadata to |
| 613 | // indicate the loop has already been unrolled. This prevents a loop |
| 614 | // from being unrolled more than is directed by a pragma if the loop |
| 615 | // unrolling pass is run more than once (which it generally is). |
| 616 | static void SetLoopAlreadyUnrolled(Loop *L) { |
| 617 | MDNode *LoopID = L->getLoopID(); |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 618 | if (!LoopID) |
| 619 | return; |
Mark Heffernan | 053a686 | 2014-07-18 21:04:33 +0000 | [diff] [blame] | 620 | |
| 621 | // First remove any existing loop unrolling metadata. |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 622 | SmallVector<Metadata *, 4> MDs; |
Mark Heffernan | 053a686 | 2014-07-18 21:04:33 +0000 | [diff] [blame] | 623 | // Reserve first location for self reference to the LoopID metadata node. |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 624 | MDs.push_back(nullptr); |
Mark Heffernan | 053a686 | 2014-07-18 21:04:33 +0000 | [diff] [blame] | 625 | for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { |
| 626 | bool IsUnrollMetadata = false; |
| 627 | MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i)); |
| 628 | if (MD) { |
| 629 | const MDString *S = dyn_cast<MDString>(MD->getOperand(0)); |
| 630 | IsUnrollMetadata = S && S->getString().startswith("llvm.loop.unroll."); |
| 631 | } |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 632 | if (!IsUnrollMetadata) |
| 633 | MDs.push_back(LoopID->getOperand(i)); |
Mark Heffernan | 053a686 | 2014-07-18 21:04:33 +0000 | [diff] [blame] | 634 | } |
| 635 | |
| 636 | // Add unroll(disable) metadata to disable future unrolling. |
| 637 | LLVMContext &Context = L->getHeader()->getContext(); |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 638 | SmallVector<Metadata *, 1> DisableOperands; |
Mark Heffernan | e6b4ba1 | 2014-07-23 17:31:37 +0000 | [diff] [blame] | 639 | DisableOperands.push_back(MDString::get(Context, "llvm.loop.unroll.disable")); |
Mark Heffernan | f3764da | 2014-07-18 21:29:41 +0000 | [diff] [blame] | 640 | MDNode *DisableNode = MDNode::get(Context, DisableOperands); |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 641 | MDs.push_back(DisableNode); |
Mark Heffernan | 053a686 | 2014-07-18 21:04:33 +0000 | [diff] [blame] | 642 | |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 643 | MDNode *NewLoopID = MDNode::get(Context, MDs); |
Mark Heffernan | 053a686 | 2014-07-18 21:04:33 +0000 | [diff] [blame] | 644 | // Set operand 0 to refer to the loop id itself. |
| 645 | NewLoopID->replaceOperandWith(0, NewLoopID); |
| 646 | L->setLoopID(NewLoopID); |
Mark Heffernan | 053a686 | 2014-07-18 21:04:33 +0000 | [diff] [blame] | 647 | } |
| 648 | |
Justin Bogner | 921b04e | 2016-01-12 01:06:32 +0000 | [diff] [blame] | 649 | static bool canUnrollCompletely(Loop *L, unsigned Threshold, |
| 650 | unsigned PercentDynamicCostSavedThreshold, |
| 651 | unsigned DynamicCostSavingsDiscount, |
| 652 | uint64_t UnrolledCost, |
| 653 | uint64_t RolledDynamicCost) { |
Michael Zolotukhin | 8c68171 | 2015-05-12 17:20:03 +0000 | [diff] [blame] | 654 | if (Threshold == NoThreshold) { |
| 655 | DEBUG(dbgs() << " Can fully unroll, because no threshold is set.\n"); |
| 656 | return true; |
| 657 | } |
| 658 | |
Chandler Carruth | 9dabd14 | 2015-06-05 17:01:43 +0000 | [diff] [blame] | 659 | if (UnrolledCost <= Threshold) { |
| 660 | DEBUG(dbgs() << " Can fully unroll, because unrolled cost: " |
| 661 | << UnrolledCost << "<" << Threshold << "\n"); |
Michael Zolotukhin | 8c68171 | 2015-05-12 17:20:03 +0000 | [diff] [blame] | 662 | return true; |
| 663 | } |
| 664 | |
Chandler Carruth | 9dabd14 | 2015-06-05 17:01:43 +0000 | [diff] [blame] | 665 | assert(UnrolledCost && "UnrolledCost can't be 0 at this point."); |
| 666 | assert(RolledDynamicCost >= UnrolledCost && |
| 667 | "Cannot have a higher unrolled cost than a rolled cost!"); |
Michael Zolotukhin | 8c68171 | 2015-05-12 17:20:03 +0000 | [diff] [blame] | 668 | |
Chandler Carruth | 9dabd14 | 2015-06-05 17:01:43 +0000 | [diff] [blame] | 669 | // Compute the percentage of the dynamic cost in the rolled form that is |
| 670 | // saved when unrolled. If unrolling dramatically reduces the estimated |
| 671 | // dynamic cost of the loop, we use a higher threshold to allow more |
| 672 | // unrolling. |
| 673 | unsigned PercentDynamicCostSaved = |
| 674 | (uint64_t)(RolledDynamicCost - UnrolledCost) * 100ull / RolledDynamicCost; |
| 675 | |
| 676 | if (PercentDynamicCostSaved >= PercentDynamicCostSavedThreshold && |
| 677 | (int64_t)UnrolledCost - (int64_t)DynamicCostSavingsDiscount <= |
| 678 | (int64_t)Threshold) { |
| 679 | DEBUG(dbgs() << " Can fully unroll, because unrolling will reduce the " |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 680 | "expected dynamic cost by " |
| 681 | << PercentDynamicCostSaved << "% (threshold: " |
| 682 | << PercentDynamicCostSavedThreshold << "%)\n" |
Chandler Carruth | 9dabd14 | 2015-06-05 17:01:43 +0000 | [diff] [blame] | 683 | << " and the unrolled cost (" << UnrolledCost |
| 684 | << ") is less than the max threshold (" |
| 685 | << DynamicCostSavingsDiscount << ").\n"); |
Michael Zolotukhin | 8c68171 | 2015-05-12 17:20:03 +0000 | [diff] [blame] | 686 | return true; |
| 687 | } |
| 688 | |
| 689 | DEBUG(dbgs() << " Too large to fully unroll:\n"); |
Chandler Carruth | 9dabd14 | 2015-06-05 17:01:43 +0000 | [diff] [blame] | 690 | DEBUG(dbgs() << " Threshold: " << Threshold << "\n"); |
| 691 | DEBUG(dbgs() << " Max threshold: " << DynamicCostSavingsDiscount << "\n"); |
| 692 | DEBUG(dbgs() << " Percent cost saved threshold: " |
| 693 | << PercentDynamicCostSavedThreshold << "%\n"); |
| 694 | DEBUG(dbgs() << " Unrolled cost: " << UnrolledCost << "\n"); |
| 695 | DEBUG(dbgs() << " Rolled dynamic cost: " << RolledDynamicCost << "\n"); |
| 696 | DEBUG(dbgs() << " Percent cost saved: " << PercentDynamicCostSaved |
| 697 | << "\n"); |
Michael Zolotukhin | 8c68171 | 2015-05-12 17:20:03 +0000 | [diff] [blame] | 698 | return false; |
| 699 | } |
| 700 | |
Justin Bogner | b8d82ab | 2016-01-12 05:21:37 +0000 | [diff] [blame] | 701 | static bool tryToUnrollLoop(Loop *L, DominatorTree &DT, LoopInfo *LI, |
| 702 | ScalarEvolution *SE, const TargetTransformInfo &TTI, |
| 703 | AssumptionCache &AC, bool PreserveLCSSA, |
| 704 | Optional<unsigned> ProvidedCount, |
| 705 | Optional<unsigned> ProvidedThreshold, |
| 706 | Optional<bool> ProvidedAllowPartial, |
| 707 | Optional<bool> ProvidedRuntime) { |
Dan Gohman | 2e1f804 | 2007-05-08 15:19:19 +0000 | [diff] [blame] | 708 | BasicBlock *Header = L->getHeader(); |
David Greene | e0b9789 | 2010-01-05 01:27:44 +0000 | [diff] [blame] | 709 | DEBUG(dbgs() << "Loop Unroll: F[" << Header->getParent()->getName() |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 710 | << "] Loop %" << Header->getName() << "\n"); |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 711 | |
| 712 | if (HasUnrollDisablePragma(L)) { |
| 713 | return false; |
| 714 | } |
Mark Heffernan | e6b4ba1 | 2014-07-23 17:31:37 +0000 | [diff] [blame] | 715 | bool PragmaFullUnroll = HasUnrollFullPragma(L); |
Mark Heffernan | 8939154 | 2015-08-10 17:28:08 +0000 | [diff] [blame] | 716 | bool PragmaEnableUnroll = HasUnrollEnablePragma(L); |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 717 | unsigned PragmaCount = UnrollCountPragmaValue(L); |
Mark Heffernan | 8939154 | 2015-08-10 17:28:08 +0000 | [diff] [blame] | 718 | bool HasPragma = PragmaFullUnroll || PragmaEnableUnroll || PragmaCount > 0; |
Andrew Trick | 279e7a6 | 2011-07-23 00:29:16 +0000 | [diff] [blame] | 719 | |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 720 | // Find trip count and trip multiple if count is not available |
| 721 | unsigned TripCount = 0; |
Andrew Trick | 1cabe54 | 2011-07-23 00:33:05 +0000 | [diff] [blame] | 722 | unsigned TripMultiple = 1; |
Chandler Carruth | 6666c27 | 2014-10-11 00:12:11 +0000 | [diff] [blame] | 723 | // If there are multiple exiting blocks but one of them is the latch, use the |
| 724 | // latch for the trip count estimation. Otherwise insist on a single exiting |
| 725 | // block for the trip count estimation. |
| 726 | BasicBlock *ExitingBlock = L->getLoopLatch(); |
| 727 | if (!ExitingBlock || !L->isLoopExiting(ExitingBlock)) |
| 728 | ExitingBlock = L->getExitingBlock(); |
| 729 | if (ExitingBlock) { |
| 730 | TripCount = SE->getSmallConstantTripCount(L, ExitingBlock); |
| 731 | TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock); |
Andrew Trick | 2b6860f | 2011-08-11 23:36:16 +0000 | [diff] [blame] | 732 | } |
Hal Finkel | 8f2e700 | 2013-09-11 19:25:43 +0000 | [diff] [blame] | 733 | |
Justin Bogner | a1dd493 | 2016-01-12 00:55:26 +0000 | [diff] [blame] | 734 | TargetTransformInfo::UnrollingPreferences UP = gatherUnrollingPreferences( |
| 735 | L, TTI, ProvidedThreshold, ProvidedCount, ProvidedAllowPartial, |
| 736 | ProvidedRuntime, PragmaCount, PragmaFullUnroll, PragmaEnableUnroll, |
| 737 | TripCount); |
| 738 | |
| 739 | unsigned Count = UP.Count; |
| 740 | bool CountSetExplicitly = Count != 0; |
| 741 | // Use a heuristic count if we didn't set anything explicitly. |
| 742 | if (!CountSetExplicitly) |
| 743 | Count = TripCount == 0 ? DefaultUnrollRuntimeCount : TripCount; |
| 744 | if (TripCount && Count > TripCount) |
| 745 | Count = TripCount; |
Fiona Glaser | 045afc4 | 2016-04-06 16:57:25 +0000 | [diff] [blame] | 746 | Count = std::min(Count, UP.FullUnrollMaxCount); |
Eli Bendersky | dc6de2c | 2014-06-12 18:05:39 +0000 | [diff] [blame] | 747 | |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 748 | unsigned NumInlineCandidates; |
Sanjay Patel | f831fdb | 2016-03-08 19:07:42 +0000 | [diff] [blame] | 749 | bool NotDuplicatable; |
Justin Lebar | 6827de1 | 2016-03-14 23:15:34 +0000 | [diff] [blame] | 750 | bool Convergent; |
| 751 | unsigned LoopSize = ApproximateLoopSize( |
| 752 | L, NumInlineCandidates, NotDuplicatable, Convergent, TTI, &AC); |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 753 | DEBUG(dbgs() << " Loop Size = " << LoopSize << "\n"); |
Hal Finkel | 38dd590 | 2015-01-10 00:30:55 +0000 | [diff] [blame] | 754 | |
| 755 | // When computing the unrolled size, note that the conditional branch on the |
| 756 | // backedge and the comparison feeding it are not replicated like the rest of |
| 757 | // the loop body (which is why 2 is subtracted). |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 758 | uint64_t UnrolledSize = (uint64_t)(LoopSize - 2) * Count + 2; |
Sanjay Patel | f831fdb | 2016-03-08 19:07:42 +0000 | [diff] [blame] | 759 | if (NotDuplicatable) { |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 760 | DEBUG(dbgs() << " Not unrolling loop which contains non-duplicatable" |
| 761 | << " instructions.\n"); |
| 762 | return false; |
| 763 | } |
| 764 | if (NumInlineCandidates != 0) { |
| 765 | DEBUG(dbgs() << " Not unrolling loop with inlinable calls.\n"); |
| 766 | return false; |
Dan Gohman | 2980d9d | 2007-05-11 20:53:41 +0000 | [diff] [blame] | 767 | } |
| 768 | |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 769 | // Given Count, TripCount and thresholds determine the type of |
| 770 | // unrolling which is to be performed. |
| 771 | enum { Full = 0, Partial = 1, Runtime = 2 }; |
| 772 | int Unrolling; |
| 773 | if (TripCount && Count == TripCount) { |
Michael Zolotukhin | 8c68171 | 2015-05-12 17:20:03 +0000 | [diff] [blame] | 774 | Unrolling = Partial; |
| 775 | // If the loop is really small, we don't need to run an expensive analysis. |
Justin Bogner | a1dd493 | 2016-01-12 00:55:26 +0000 | [diff] [blame] | 776 | if (canUnrollCompletely(L, UP.Threshold, 100, UP.DynamicCostSavingsDiscount, |
Chandler Carruth | 9dabd14 | 2015-06-05 17:01:43 +0000 | [diff] [blame] | 777 | UnrolledSize, UnrolledSize)) { |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 778 | Unrolling = Full; |
Michael Zolotukhin | 8c68171 | 2015-05-12 17:20:03 +0000 | [diff] [blame] | 779 | } else { |
| 780 | // The loop isn't that small, but we still can fully unroll it if that |
| 781 | // helps to remove a significant number of instructions. |
| 782 | // To check that, run additional analysis on the loop. |
Justin Bogner | a1dd493 | 2016-01-12 00:55:26 +0000 | [diff] [blame] | 783 | if (Optional<EstimatedUnrollCost> Cost = analyzeLoopUnrollCost( |
| 784 | L, TripCount, DT, *SE, TTI, |
| 785 | UP.Threshold + UP.DynamicCostSavingsDiscount)) |
| 786 | if (canUnrollCompletely(L, UP.Threshold, |
| 787 | UP.PercentDynamicCostSavedThreshold, |
| 788 | UP.DynamicCostSavingsDiscount, |
| 789 | Cost->UnrolledCost, Cost->RolledDynamicCost)) { |
Chandler Carruth | 0215608 | 2015-05-22 17:41:35 +0000 | [diff] [blame] | 790 | Unrolling = Full; |
| 791 | } |
Dan Gohman | 2980d9d | 2007-05-11 20:53:41 +0000 | [diff] [blame] | 792 | } |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 793 | } else if (TripCount && Count < TripCount) { |
| 794 | Unrolling = Partial; |
| 795 | } else { |
| 796 | Unrolling = Runtime; |
| 797 | } |
| 798 | |
| 799 | // Reduce count based on the type of unrolling and the threshold values. |
| 800 | unsigned OriginalCount = Count; |
Justin Bogner | a1dd493 | 2016-01-12 00:55:26 +0000 | [diff] [blame] | 801 | bool AllowRuntime = PragmaEnableUnroll || (PragmaCount > 0) || UP.Runtime; |
Mark Heffernan | d7ebc24 | 2015-07-13 18:26:27 +0000 | [diff] [blame] | 802 | // Don't unroll a runtime trip count loop with unroll full pragma. |
| 803 | if (HasRuntimeUnrollDisablePragma(L) || PragmaFullUnroll) { |
Kevin Qin | 715b01e | 2015-03-09 06:14:18 +0000 | [diff] [blame] | 804 | AllowRuntime = false; |
| 805 | } |
Justin Lebar | 6827de1 | 2016-03-14 23:15:34 +0000 | [diff] [blame] | 806 | bool DecreasedCountDueToConvergence = false; |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 807 | if (Unrolling == Partial) { |
Justin Bogner | a1dd493 | 2016-01-12 00:55:26 +0000 | [diff] [blame] | 808 | bool AllowPartial = PragmaEnableUnroll || UP.Partial; |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 809 | if (!AllowPartial && !CountSetExplicitly) { |
| 810 | DEBUG(dbgs() << " will not try to unroll partially because " |
| 811 | << "-unroll-allow-partial not given\n"); |
| 812 | return false; |
| 813 | } |
Fiona Glaser | 045afc4 | 2016-04-06 16:57:25 +0000 | [diff] [blame] | 814 | if (UP.PartialThreshold != NoThreshold && Count > 1) { |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 815 | // Reduce unroll count to be modulo of TripCount for partial unrolling. |
Fiona Glaser | 045afc4 | 2016-04-06 16:57:25 +0000 | [diff] [blame] | 816 | if (UnrolledSize > UP.PartialThreshold) |
| 817 | Count = (std::max(UP.PartialThreshold, 3u) - 2) / (LoopSize - 2); |
| 818 | if (Count > UP.MaxCount) |
| 819 | Count = UP.MaxCount; |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 820 | while (Count != 0 && TripCount % Count != 0) |
| 821 | Count--; |
Fiona Glaser | 16332ba | 2016-04-06 16:43:45 +0000 | [diff] [blame] | 822 | if (AllowRuntime && Count <= 1) { |
Zia Ansari | a82a58a4 | 2016-04-04 19:24:46 +0000 | [diff] [blame] | 823 | // If there is no Count that is modulo of TripCount, set Count to |
| 824 | // largest power-of-two factor that satisfies the threshold limit. |
Fiona Glaser | 16332ba | 2016-04-06 16:43:45 +0000 | [diff] [blame] | 825 | // As we'll create fixup loop, do the type of unrolling only if |
| 826 | // runtime unrolling is allowed. |
| 827 | Count = DefaultUnrollRuntimeCount; |
Zia Ansari | a82a58a4 | 2016-04-04 19:24:46 +0000 | [diff] [blame] | 828 | UnrolledSize = (LoopSize - 2) * Count + 2; |
| 829 | while (Count != 0 && UnrolledSize > UP.PartialThreshold) { |
| 830 | Count >>= 1; |
| 831 | UnrolledSize = (LoopSize - 2) * Count + 2; |
| 832 | } |
| 833 | } |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 834 | } |
| 835 | } else if (Unrolling == Runtime) { |
| 836 | if (!AllowRuntime && !CountSetExplicitly) { |
| 837 | DEBUG(dbgs() << " will not try to unroll loop with runtime trip count " |
| 838 | << "-unroll-runtime not given\n"); |
| 839 | return false; |
| 840 | } |
Justin Lebar | 6827de1 | 2016-03-14 23:15:34 +0000 | [diff] [blame] | 841 | |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 842 | // Reduce unroll count to be the largest power-of-two factor of |
| 843 | // the original count which satisfies the threshold limit. |
Justin Bogner | a1dd493 | 2016-01-12 00:55:26 +0000 | [diff] [blame] | 844 | while (Count != 0 && UnrolledSize > UP.PartialThreshold) { |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 845 | Count >>= 1; |
Dehao Chen | d55bc4c | 2016-05-05 00:54:54 +0000 | [diff] [blame] | 846 | UnrolledSize = (LoopSize - 2) * Count + 2; |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 847 | } |
Justin Lebar | 6827de1 | 2016-03-14 23:15:34 +0000 | [diff] [blame] | 848 | |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 849 | if (Count > UP.MaxCount) |
| 850 | Count = UP.MaxCount; |
Justin Lebar | 6827de1 | 2016-03-14 23:15:34 +0000 | [diff] [blame] | 851 | |
| 852 | // If the loop contains a convergent operation, the prelude we'd add |
| 853 | // to do the first few instructions before we hit the unrolled loop |
| 854 | // is unsafe -- it adds a control-flow dependency to the convergent |
| 855 | // operation. Therefore Count must divide TripMultiple. |
| 856 | // |
| 857 | // TODO: This is quite conservative. In practice, convergent_op() |
| 858 | // is likely to be called unconditionally in the loop. In this |
| 859 | // case, the program would be ill-formed (on most architectures) |
| 860 | // unless n were the same on all threads in a thread group. |
| 861 | // Assuming n is the same on all threads, any kind of unrolling is |
| 862 | // safe. But currently llvm's notion of convergence isn't powerful |
| 863 | // enough to express this. |
| 864 | unsigned OrigCount = Count; |
| 865 | while (Convergent && Count != 0 && TripMultiple % Count != 0) { |
| 866 | DecreasedCountDueToConvergence = true; |
| 867 | Count >>= 1; |
| 868 | } |
| 869 | if (OrigCount > Count) { |
| 870 | DEBUG(dbgs() << " loop contains a convergent instruction, so unroll " |
| 871 | "count must divide the trip multiple, " |
| 872 | << TripMultiple << ". Reducing unroll count from " |
| 873 | << OrigCount << " to " << Count << ".\n"); |
| 874 | } |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 875 | DEBUG(dbgs() << " partially unrolling with count: " << Count << "\n"); |
| 876 | } |
| 877 | |
| 878 | if (HasPragma) { |
| 879 | // Emit optimization remarks if we are unable to unroll the loop |
| 880 | // as directed by a pragma. |
| 881 | DebugLoc LoopLoc = L->getStartLoc(); |
| 882 | Function *F = Header->getParent(); |
| 883 | LLVMContext &Ctx = F->getContext(); |
Justin Lebar | 6827de1 | 2016-03-14 23:15:34 +0000 | [diff] [blame] | 884 | if (PragmaCount > 0 && DecreasedCountDueToConvergence) { |
| 885 | emitOptimizationRemarkMissed( |
| 886 | Ctx, DEBUG_TYPE, *F, LoopLoc, |
| 887 | Twine("Unable to unroll loop the number of times directed by " |
| 888 | "unroll_count pragma because the loop contains a convergent " |
| 889 | "instruction, and so must have an unroll count that divides " |
| 890 | "the loop trip multiple of ") + |
| 891 | Twine(TripMultiple) + ". Unrolling instead " + Twine(Count) + |
| 892 | " time(s)."); |
| 893 | } else if ((PragmaCount > 0) && Count != OriginalCount) { |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 894 | emitOptimizationRemarkMissed( |
| 895 | Ctx, DEBUG_TYPE, *F, LoopLoc, |
| 896 | "Unable to unroll loop the number of times directed by " |
| 897 | "unroll_count pragma because unrolled size is too large."); |
Mark Heffernan | 8939154 | 2015-08-10 17:28:08 +0000 | [diff] [blame] | 898 | } else if (PragmaFullUnroll && !TripCount) { |
| 899 | emitOptimizationRemarkMissed( |
| 900 | Ctx, DEBUG_TYPE, *F, LoopLoc, |
| 901 | "Unable to fully unroll loop as directed by unroll(full) pragma " |
| 902 | "because loop has a runtime trip count."); |
| 903 | } else if (PragmaEnableUnroll && Count != TripCount && Count < 2) { |
| 904 | emitOptimizationRemarkMissed( |
| 905 | Ctx, DEBUG_TYPE, *F, LoopLoc, |
| 906 | "Unable to unroll loop as directed by unroll(enable) pragma because " |
| 907 | "unrolled size is too large."); |
| 908 | } else if ((PragmaFullUnroll || PragmaEnableUnroll) && TripCount && |
| 909 | Count != TripCount) { |
| 910 | emitOptimizationRemarkMissed( |
| 911 | Ctx, DEBUG_TYPE, *F, LoopLoc, |
| 912 | "Unable to fully unroll loop as directed by unroll pragma because " |
| 913 | "unrolled size is too large."); |
Eli Bendersky | ff90324 | 2014-06-16 23:53:02 +0000 | [diff] [blame] | 914 | } |
| 915 | } |
| 916 | |
| 917 | if (Unrolling != Full && Count < 2) { |
| 918 | // Partial unrolling by 1 is a nop. For full unrolling, a factor |
| 919 | // of 1 makes sense because loop control can be eliminated. |
| 920 | return false; |
Dan Gohman | 2980d9d | 2007-05-11 20:53:41 +0000 | [diff] [blame] | 921 | } |
| 922 | |
Dan Gohman | 3dc2d92 | 2008-05-14 00:24:14 +0000 | [diff] [blame] | 923 | // Unroll the loop. |
Sanjoy Das | e178f46 | 2015-04-14 03:20:38 +0000 | [diff] [blame] | 924 | if (!UnrollLoop(L, Count, TripCount, AllowRuntime, UP.AllowExpensiveTripCount, |
Justin Bogner | 883a3ea | 2015-12-16 18:40:20 +0000 | [diff] [blame] | 925 | TripMultiple, LI, SE, &DT, &AC, PreserveLCSSA)) |
Dan Gohman | 3dc2d92 | 2008-05-14 00:24:14 +0000 | [diff] [blame] | 926 | return false; |
Dan Gohman | 2980d9d | 2007-05-11 20:53:41 +0000 | [diff] [blame] | 927 | |
David L Kreitzer | 8d441eb | 2016-03-25 14:24:52 +0000 | [diff] [blame] | 928 | // If loop has an unroll count pragma mark loop as unrolled to prevent |
| 929 | // unrolling beyond that requested by the pragma. |
| 930 | if (HasPragma && PragmaCount != 0) |
| 931 | SetLoopAlreadyUnrolled(L); |
Chris Lattner | 946b255 | 2004-04-18 05:20:17 +0000 | [diff] [blame] | 932 | return true; |
| 933 | } |
Justin Bogner | b8d82ab | 2016-01-12 05:21:37 +0000 | [diff] [blame] | 934 | |
| 935 | namespace { |
| 936 | class LoopUnroll : public LoopPass { |
| 937 | public: |
| 938 | static char ID; // Pass ID, replacement for typeid |
| 939 | LoopUnroll(Optional<unsigned> Threshold = None, |
| 940 | Optional<unsigned> Count = None, |
| 941 | Optional<bool> AllowPartial = None, Optional<bool> Runtime = None) |
| 942 | : LoopPass(ID), ProvidedCount(Count), ProvidedThreshold(Threshold), |
| 943 | ProvidedAllowPartial(AllowPartial), ProvidedRuntime(Runtime) { |
| 944 | initializeLoopUnrollPass(*PassRegistry::getPassRegistry()); |
| 945 | } |
| 946 | |
| 947 | Optional<unsigned> ProvidedCount; |
| 948 | Optional<unsigned> ProvidedThreshold; |
| 949 | Optional<bool> ProvidedAllowPartial; |
| 950 | Optional<bool> ProvidedRuntime; |
| 951 | |
| 952 | bool runOnLoop(Loop *L, LPPassManager &) override { |
Andrew Kaylor | aa641a5 | 2016-04-22 22:06:11 +0000 | [diff] [blame] | 953 | if (skipLoop(L)) |
Justin Bogner | b8d82ab | 2016-01-12 05:21:37 +0000 | [diff] [blame] | 954 | return false; |
| 955 | |
| 956 | Function &F = *L->getHeader()->getParent(); |
| 957 | |
| 958 | auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
| 959 | LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
| 960 | ScalarEvolution *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); |
| 961 | const TargetTransformInfo &TTI = |
| 962 | getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); |
| 963 | auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); |
| 964 | bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID); |
| 965 | |
| 966 | return tryToUnrollLoop(L, DT, LI, SE, TTI, AC, PreserveLCSSA, ProvidedCount, |
| 967 | ProvidedThreshold, ProvidedAllowPartial, |
| 968 | ProvidedRuntime); |
| 969 | } |
| 970 | |
| 971 | /// This transformation requires natural loop information & requires that |
| 972 | /// loop preheaders be inserted into the CFG... |
| 973 | /// |
| 974 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 975 | AU.addRequired<AssumptionCacheTracker>(); |
Justin Bogner | b8d82ab | 2016-01-12 05:21:37 +0000 | [diff] [blame] | 976 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 977 | // FIXME: Loop passes are required to preserve domtree, and for now we just |
| 978 | // recreate dom info if anything gets unrolled. |
| 979 | getLoopAnalysisUsage(AU); |
Justin Bogner | b8d82ab | 2016-01-12 05:21:37 +0000 | [diff] [blame] | 980 | } |
| 981 | }; |
| 982 | } |
| 983 | |
| 984 | char LoopUnroll::ID = 0; |
| 985 | INITIALIZE_PASS_BEGIN(LoopUnroll, "loop-unroll", "Unroll loops", false, false) |
Justin Bogner | b8d82ab | 2016-01-12 05:21:37 +0000 | [diff] [blame] | 986 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 987 | INITIALIZE_PASS_DEPENDENCY(LoopPass) |
| 988 | INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) |
Justin Bogner | b8d82ab | 2016-01-12 05:21:37 +0000 | [diff] [blame] | 989 | INITIALIZE_PASS_END(LoopUnroll, "loop-unroll", "Unroll loops", false, false) |
| 990 | |
| 991 | Pass *llvm::createLoopUnrollPass(int Threshold, int Count, int AllowPartial, |
| 992 | int Runtime) { |
| 993 | // TODO: It would make more sense for this function to take the optionals |
| 994 | // directly, but that's dangerous since it would silently break out of tree |
| 995 | // callers. |
| 996 | return new LoopUnroll(Threshold == -1 ? None : Optional<unsigned>(Threshold), |
| 997 | Count == -1 ? None : Optional<unsigned>(Count), |
| 998 | AllowPartial == -1 ? None |
| 999 | : Optional<bool>(AllowPartial), |
| 1000 | Runtime == -1 ? None : Optional<bool>(Runtime)); |
| 1001 | } |
| 1002 | |
| 1003 | Pass *llvm::createSimpleLoopUnrollPass() { |
| 1004 | return llvm::createLoopUnrollPass(-1, -1, 0, 0); |
| 1005 | } |