File: | build/source/llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp |
Warning: | line 5598, column 22 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | // | |||
9 | // This transformation analyzes and transforms the induction variables (and | |||
10 | // computations derived from them) into forms suitable for efficient execution | |||
11 | // on the target. | |||
12 | // | |||
13 | // This pass performs a strength reduction on array references inside loops that | |||
14 | // have as one or more of their components the loop induction variable, it | |||
15 | // rewrites expressions to take advantage of scaled-index addressing modes | |||
16 | // available on the target, and it performs a variety of other optimizations | |||
17 | // related to loop induction variables. | |||
18 | // | |||
19 | // Terminology note: this code has a lot of handling for "post-increment" or | |||
20 | // "post-inc" users. This is not talking about post-increment addressing modes; | |||
21 | // it is instead talking about code like this: | |||
22 | // | |||
23 | // %i = phi [ 0, %entry ], [ %i.next, %latch ] | |||
24 | // ... | |||
25 | // %i.next = add %i, 1 | |||
26 | // %c = icmp eq %i.next, %n | |||
27 | // | |||
28 | // The SCEV for %i is {0,+,1}<%L>. The SCEV for %i.next is {1,+,1}<%L>, however | |||
29 | // it's useful to think about these as the same register, with some uses using | |||
30 | // the value of the register before the add and some using it after. In this | |||
31 | // example, the icmp is a post-increment user, since it uses %i.next, which is | |||
32 | // the value of the induction variable after the increment. The other common | |||
33 | // case of post-increment users is users outside the loop. | |||
34 | // | |||
35 | // TODO: More sophistication in the way Formulae are generated and filtered. | |||
36 | // | |||
37 | // TODO: Handle multiple loops at a time. | |||
38 | // | |||
39 | // TODO: Should the addressing mode BaseGV be changed to a ConstantExpr instead | |||
40 | // of a GlobalValue? | |||
41 | // | |||
42 | // TODO: When truncation is free, truncate ICmp users' operands to make it a | |||
43 | // smaller encoding (on x86 at least). | |||
44 | // | |||
45 | // TODO: When a negated register is used by an add (such as in a list of | |||
46 | // multiple base registers, or as the increment expression in an addrec), | |||
47 | // we may not actually need both reg and (-1 * reg) in registers; the | |||
48 | // negation can be implemented by using a sub instead of an add. The | |||
49 | // lack of support for taking this into consideration when making | |||
50 | // register pressure decisions is partly worked around by the "Special" | |||
51 | // use kind. | |||
52 | // | |||
53 | //===----------------------------------------------------------------------===// | |||
54 | ||||
55 | #include "llvm/Transforms/Scalar/LoopStrengthReduce.h" | |||
56 | #include "llvm/ADT/APInt.h" | |||
57 | #include "llvm/ADT/DenseMap.h" | |||
58 | #include "llvm/ADT/DenseSet.h" | |||
59 | #include "llvm/ADT/Hashing.h" | |||
60 | #include "llvm/ADT/PointerIntPair.h" | |||
61 | #include "llvm/ADT/STLExtras.h" | |||
62 | #include "llvm/ADT/SetVector.h" | |||
63 | #include "llvm/ADT/SmallBitVector.h" | |||
64 | #include "llvm/ADT/SmallPtrSet.h" | |||
65 | #include "llvm/ADT/SmallSet.h" | |||
66 | #include "llvm/ADT/SmallVector.h" | |||
67 | #include "llvm/ADT/Statistic.h" | |||
68 | #include "llvm/ADT/iterator_range.h" | |||
69 | #include "llvm/Analysis/AssumptionCache.h" | |||
70 | #include "llvm/Analysis/IVUsers.h" | |||
71 | #include "llvm/Analysis/LoopAnalysisManager.h" | |||
72 | #include "llvm/Analysis/LoopInfo.h" | |||
73 | #include "llvm/Analysis/LoopPass.h" | |||
74 | #include "llvm/Analysis/MemorySSA.h" | |||
75 | #include "llvm/Analysis/MemorySSAUpdater.h" | |||
76 | #include "llvm/Analysis/ScalarEvolution.h" | |||
77 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" | |||
78 | #include "llvm/Analysis/ScalarEvolutionNormalization.h" | |||
79 | #include "llvm/Analysis/TargetLibraryInfo.h" | |||
80 | #include "llvm/Analysis/TargetTransformInfo.h" | |||
81 | #include "llvm/Analysis/ValueTracking.h" | |||
82 | #include "llvm/BinaryFormat/Dwarf.h" | |||
83 | #include "llvm/Config/llvm-config.h" | |||
84 | #include "llvm/IR/BasicBlock.h" | |||
85 | #include "llvm/IR/Constant.h" | |||
86 | #include "llvm/IR/Constants.h" | |||
87 | #include "llvm/IR/DebugInfoMetadata.h" | |||
88 | #include "llvm/IR/DerivedTypes.h" | |||
89 | #include "llvm/IR/Dominators.h" | |||
90 | #include "llvm/IR/GlobalValue.h" | |||
91 | #include "llvm/IR/IRBuilder.h" | |||
92 | #include "llvm/IR/InstrTypes.h" | |||
93 | #include "llvm/IR/Instruction.h" | |||
94 | #include "llvm/IR/Instructions.h" | |||
95 | #include "llvm/IR/IntrinsicInst.h" | |||
96 | #include "llvm/IR/Module.h" | |||
97 | #include "llvm/IR/Operator.h" | |||
98 | #include "llvm/IR/PassManager.h" | |||
99 | #include "llvm/IR/Type.h" | |||
100 | #include "llvm/IR/Use.h" | |||
101 | #include "llvm/IR/User.h" | |||
102 | #include "llvm/IR/Value.h" | |||
103 | #include "llvm/IR/ValueHandle.h" | |||
104 | #include "llvm/InitializePasses.h" | |||
105 | #include "llvm/Pass.h" | |||
106 | #include "llvm/Support/Casting.h" | |||
107 | #include "llvm/Support/CommandLine.h" | |||
108 | #include "llvm/Support/Compiler.h" | |||
109 | #include "llvm/Support/Debug.h" | |||
110 | #include "llvm/Support/ErrorHandling.h" | |||
111 | #include "llvm/Support/MathExtras.h" | |||
112 | #include "llvm/Support/raw_ostream.h" | |||
113 | #include "llvm/Transforms/Scalar.h" | |||
114 | #include "llvm/Transforms/Utils.h" | |||
115 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" | |||
116 | #include "llvm/Transforms/Utils/Local.h" | |||
117 | #include "llvm/Transforms/Utils/LoopUtils.h" | |||
118 | #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" | |||
119 | #include <algorithm> | |||
120 | #include <cassert> | |||
121 | #include <cstddef> | |||
122 | #include <cstdint> | |||
123 | #include <iterator> | |||
124 | #include <limits> | |||
125 | #include <map> | |||
126 | #include <numeric> | |||
127 | #include <optional> | |||
128 | #include <utility> | |||
129 | ||||
130 | using namespace llvm; | |||
131 | ||||
132 | #define DEBUG_TYPE"loop-reduce" "loop-reduce" | |||
133 | ||||
134 | /// MaxIVUsers is an arbitrary threshold that provides an early opportunity for | |||
135 | /// bail out. This threshold is far beyond the number of users that LSR can | |||
136 | /// conceivably solve, so it should not affect generated code, but catches the | |||
137 | /// worst cases before LSR burns too much compile time and stack space. | |||
138 | static const unsigned MaxIVUsers = 200; | |||
139 | ||||
140 | /// Limit the size of expression that SCEV-based salvaging will attempt to | |||
141 | /// translate into a DIExpression. | |||
142 | /// Choose a maximum size such that debuginfo is not excessively increased and | |||
143 | /// the salvaging is not too expensive for the compiler. | |||
144 | static const unsigned MaxSCEVSalvageExpressionSize = 64; | |||
145 | ||||
146 | // Cleanup congruent phis after LSR phi expansion. | |||
147 | static cl::opt<bool> EnablePhiElim( | |||
148 | "enable-lsr-phielim", cl::Hidden, cl::init(true), | |||
149 | cl::desc("Enable LSR phi elimination")); | |||
150 | ||||
151 | // The flag adds instruction count to solutions cost comparison. | |||
152 | static cl::opt<bool> InsnsCost( | |||
153 | "lsr-insns-cost", cl::Hidden, cl::init(true), | |||
154 | cl::desc("Add instruction count to a LSR cost model")); | |||
155 | ||||
156 | // Flag to choose how to narrow complex lsr solution | |||
157 | static cl::opt<bool> LSRExpNarrow( | |||
158 | "lsr-exp-narrow", cl::Hidden, cl::init(false), | |||
159 | cl::desc("Narrow LSR complex solution using" | |||
160 | " expectation of registers number")); | |||
161 | ||||
162 | // Flag to narrow search space by filtering non-optimal formulae with | |||
163 | // the same ScaledReg and Scale. | |||
164 | static cl::opt<bool> FilterSameScaledReg( | |||
165 | "lsr-filter-same-scaled-reg", cl::Hidden, cl::init(true), | |||
166 | cl::desc("Narrow LSR search space by filtering non-optimal formulae" | |||
167 | " with the same ScaledReg and Scale")); | |||
168 | ||||
169 | static cl::opt<TTI::AddressingModeKind> PreferredAddresingMode( | |||
170 | "lsr-preferred-addressing-mode", cl::Hidden, cl::init(TTI::AMK_None), | |||
171 | cl::desc("A flag that overrides the target's preferred addressing mode."), | |||
172 | cl::values(clEnumValN(TTI::AMK_None,llvm::cl::OptionEnumValue { "none", int(TTI::AMK_None), "Don't prefer any addressing mode" } | |||
173 | "none",llvm::cl::OptionEnumValue { "none", int(TTI::AMK_None), "Don't prefer any addressing mode" } | |||
174 | "Don't prefer any addressing mode")llvm::cl::OptionEnumValue { "none", int(TTI::AMK_None), "Don't prefer any addressing mode" }, | |||
175 | clEnumValN(TTI::AMK_PreIndexed,llvm::cl::OptionEnumValue { "preindexed", int(TTI::AMK_PreIndexed ), "Prefer pre-indexed addressing mode" } | |||
176 | "preindexed",llvm::cl::OptionEnumValue { "preindexed", int(TTI::AMK_PreIndexed ), "Prefer pre-indexed addressing mode" } | |||
177 | "Prefer pre-indexed addressing mode")llvm::cl::OptionEnumValue { "preindexed", int(TTI::AMK_PreIndexed ), "Prefer pre-indexed addressing mode" }, | |||
178 | clEnumValN(TTI::AMK_PostIndexed,llvm::cl::OptionEnumValue { "postindexed", int(TTI::AMK_PostIndexed ), "Prefer post-indexed addressing mode" } | |||
179 | "postindexed",llvm::cl::OptionEnumValue { "postindexed", int(TTI::AMK_PostIndexed ), "Prefer post-indexed addressing mode" } | |||
180 | "Prefer post-indexed addressing mode")llvm::cl::OptionEnumValue { "postindexed", int(TTI::AMK_PostIndexed ), "Prefer post-indexed addressing mode" })); | |||
181 | ||||
182 | static cl::opt<unsigned> ComplexityLimit( | |||
183 | "lsr-complexity-limit", cl::Hidden, | |||
184 | cl::init(std::numeric_limits<uint16_t>::max()), | |||
185 | cl::desc("LSR search space complexity limit")); | |||
186 | ||||
187 | static cl::opt<unsigned> SetupCostDepthLimit( | |||
188 | "lsr-setupcost-depth-limit", cl::Hidden, cl::init(7), | |||
189 | cl::desc("The limit on recursion depth for LSRs setup cost")); | |||
190 | ||||
191 | static cl::opt<bool> AllowTerminatingConditionFoldingAfterLSR( | |||
192 | "lsr-term-fold", cl::Hidden, cl::init(false), | |||
193 | cl::desc("Attempt to replace primary IV with other IV.")); | |||
194 | ||||
195 | static cl::opt<bool> AllowDropSolutionIfLessProfitable( | |||
196 | "lsr-drop-solution", cl::Hidden, cl::init(false), | |||
197 | cl::desc("Attempt to drop solution if it is less profitable")); | |||
198 | ||||
199 | STATISTIC(NumTermFold,static llvm::Statistic NumTermFold = {"loop-reduce", "NumTermFold" , "Number of terminating condition fold recognized and performed" } | |||
200 | "Number of terminating condition fold recognized and performed")static llvm::Statistic NumTermFold = {"loop-reduce", "NumTermFold" , "Number of terminating condition fold recognized and performed" }; | |||
201 | ||||
202 | #ifndef NDEBUG | |||
203 | // Stress test IV chain generation. | |||
204 | static cl::opt<bool> StressIVChain( | |||
205 | "stress-ivchain", cl::Hidden, cl::init(false), | |||
206 | cl::desc("Stress test LSR IV chains")); | |||
207 | #else | |||
208 | static bool StressIVChain = false; | |||
209 | #endif | |||
210 | ||||
211 | namespace { | |||
212 | ||||
213 | struct MemAccessTy { | |||
214 | /// Used in situations where the accessed memory type is unknown. | |||
215 | static const unsigned UnknownAddressSpace = | |||
216 | std::numeric_limits<unsigned>::max(); | |||
217 | ||||
218 | Type *MemTy = nullptr; | |||
219 | unsigned AddrSpace = UnknownAddressSpace; | |||
220 | ||||
221 | MemAccessTy() = default; | |||
222 | MemAccessTy(Type *Ty, unsigned AS) : MemTy(Ty), AddrSpace(AS) {} | |||
223 | ||||
224 | bool operator==(MemAccessTy Other) const { | |||
225 | return MemTy == Other.MemTy && AddrSpace == Other.AddrSpace; | |||
226 | } | |||
227 | ||||
228 | bool operator!=(MemAccessTy Other) const { return !(*this == Other); } | |||
229 | ||||
230 | static MemAccessTy getUnknown(LLVMContext &Ctx, | |||
231 | unsigned AS = UnknownAddressSpace) { | |||
232 | return MemAccessTy(Type::getVoidTy(Ctx), AS); | |||
233 | } | |||
234 | ||||
235 | Type *getType() { return MemTy; } | |||
236 | }; | |||
237 | ||||
238 | /// This class holds data which is used to order reuse candidates. | |||
239 | class RegSortData { | |||
240 | public: | |||
241 | /// This represents the set of LSRUse indices which reference | |||
242 | /// a particular register. | |||
243 | SmallBitVector UsedByIndices; | |||
244 | ||||
245 | void print(raw_ostream &OS) const; | |||
246 | void dump() const; | |||
247 | }; | |||
248 | ||||
249 | } // end anonymous namespace | |||
250 | ||||
251 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) | |||
252 | void RegSortData::print(raw_ostream &OS) const { | |||
253 | OS << "[NumUses=" << UsedByIndices.count() << ']'; | |||
254 | } | |||
255 | ||||
256 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void RegSortData::dump() const { | |||
257 | print(errs()); errs() << '\n'; | |||
258 | } | |||
259 | #endif | |||
260 | ||||
261 | namespace { | |||
262 | ||||
263 | /// Map register candidates to information about how they are used. | |||
264 | class RegUseTracker { | |||
265 | using RegUsesTy = DenseMap<const SCEV *, RegSortData>; | |||
266 | ||||
267 | RegUsesTy RegUsesMap; | |||
268 | SmallVector<const SCEV *, 16> RegSequence; | |||
269 | ||||
270 | public: | |||
271 | void countRegister(const SCEV *Reg, size_t LUIdx); | |||
272 | void dropRegister(const SCEV *Reg, size_t LUIdx); | |||
273 | void swapAndDropUse(size_t LUIdx, size_t LastLUIdx); | |||
274 | ||||
275 | bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const; | |||
276 | ||||
277 | const SmallBitVector &getUsedByIndices(const SCEV *Reg) const; | |||
278 | ||||
279 | void clear(); | |||
280 | ||||
281 | using iterator = SmallVectorImpl<const SCEV *>::iterator; | |||
282 | using const_iterator = SmallVectorImpl<const SCEV *>::const_iterator; | |||
283 | ||||
284 | iterator begin() { return RegSequence.begin(); } | |||
285 | iterator end() { return RegSequence.end(); } | |||
286 | const_iterator begin() const { return RegSequence.begin(); } | |||
287 | const_iterator end() const { return RegSequence.end(); } | |||
288 | }; | |||
289 | ||||
290 | } // end anonymous namespace | |||
291 | ||||
292 | void | |||
293 | RegUseTracker::countRegister(const SCEV *Reg, size_t LUIdx) { | |||
294 | std::pair<RegUsesTy::iterator, bool> Pair = | |||
295 | RegUsesMap.insert(std::make_pair(Reg, RegSortData())); | |||
296 | RegSortData &RSD = Pair.first->second; | |||
297 | if (Pair.second) | |||
298 | RegSequence.push_back(Reg); | |||
299 | RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1)); | |||
300 | RSD.UsedByIndices.set(LUIdx); | |||
301 | } | |||
302 | ||||
303 | void | |||
304 | RegUseTracker::dropRegister(const SCEV *Reg, size_t LUIdx) { | |||
305 | RegUsesTy::iterator It = RegUsesMap.find(Reg); | |||
306 | assert(It != RegUsesMap.end())(static_cast <bool> (It != RegUsesMap.end()) ? void (0) : __assert_fail ("It != RegUsesMap.end()", "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp" , 306, __extension__ __PRETTY_FUNCTION__)); | |||
307 | RegSortData &RSD = It->second; | |||
308 | assert(RSD.UsedByIndices.size() > LUIdx)(static_cast <bool> (RSD.UsedByIndices.size() > LUIdx ) ? void (0) : __assert_fail ("RSD.UsedByIndices.size() > LUIdx" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 308, __extension__ __PRETTY_FUNCTION__)); | |||
309 | RSD.UsedByIndices.reset(LUIdx); | |||
310 | } | |||
311 | ||||
312 | void | |||
313 | RegUseTracker::swapAndDropUse(size_t LUIdx, size_t LastLUIdx) { | |||
314 | assert(LUIdx <= LastLUIdx)(static_cast <bool> (LUIdx <= LastLUIdx) ? void (0) : __assert_fail ("LUIdx <= LastLUIdx", "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp" , 314, __extension__ __PRETTY_FUNCTION__)); | |||
315 | ||||
316 | // Update RegUses. The data structure is not optimized for this purpose; | |||
317 | // we must iterate through it and update each of the bit vectors. | |||
318 | for (auto &Pair : RegUsesMap) { | |||
319 | SmallBitVector &UsedByIndices = Pair.second.UsedByIndices; | |||
320 | if (LUIdx < UsedByIndices.size()) | |||
321 | UsedByIndices[LUIdx] = | |||
322 | LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : false; | |||
323 | UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx)); | |||
324 | } | |||
325 | } | |||
326 | ||||
327 | bool | |||
328 | RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const { | |||
329 | RegUsesTy::const_iterator I = RegUsesMap.find(Reg); | |||
330 | if (I == RegUsesMap.end()) | |||
331 | return false; | |||
332 | const SmallBitVector &UsedByIndices = I->second.UsedByIndices; | |||
333 | int i = UsedByIndices.find_first(); | |||
334 | if (i == -1) return false; | |||
335 | if ((size_t)i != LUIdx) return true; | |||
336 | return UsedByIndices.find_next(i) != -1; | |||
337 | } | |||
338 | ||||
339 | const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const { | |||
340 | RegUsesTy::const_iterator I = RegUsesMap.find(Reg); | |||
341 | assert(I != RegUsesMap.end() && "Unknown register!")(static_cast <bool> (I != RegUsesMap.end() && "Unknown register!" ) ? void (0) : __assert_fail ("I != RegUsesMap.end() && \"Unknown register!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 341, __extension__ __PRETTY_FUNCTION__)); | |||
342 | return I->second.UsedByIndices; | |||
343 | } | |||
344 | ||||
345 | void RegUseTracker::clear() { | |||
346 | RegUsesMap.clear(); | |||
347 | RegSequence.clear(); | |||
348 | } | |||
349 | ||||
350 | namespace { | |||
351 | ||||
352 | /// This class holds information that describes a formula for computing | |||
353 | /// satisfying a use. It may include broken-out immediates and scaled registers. | |||
354 | struct Formula { | |||
355 | /// Global base address used for complex addressing. | |||
356 | GlobalValue *BaseGV = nullptr; | |||
357 | ||||
358 | /// Base offset for complex addressing. | |||
359 | int64_t BaseOffset = 0; | |||
360 | ||||
361 | /// Whether any complex addressing has a base register. | |||
362 | bool HasBaseReg = false; | |||
363 | ||||
364 | /// The scale of any complex addressing. | |||
365 | int64_t Scale = 0; | |||
366 | ||||
367 | /// The list of "base" registers for this use. When this is non-empty. The | |||
368 | /// canonical representation of a formula is | |||
369 | /// 1. BaseRegs.size > 1 implies ScaledReg != NULL and | |||
370 | /// 2. ScaledReg != NULL implies Scale != 1 || !BaseRegs.empty(). | |||
371 | /// 3. The reg containing recurrent expr related with currect loop in the | |||
372 | /// formula should be put in the ScaledReg. | |||
373 | /// #1 enforces that the scaled register is always used when at least two | |||
374 | /// registers are needed by the formula: e.g., reg1 + reg2 is reg1 + 1 * reg2. | |||
375 | /// #2 enforces that 1 * reg is reg. | |||
376 | /// #3 ensures invariant regs with respect to current loop can be combined | |||
377 | /// together in LSR codegen. | |||
378 | /// This invariant can be temporarily broken while building a formula. | |||
379 | /// However, every formula inserted into the LSRInstance must be in canonical | |||
380 | /// form. | |||
381 | SmallVector<const SCEV *, 4> BaseRegs; | |||
382 | ||||
383 | /// The 'scaled' register for this use. This should be non-null when Scale is | |||
384 | /// not zero. | |||
385 | const SCEV *ScaledReg = nullptr; | |||
386 | ||||
387 | /// An additional constant offset which added near the use. This requires a | |||
388 | /// temporary register, but the offset itself can live in an add immediate | |||
389 | /// field rather than a register. | |||
390 | int64_t UnfoldedOffset = 0; | |||
391 | ||||
392 | Formula() = default; | |||
393 | ||||
394 | void initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE); | |||
395 | ||||
396 | bool isCanonical(const Loop &L) const; | |||
397 | ||||
398 | void canonicalize(const Loop &L); | |||
399 | ||||
400 | bool unscale(); | |||
401 | ||||
402 | bool hasZeroEnd() const; | |||
403 | ||||
404 | size_t getNumRegs() const; | |||
405 | Type *getType() const; | |||
406 | ||||
407 | void deleteBaseReg(const SCEV *&S); | |||
408 | ||||
409 | bool referencesReg(const SCEV *S) const; | |||
410 | bool hasRegsUsedByUsesOtherThan(size_t LUIdx, | |||
411 | const RegUseTracker &RegUses) const; | |||
412 | ||||
413 | void print(raw_ostream &OS) const; | |||
414 | void dump() const; | |||
415 | }; | |||
416 | ||||
417 | } // end anonymous namespace | |||
418 | ||||
419 | /// Recursion helper for initialMatch. | |||
420 | static void DoInitialMatch(const SCEV *S, Loop *L, | |||
421 | SmallVectorImpl<const SCEV *> &Good, | |||
422 | SmallVectorImpl<const SCEV *> &Bad, | |||
423 | ScalarEvolution &SE) { | |||
424 | // Collect expressions which properly dominate the loop header. | |||
425 | if (SE.properlyDominates(S, L->getHeader())) { | |||
426 | Good.push_back(S); | |||
427 | return; | |||
428 | } | |||
429 | ||||
430 | // Look at add operands. | |||
431 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { | |||
432 | for (const SCEV *S : Add->operands()) | |||
433 | DoInitialMatch(S, L, Good, Bad, SE); | |||
434 | return; | |||
435 | } | |||
436 | ||||
437 | // Look at addrec operands. | |||
438 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) | |||
439 | if (!AR->getStart()->isZero() && AR->isAffine()) { | |||
440 | DoInitialMatch(AR->getStart(), L, Good, Bad, SE); | |||
441 | DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0), | |||
442 | AR->getStepRecurrence(SE), | |||
443 | // FIXME: AR->getNoWrapFlags() | |||
444 | AR->getLoop(), SCEV::FlagAnyWrap), | |||
445 | L, Good, Bad, SE); | |||
446 | return; | |||
447 | } | |||
448 | ||||
449 | // Handle a multiplication by -1 (negation) if it didn't fold. | |||
450 | if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) | |||
451 | if (Mul->getOperand(0)->isAllOnesValue()) { | |||
452 | SmallVector<const SCEV *, 4> Ops(drop_begin(Mul->operands())); | |||
453 | const SCEV *NewMul = SE.getMulExpr(Ops); | |||
454 | ||||
455 | SmallVector<const SCEV *, 4> MyGood; | |||
456 | SmallVector<const SCEV *, 4> MyBad; | |||
457 | DoInitialMatch(NewMul, L, MyGood, MyBad, SE); | |||
458 | const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue( | |||
459 | SE.getEffectiveSCEVType(NewMul->getType()))); | |||
460 | for (const SCEV *S : MyGood) | |||
461 | Good.push_back(SE.getMulExpr(NegOne, S)); | |||
462 | for (const SCEV *S : MyBad) | |||
463 | Bad.push_back(SE.getMulExpr(NegOne, S)); | |||
464 | return; | |||
465 | } | |||
466 | ||||
467 | // Ok, we can't do anything interesting. Just stuff the whole thing into a | |||
468 | // register and hope for the best. | |||
469 | Bad.push_back(S); | |||
470 | } | |||
471 | ||||
472 | /// Incorporate loop-variant parts of S into this Formula, attempting to keep | |||
473 | /// all loop-invariant and loop-computable values in a single base register. | |||
474 | void Formula::initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) { | |||
475 | SmallVector<const SCEV *, 4> Good; | |||
476 | SmallVector<const SCEV *, 4> Bad; | |||
477 | DoInitialMatch(S, L, Good, Bad, SE); | |||
478 | if (!Good.empty()) { | |||
479 | const SCEV *Sum = SE.getAddExpr(Good); | |||
480 | if (!Sum->isZero()) | |||
481 | BaseRegs.push_back(Sum); | |||
482 | HasBaseReg = true; | |||
483 | } | |||
484 | if (!Bad.empty()) { | |||
485 | const SCEV *Sum = SE.getAddExpr(Bad); | |||
486 | if (!Sum->isZero()) | |||
487 | BaseRegs.push_back(Sum); | |||
488 | HasBaseReg = true; | |||
489 | } | |||
490 | canonicalize(*L); | |||
491 | } | |||
492 | ||||
493 | static bool containsAddRecDependentOnLoop(const SCEV *S, const Loop &L) { | |||
494 | return SCEVExprContains(S, [&L](const SCEV *S) { | |||
495 | return isa<SCEVAddRecExpr>(S) && (cast<SCEVAddRecExpr>(S)->getLoop() == &L); | |||
496 | }); | |||
497 | } | |||
498 | ||||
499 | /// Check whether or not this formula satisfies the canonical | |||
500 | /// representation. | |||
501 | /// \see Formula::BaseRegs. | |||
502 | bool Formula::isCanonical(const Loop &L) const { | |||
503 | if (!ScaledReg) | |||
504 | return BaseRegs.size() <= 1; | |||
505 | ||||
506 | if (Scale != 1) | |||
507 | return true; | |||
508 | ||||
509 | if (Scale == 1 && BaseRegs.empty()) | |||
510 | return false; | |||
511 | ||||
512 | if (containsAddRecDependentOnLoop(ScaledReg, L)) | |||
513 | return true; | |||
514 | ||||
515 | // If ScaledReg is not a recurrent expr, or it is but its loop is not current | |||
516 | // loop, meanwhile BaseRegs contains a recurrent expr reg related with current | |||
517 | // loop, we want to swap the reg in BaseRegs with ScaledReg. | |||
518 | return none_of(BaseRegs, [&L](const SCEV *S) { | |||
519 | return containsAddRecDependentOnLoop(S, L); | |||
520 | }); | |||
521 | } | |||
522 | ||||
523 | /// Helper method to morph a formula into its canonical representation. | |||
524 | /// \see Formula::BaseRegs. | |||
525 | /// Every formula having more than one base register, must use the ScaledReg | |||
526 | /// field. Otherwise, we would have to do special cases everywhere in LSR | |||
527 | /// to treat reg1 + reg2 + ... the same way as reg1 + 1*reg2 + ... | |||
528 | /// On the other hand, 1*reg should be canonicalized into reg. | |||
529 | void Formula::canonicalize(const Loop &L) { | |||
530 | if (isCanonical(L)) | |||
531 | return; | |||
532 | ||||
533 | if (BaseRegs.empty()) { | |||
534 | // No base reg? Use scale reg with scale = 1 as such. | |||
535 | assert(ScaledReg && "Expected 1*reg => reg")(static_cast <bool> (ScaledReg && "Expected 1*reg => reg" ) ? void (0) : __assert_fail ("ScaledReg && \"Expected 1*reg => reg\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 535, __extension__ __PRETTY_FUNCTION__)); | |||
536 | assert(Scale == 1 && "Expected 1*reg => reg")(static_cast <bool> (Scale == 1 && "Expected 1*reg => reg" ) ? void (0) : __assert_fail ("Scale == 1 && \"Expected 1*reg => reg\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 536, __extension__ __PRETTY_FUNCTION__)); | |||
537 | BaseRegs.push_back(ScaledReg); | |||
538 | Scale = 0; | |||
539 | ScaledReg = nullptr; | |||
540 | return; | |||
541 | } | |||
542 | ||||
543 | // Keep the invariant sum in BaseRegs and one of the variant sum in ScaledReg. | |||
544 | if (!ScaledReg) { | |||
545 | ScaledReg = BaseRegs.pop_back_val(); | |||
546 | Scale = 1; | |||
547 | } | |||
548 | ||||
549 | // If ScaledReg is an invariant with respect to L, find the reg from | |||
550 | // BaseRegs containing the recurrent expr related with Loop L. Swap the | |||
551 | // reg with ScaledReg. | |||
552 | if (!containsAddRecDependentOnLoop(ScaledReg, L)) { | |||
553 | auto I = find_if(BaseRegs, [&L](const SCEV *S) { | |||
554 | return containsAddRecDependentOnLoop(S, L); | |||
555 | }); | |||
556 | if (I != BaseRegs.end()) | |||
557 | std::swap(ScaledReg, *I); | |||
558 | } | |||
559 | assert(isCanonical(L) && "Failed to canonicalize?")(static_cast <bool> (isCanonical(L) && "Failed to canonicalize?" ) ? void (0) : __assert_fail ("isCanonical(L) && \"Failed to canonicalize?\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 559, __extension__ __PRETTY_FUNCTION__)); | |||
560 | } | |||
561 | ||||
562 | /// Get rid of the scale in the formula. | |||
563 | /// In other words, this method morphes reg1 + 1*reg2 into reg1 + reg2. | |||
564 | /// \return true if it was possible to get rid of the scale, false otherwise. | |||
565 | /// \note After this operation the formula may not be in the canonical form. | |||
566 | bool Formula::unscale() { | |||
567 | if (Scale != 1) | |||
568 | return false; | |||
569 | Scale = 0; | |||
570 | BaseRegs.push_back(ScaledReg); | |||
571 | ScaledReg = nullptr; | |||
572 | return true; | |||
573 | } | |||
574 | ||||
575 | bool Formula::hasZeroEnd() const { | |||
576 | if (UnfoldedOffset || BaseOffset) | |||
577 | return false; | |||
578 | if (BaseRegs.size() != 1 || ScaledReg) | |||
579 | return false; | |||
580 | return true; | |||
581 | } | |||
582 | ||||
583 | /// Return the total number of register operands used by this formula. This does | |||
584 | /// not include register uses implied by non-constant addrec strides. | |||
585 | size_t Formula::getNumRegs() const { | |||
586 | return !!ScaledReg + BaseRegs.size(); | |||
587 | } | |||
588 | ||||
589 | /// Return the type of this formula, if it has one, or null otherwise. This type | |||
590 | /// is meaningless except for the bit size. | |||
591 | Type *Formula::getType() const { | |||
592 | return !BaseRegs.empty() ? BaseRegs.front()->getType() : | |||
593 | ScaledReg ? ScaledReg->getType() : | |||
594 | BaseGV ? BaseGV->getType() : | |||
595 | nullptr; | |||
596 | } | |||
597 | ||||
598 | /// Delete the given base reg from the BaseRegs list. | |||
599 | void Formula::deleteBaseReg(const SCEV *&S) { | |||
600 | if (&S != &BaseRegs.back()) | |||
601 | std::swap(S, BaseRegs.back()); | |||
602 | BaseRegs.pop_back(); | |||
603 | } | |||
604 | ||||
605 | /// Test if this formula references the given register. | |||
606 | bool Formula::referencesReg(const SCEV *S) const { | |||
607 | return S == ScaledReg || is_contained(BaseRegs, S); | |||
608 | } | |||
609 | ||||
610 | /// Test whether this formula uses registers which are used by uses other than | |||
611 | /// the use with the given index. | |||
612 | bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx, | |||
613 | const RegUseTracker &RegUses) const { | |||
614 | if (ScaledReg) | |||
615 | if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx)) | |||
616 | return true; | |||
617 | for (const SCEV *BaseReg : BaseRegs) | |||
618 | if (RegUses.isRegUsedByUsesOtherThan(BaseReg, LUIdx)) | |||
619 | return true; | |||
620 | return false; | |||
621 | } | |||
622 | ||||
623 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) | |||
624 | void Formula::print(raw_ostream &OS) const { | |||
625 | bool First = true; | |||
626 | if (BaseGV) { | |||
627 | if (!First) OS << " + "; else First = false; | |||
628 | BaseGV->printAsOperand(OS, /*PrintType=*/false); | |||
629 | } | |||
630 | if (BaseOffset != 0) { | |||
631 | if (!First) OS << " + "; else First = false; | |||
632 | OS << BaseOffset; | |||
633 | } | |||
634 | for (const SCEV *BaseReg : BaseRegs) { | |||
635 | if (!First) OS << " + "; else First = false; | |||
636 | OS << "reg(" << *BaseReg << ')'; | |||
637 | } | |||
638 | if (HasBaseReg && BaseRegs.empty()) { | |||
639 | if (!First) OS << " + "; else First = false; | |||
640 | OS << "**error: HasBaseReg**"; | |||
641 | } else if (!HasBaseReg && !BaseRegs.empty()) { | |||
642 | if (!First) OS << " + "; else First = false; | |||
643 | OS << "**error: !HasBaseReg**"; | |||
644 | } | |||
645 | if (Scale != 0) { | |||
646 | if (!First) OS << " + "; else First = false; | |||
647 | OS << Scale << "*reg("; | |||
648 | if (ScaledReg) | |||
649 | OS << *ScaledReg; | |||
650 | else | |||
651 | OS << "<unknown>"; | |||
652 | OS << ')'; | |||
653 | } | |||
654 | if (UnfoldedOffset != 0) { | |||
655 | if (!First) OS << " + "; | |||
656 | OS << "imm(" << UnfoldedOffset << ')'; | |||
657 | } | |||
658 | } | |||
659 | ||||
660 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void Formula::dump() const { | |||
661 | print(errs()); errs() << '\n'; | |||
662 | } | |||
663 | #endif | |||
664 | ||||
665 | /// Return true if the given addrec can be sign-extended without changing its | |||
666 | /// value. | |||
667 | static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) { | |||
668 | Type *WideTy = | |||
669 | IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1); | |||
670 | return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy)); | |||
671 | } | |||
672 | ||||
673 | /// Return true if the given add can be sign-extended without changing its | |||
674 | /// value. | |||
675 | static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) { | |||
676 | Type *WideTy = | |||
677 | IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1); | |||
678 | return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy)); | |||
679 | } | |||
680 | ||||
681 | /// Return true if the given mul can be sign-extended without changing its | |||
682 | /// value. | |||
683 | static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) { | |||
684 | Type *WideTy = | |||
685 | IntegerType::get(SE.getContext(), | |||
686 | SE.getTypeSizeInBits(M->getType()) * M->getNumOperands()); | |||
687 | return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy)); | |||
688 | } | |||
689 | ||||
690 | /// Return an expression for LHS /s RHS, if it can be determined and if the | |||
691 | /// remainder is known to be zero, or null otherwise. If IgnoreSignificantBits | |||
692 | /// is true, expressions like (X * Y) /s Y are simplified to X, ignoring that | |||
693 | /// the multiplication may overflow, which is useful when the result will be | |||
694 | /// used in a context where the most significant bits are ignored. | |||
695 | static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS, | |||
696 | ScalarEvolution &SE, | |||
697 | bool IgnoreSignificantBits = false) { | |||
698 | // Handle the trivial case, which works for any SCEV type. | |||
699 | if (LHS == RHS) | |||
700 | return SE.getConstant(LHS->getType(), 1); | |||
701 | ||||
702 | // Handle a few RHS special cases. | |||
703 | const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS); | |||
704 | if (RC) { | |||
705 | const APInt &RA = RC->getAPInt(); | |||
706 | // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do | |||
707 | // some folding. | |||
708 | if (RA.isAllOnes()) { | |||
709 | if (LHS->getType()->isPointerTy()) | |||
710 | return nullptr; | |||
711 | return SE.getMulExpr(LHS, RC); | |||
712 | } | |||
713 | // Handle x /s 1 as x. | |||
714 | if (RA == 1) | |||
715 | return LHS; | |||
716 | } | |||
717 | ||||
718 | // Check for a division of a constant by a constant. | |||
719 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) { | |||
720 | if (!RC) | |||
721 | return nullptr; | |||
722 | const APInt &LA = C->getAPInt(); | |||
723 | const APInt &RA = RC->getAPInt(); | |||
724 | if (LA.srem(RA) != 0) | |||
725 | return nullptr; | |||
726 | return SE.getConstant(LA.sdiv(RA)); | |||
727 | } | |||
728 | ||||
729 | // Distribute the sdiv over addrec operands, if the addrec doesn't overflow. | |||
730 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) { | |||
731 | if ((IgnoreSignificantBits || isAddRecSExtable(AR, SE)) && AR->isAffine()) { | |||
732 | const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE, | |||
733 | IgnoreSignificantBits); | |||
734 | if (!Step) return nullptr; | |||
735 | const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE, | |||
736 | IgnoreSignificantBits); | |||
737 | if (!Start) return nullptr; | |||
738 | // FlagNW is independent of the start value, step direction, and is | |||
739 | // preserved with smaller magnitude steps. | |||
740 | // FIXME: AR->getNoWrapFlags(SCEV::FlagNW) | |||
741 | return SE.getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagAnyWrap); | |||
742 | } | |||
743 | return nullptr; | |||
744 | } | |||
745 | ||||
746 | // Distribute the sdiv over add operands, if the add doesn't overflow. | |||
747 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) { | |||
748 | if (IgnoreSignificantBits || isAddSExtable(Add, SE)) { | |||
749 | SmallVector<const SCEV *, 8> Ops; | |||
750 | for (const SCEV *S : Add->operands()) { | |||
751 | const SCEV *Op = getExactSDiv(S, RHS, SE, IgnoreSignificantBits); | |||
752 | if (!Op) return nullptr; | |||
753 | Ops.push_back(Op); | |||
754 | } | |||
755 | return SE.getAddExpr(Ops); | |||
756 | } | |||
757 | return nullptr; | |||
758 | } | |||
759 | ||||
760 | // Check for a multiply operand that we can pull RHS out of. | |||
761 | if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) { | |||
762 | if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) { | |||
763 | // Handle special case C1*X*Y /s C2*X*Y. | |||
764 | if (const SCEVMulExpr *MulRHS = dyn_cast<SCEVMulExpr>(RHS)) { | |||
765 | if (IgnoreSignificantBits || isMulSExtable(MulRHS, SE)) { | |||
766 | const SCEVConstant *LC = dyn_cast<SCEVConstant>(Mul->getOperand(0)); | |||
767 | const SCEVConstant *RC = | |||
768 | dyn_cast<SCEVConstant>(MulRHS->getOperand(0)); | |||
769 | if (LC && RC) { | |||
770 | SmallVector<const SCEV *, 4> LOps(drop_begin(Mul->operands())); | |||
771 | SmallVector<const SCEV *, 4> ROps(drop_begin(MulRHS->operands())); | |||
772 | if (LOps == ROps) | |||
773 | return getExactSDiv(LC, RC, SE, IgnoreSignificantBits); | |||
774 | } | |||
775 | } | |||
776 | } | |||
777 | ||||
778 | SmallVector<const SCEV *, 4> Ops; | |||
779 | bool Found = false; | |||
780 | for (const SCEV *S : Mul->operands()) { | |||
781 | if (!Found) | |||
782 | if (const SCEV *Q = getExactSDiv(S, RHS, SE, | |||
783 | IgnoreSignificantBits)) { | |||
784 | S = Q; | |||
785 | Found = true; | |||
786 | } | |||
787 | Ops.push_back(S); | |||
788 | } | |||
789 | return Found ? SE.getMulExpr(Ops) : nullptr; | |||
790 | } | |||
791 | return nullptr; | |||
792 | } | |||
793 | ||||
794 | // Otherwise we don't know. | |||
795 | return nullptr; | |||
796 | } | |||
797 | ||||
798 | /// If S involves the addition of a constant integer value, return that integer | |||
799 | /// value, and mutate S to point to a new SCEV with that value excluded. | |||
800 | static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) { | |||
801 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) { | |||
802 | if (C->getAPInt().getSignificantBits() <= 64) { | |||
803 | S = SE.getConstant(C->getType(), 0); | |||
804 | return C->getValue()->getSExtValue(); | |||
805 | } | |||
806 | } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { | |||
807 | SmallVector<const SCEV *, 8> NewOps(Add->operands()); | |||
808 | int64_t Result = ExtractImmediate(NewOps.front(), SE); | |||
809 | if (Result != 0) | |||
810 | S = SE.getAddExpr(NewOps); | |||
811 | return Result; | |||
812 | } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { | |||
813 | SmallVector<const SCEV *, 8> NewOps(AR->operands()); | |||
814 | int64_t Result = ExtractImmediate(NewOps.front(), SE); | |||
815 | if (Result != 0) | |||
816 | S = SE.getAddRecExpr(NewOps, AR->getLoop(), | |||
817 | // FIXME: AR->getNoWrapFlags(SCEV::FlagNW) | |||
818 | SCEV::FlagAnyWrap); | |||
819 | return Result; | |||
820 | } | |||
821 | return 0; | |||
822 | } | |||
823 | ||||
824 | /// If S involves the addition of a GlobalValue address, return that symbol, and | |||
825 | /// mutate S to point to a new SCEV with that value excluded. | |||
826 | static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) { | |||
827 | if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) { | |||
828 | if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) { | |||
829 | S = SE.getConstant(GV->getType(), 0); | |||
830 | return GV; | |||
831 | } | |||
832 | } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { | |||
833 | SmallVector<const SCEV *, 8> NewOps(Add->operands()); | |||
834 | GlobalValue *Result = ExtractSymbol(NewOps.back(), SE); | |||
835 | if (Result) | |||
836 | S = SE.getAddExpr(NewOps); | |||
837 | return Result; | |||
838 | } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { | |||
839 | SmallVector<const SCEV *, 8> NewOps(AR->operands()); | |||
840 | GlobalValue *Result = ExtractSymbol(NewOps.front(), SE); | |||
841 | if (Result) | |||
842 | S = SE.getAddRecExpr(NewOps, AR->getLoop(), | |||
843 | // FIXME: AR->getNoWrapFlags(SCEV::FlagNW) | |||
844 | SCEV::FlagAnyWrap); | |||
845 | return Result; | |||
846 | } | |||
847 | return nullptr; | |||
848 | } | |||
849 | ||||
850 | /// Returns true if the specified instruction is using the specified value as an | |||
851 | /// address. | |||
852 | static bool isAddressUse(const TargetTransformInfo &TTI, | |||
853 | Instruction *Inst, Value *OperandVal) { | |||
854 | bool isAddress = isa<LoadInst>(Inst); | |||
855 | if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { | |||
856 | if (SI->getPointerOperand() == OperandVal) | |||
857 | isAddress = true; | |||
858 | } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { | |||
859 | // Addressing modes can also be folded into prefetches and a variety | |||
860 | // of intrinsics. | |||
861 | switch (II->getIntrinsicID()) { | |||
862 | case Intrinsic::memset: | |||
863 | case Intrinsic::prefetch: | |||
864 | case Intrinsic::masked_load: | |||
865 | if (II->getArgOperand(0) == OperandVal) | |||
866 | isAddress = true; | |||
867 | break; | |||
868 | case Intrinsic::masked_store: | |||
869 | if (II->getArgOperand(1) == OperandVal) | |||
870 | isAddress = true; | |||
871 | break; | |||
872 | case Intrinsic::memmove: | |||
873 | case Intrinsic::memcpy: | |||
874 | if (II->getArgOperand(0) == OperandVal || | |||
875 | II->getArgOperand(1) == OperandVal) | |||
876 | isAddress = true; | |||
877 | break; | |||
878 | default: { | |||
879 | MemIntrinsicInfo IntrInfo; | |||
880 | if (TTI.getTgtMemIntrinsic(II, IntrInfo)) { | |||
881 | if (IntrInfo.PtrVal == OperandVal) | |||
882 | isAddress = true; | |||
883 | } | |||
884 | } | |||
885 | } | |||
886 | } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) { | |||
887 | if (RMW->getPointerOperand() == OperandVal) | |||
888 | isAddress = true; | |||
889 | } else if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) { | |||
890 | if (CmpX->getPointerOperand() == OperandVal) | |||
891 | isAddress = true; | |||
892 | } | |||
893 | return isAddress; | |||
894 | } | |||
895 | ||||
896 | /// Return the type of the memory being accessed. | |||
897 | static MemAccessTy getAccessType(const TargetTransformInfo &TTI, | |||
898 | Instruction *Inst, Value *OperandVal) { | |||
899 | MemAccessTy AccessTy(Inst->getType(), MemAccessTy::UnknownAddressSpace); | |||
900 | if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) { | |||
901 | AccessTy.MemTy = SI->getOperand(0)->getType(); | |||
902 | AccessTy.AddrSpace = SI->getPointerAddressSpace(); | |||
903 | } else if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) { | |||
904 | AccessTy.AddrSpace = LI->getPointerAddressSpace(); | |||
905 | } else if (const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) { | |||
906 | AccessTy.AddrSpace = RMW->getPointerAddressSpace(); | |||
907 | } else if (const AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) { | |||
908 | AccessTy.AddrSpace = CmpX->getPointerAddressSpace(); | |||
909 | } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) { | |||
910 | switch (II->getIntrinsicID()) { | |||
911 | case Intrinsic::prefetch: | |||
912 | case Intrinsic::memset: | |||
913 | AccessTy.AddrSpace = II->getArgOperand(0)->getType()->getPointerAddressSpace(); | |||
914 | AccessTy.MemTy = OperandVal->getType(); | |||
915 | break; | |||
916 | case Intrinsic::memmove: | |||
917 | case Intrinsic::memcpy: | |||
918 | AccessTy.AddrSpace = OperandVal->getType()->getPointerAddressSpace(); | |||
919 | AccessTy.MemTy = OperandVal->getType(); | |||
920 | break; | |||
921 | case Intrinsic::masked_load: | |||
922 | AccessTy.AddrSpace = | |||
923 | II->getArgOperand(0)->getType()->getPointerAddressSpace(); | |||
924 | break; | |||
925 | case Intrinsic::masked_store: | |||
926 | AccessTy.MemTy = II->getOperand(0)->getType(); | |||
927 | AccessTy.AddrSpace = | |||
928 | II->getArgOperand(1)->getType()->getPointerAddressSpace(); | |||
929 | break; | |||
930 | default: { | |||
931 | MemIntrinsicInfo IntrInfo; | |||
932 | if (TTI.getTgtMemIntrinsic(II, IntrInfo) && IntrInfo.PtrVal) { | |||
933 | AccessTy.AddrSpace | |||
934 | = IntrInfo.PtrVal->getType()->getPointerAddressSpace(); | |||
935 | } | |||
936 | ||||
937 | break; | |||
938 | } | |||
939 | } | |||
940 | } | |||
941 | ||||
942 | // All pointers have the same requirements, so canonicalize them to an | |||
943 | // arbitrary pointer type to minimize variation. | |||
944 | if (PointerType *PTy = dyn_cast<PointerType>(AccessTy.MemTy)) | |||
945 | AccessTy.MemTy = PointerType::get(IntegerType::get(PTy->getContext(), 1), | |||
946 | PTy->getAddressSpace()); | |||
947 | ||||
948 | return AccessTy; | |||
949 | } | |||
950 | ||||
951 | /// Return true if this AddRec is already a phi in its loop. | |||
952 | static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) { | |||
953 | for (PHINode &PN : AR->getLoop()->getHeader()->phis()) { | |||
954 | if (SE.isSCEVable(PN.getType()) && | |||
955 | (SE.getEffectiveSCEVType(PN.getType()) == | |||
956 | SE.getEffectiveSCEVType(AR->getType())) && | |||
957 | SE.getSCEV(&PN) == AR) | |||
958 | return true; | |||
959 | } | |||
960 | return false; | |||
961 | } | |||
962 | ||||
963 | /// Check if expanding this expression is likely to incur significant cost. This | |||
964 | /// is tricky because SCEV doesn't track which expressions are actually computed | |||
965 | /// by the current IR. | |||
966 | /// | |||
967 | /// We currently allow expansion of IV increments that involve adds, | |||
968 | /// multiplication by constants, and AddRecs from existing phis. | |||
969 | /// | |||
970 | /// TODO: Allow UDivExpr if we can find an existing IV increment that is an | |||
971 | /// obvious multiple of the UDivExpr. | |||
972 | static bool isHighCostExpansion(const SCEV *S, | |||
973 | SmallPtrSetImpl<const SCEV*> &Processed, | |||
974 | ScalarEvolution &SE) { | |||
975 | // Zero/One operand expressions | |||
976 | switch (S->getSCEVType()) { | |||
977 | case scUnknown: | |||
978 | case scConstant: | |||
979 | case scVScale: | |||
980 | return false; | |||
981 | case scTruncate: | |||
982 | return isHighCostExpansion(cast<SCEVTruncateExpr>(S)->getOperand(), | |||
983 | Processed, SE); | |||
984 | case scZeroExtend: | |||
985 | return isHighCostExpansion(cast<SCEVZeroExtendExpr>(S)->getOperand(), | |||
986 | Processed, SE); | |||
987 | case scSignExtend: | |||
988 | return isHighCostExpansion(cast<SCEVSignExtendExpr>(S)->getOperand(), | |||
989 | Processed, SE); | |||
990 | default: | |||
991 | break; | |||
992 | } | |||
993 | ||||
994 | if (!Processed.insert(S).second) | |||
995 | return false; | |||
996 | ||||
997 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { | |||
998 | for (const SCEV *S : Add->operands()) { | |||
999 | if (isHighCostExpansion(S, Processed, SE)) | |||
1000 | return true; | |||
1001 | } | |||
1002 | return false; | |||
1003 | } | |||
1004 | ||||
1005 | if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { | |||
1006 | if (Mul->getNumOperands() == 2) { | |||
1007 | // Multiplication by a constant is ok | |||
1008 | if (isa<SCEVConstant>(Mul->getOperand(0))) | |||
1009 | return isHighCostExpansion(Mul->getOperand(1), Processed, SE); | |||
1010 | ||||
1011 | // If we have the value of one operand, check if an existing | |||
1012 | // multiplication already generates this expression. | |||
1013 | if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) { | |||
1014 | Value *UVal = U->getValue(); | |||
1015 | for (User *UR : UVal->users()) { | |||
1016 | // If U is a constant, it may be used by a ConstantExpr. | |||
1017 | Instruction *UI = dyn_cast<Instruction>(UR); | |||
1018 | if (UI && UI->getOpcode() == Instruction::Mul && | |||
1019 | SE.isSCEVable(UI->getType())) { | |||
1020 | return SE.getSCEV(UI) == Mul; | |||
1021 | } | |||
1022 | } | |||
1023 | } | |||
1024 | } | |||
1025 | } | |||
1026 | ||||
1027 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { | |||
1028 | if (isExistingPhi(AR, SE)) | |||
1029 | return false; | |||
1030 | } | |||
1031 | ||||
1032 | // Fow now, consider any other type of expression (div/mul/min/max) high cost. | |||
1033 | return true; | |||
1034 | } | |||
1035 | ||||
1036 | namespace { | |||
1037 | ||||
1038 | class LSRUse; | |||
1039 | ||||
1040 | } // end anonymous namespace | |||
1041 | ||||
1042 | /// Check if the addressing mode defined by \p F is completely | |||
1043 | /// folded in \p LU at isel time. | |||
1044 | /// This includes address-mode folding and special icmp tricks. | |||
1045 | /// This function returns true if \p LU can accommodate what \p F | |||
1046 | /// defines and up to 1 base + 1 scaled + offset. | |||
1047 | /// In other words, if \p F has several base registers, this function may | |||
1048 | /// still return true. Therefore, users still need to account for | |||
1049 | /// additional base registers and/or unfolded offsets to derive an | |||
1050 | /// accurate cost model. | |||
1051 | static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, | |||
1052 | const LSRUse &LU, const Formula &F); | |||
1053 | ||||
1054 | // Get the cost of the scaling factor used in F for LU. | |||
1055 | static InstructionCost getScalingFactorCost(const TargetTransformInfo &TTI, | |||
1056 | const LSRUse &LU, const Formula &F, | |||
1057 | const Loop &L); | |||
1058 | ||||
1059 | namespace { | |||
1060 | ||||
1061 | /// This class is used to measure and compare candidate formulae. | |||
1062 | class Cost { | |||
1063 | const Loop *L = nullptr; | |||
1064 | ScalarEvolution *SE = nullptr; | |||
1065 | const TargetTransformInfo *TTI = nullptr; | |||
1066 | TargetTransformInfo::LSRCost C; | |||
1067 | TTI::AddressingModeKind AMK = TTI::AMK_None; | |||
1068 | ||||
1069 | public: | |||
1070 | Cost() = delete; | |||
1071 | Cost(const Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI, | |||
1072 | TTI::AddressingModeKind AMK) : | |||
1073 | L(L), SE(&SE), TTI(&TTI), AMK(AMK) { | |||
1074 | C.Insns = 0; | |||
1075 | C.NumRegs = 0; | |||
1076 | C.AddRecCost = 0; | |||
1077 | C.NumIVMuls = 0; | |||
1078 | C.NumBaseAdds = 0; | |||
1079 | C.ImmCost = 0; | |||
1080 | C.SetupCost = 0; | |||
1081 | C.ScaleCost = 0; | |||
1082 | } | |||
1083 | ||||
1084 | bool isLess(const Cost &Other) const; | |||
1085 | ||||
1086 | void Lose(); | |||
1087 | ||||
1088 | #ifndef NDEBUG | |||
1089 | // Once any of the metrics loses, they must all remain losers. | |||
1090 | bool isValid() { | |||
1091 | return ((C.Insns | C.NumRegs | C.AddRecCost | C.NumIVMuls | C.NumBaseAdds | |||
1092 | | C.ImmCost | C.SetupCost | C.ScaleCost) != ~0u) | |||
1093 | || ((C.Insns & C.NumRegs & C.AddRecCost & C.NumIVMuls & C.NumBaseAdds | |||
1094 | & C.ImmCost & C.SetupCost & C.ScaleCost) == ~0u); | |||
1095 | } | |||
1096 | #endif | |||
1097 | ||||
1098 | bool isLoser() { | |||
1099 | assert(isValid() && "invalid cost")(static_cast <bool> (isValid() && "invalid cost" ) ? void (0) : __assert_fail ("isValid() && \"invalid cost\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 1099, __extension__ __PRETTY_FUNCTION__)); | |||
1100 | return C.NumRegs == ~0u; | |||
1101 | } | |||
1102 | ||||
1103 | void RateFormula(const Formula &F, | |||
1104 | SmallPtrSetImpl<const SCEV *> &Regs, | |||
1105 | const DenseSet<const SCEV *> &VisitedRegs, | |||
1106 | const LSRUse &LU, | |||
1107 | SmallPtrSetImpl<const SCEV *> *LoserRegs = nullptr); | |||
1108 | ||||
1109 | void print(raw_ostream &OS) const; | |||
1110 | void dump() const; | |||
1111 | ||||
1112 | private: | |||
1113 | void RateRegister(const Formula &F, const SCEV *Reg, | |||
1114 | SmallPtrSetImpl<const SCEV *> &Regs); | |||
1115 | void RatePrimaryRegister(const Formula &F, const SCEV *Reg, | |||
1116 | SmallPtrSetImpl<const SCEV *> &Regs, | |||
1117 | SmallPtrSetImpl<const SCEV *> *LoserRegs); | |||
1118 | }; | |||
1119 | ||||
1120 | /// An operand value in an instruction which is to be replaced with some | |||
1121 | /// equivalent, possibly strength-reduced, replacement. | |||
1122 | struct LSRFixup { | |||
1123 | /// The instruction which will be updated. | |||
1124 | Instruction *UserInst = nullptr; | |||
1125 | ||||
1126 | /// The operand of the instruction which will be replaced. The operand may be | |||
1127 | /// used more than once; every instance will be replaced. | |||
1128 | Value *OperandValToReplace = nullptr; | |||
1129 | ||||
1130 | /// If this user is to use the post-incremented value of an induction | |||
1131 | /// variable, this set is non-empty and holds the loops associated with the | |||
1132 | /// induction variable. | |||
1133 | PostIncLoopSet PostIncLoops; | |||
1134 | ||||
1135 | /// A constant offset to be added to the LSRUse expression. This allows | |||
1136 | /// multiple fixups to share the same LSRUse with different offsets, for | |||
1137 | /// example in an unrolled loop. | |||
1138 | int64_t Offset = 0; | |||
1139 | ||||
1140 | LSRFixup() = default; | |||
1141 | ||||
1142 | bool isUseFullyOutsideLoop(const Loop *L) const; | |||
1143 | ||||
1144 | void print(raw_ostream &OS) const; | |||
1145 | void dump() const; | |||
1146 | }; | |||
1147 | ||||
1148 | /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of sorted | |||
1149 | /// SmallVectors of const SCEV*. | |||
1150 | struct UniquifierDenseMapInfo { | |||
1151 | static SmallVector<const SCEV *, 4> getEmptyKey() { | |||
1152 | SmallVector<const SCEV *, 4> V; | |||
1153 | V.push_back(reinterpret_cast<const SCEV *>(-1)); | |||
1154 | return V; | |||
1155 | } | |||
1156 | ||||
1157 | static SmallVector<const SCEV *, 4> getTombstoneKey() { | |||
1158 | SmallVector<const SCEV *, 4> V; | |||
1159 | V.push_back(reinterpret_cast<const SCEV *>(-2)); | |||
1160 | return V; | |||
1161 | } | |||
1162 | ||||
1163 | static unsigned getHashValue(const SmallVector<const SCEV *, 4> &V) { | |||
1164 | return static_cast<unsigned>(hash_combine_range(V.begin(), V.end())); | |||
1165 | } | |||
1166 | ||||
1167 | static bool isEqual(const SmallVector<const SCEV *, 4> &LHS, | |||
1168 | const SmallVector<const SCEV *, 4> &RHS) { | |||
1169 | return LHS == RHS; | |||
1170 | } | |||
1171 | }; | |||
1172 | ||||
1173 | /// This class holds the state that LSR keeps for each use in IVUsers, as well | |||
1174 | /// as uses invented by LSR itself. It includes information about what kinds of | |||
1175 | /// things can be folded into the user, information about the user itself, and | |||
1176 | /// information about how the use may be satisfied. TODO: Represent multiple | |||
1177 | /// users of the same expression in common? | |||
1178 | class LSRUse { | |||
1179 | DenseSet<SmallVector<const SCEV *, 4>, UniquifierDenseMapInfo> Uniquifier; | |||
1180 | ||||
1181 | public: | |||
1182 | /// An enum for a kind of use, indicating what types of scaled and immediate | |||
1183 | /// operands it might support. | |||
1184 | enum KindType { | |||
1185 | Basic, ///< A normal use, with no folding. | |||
1186 | Special, ///< A special case of basic, allowing -1 scales. | |||
1187 | Address, ///< An address use; folding according to TargetLowering | |||
1188 | ICmpZero ///< An equality icmp with both operands folded into one. | |||
1189 | // TODO: Add a generic icmp too? | |||
1190 | }; | |||
1191 | ||||
1192 | using SCEVUseKindPair = PointerIntPair<const SCEV *, 2, KindType>; | |||
1193 | ||||
1194 | KindType Kind; | |||
1195 | MemAccessTy AccessTy; | |||
1196 | ||||
1197 | /// The list of operands which are to be replaced. | |||
1198 | SmallVector<LSRFixup, 8> Fixups; | |||
1199 | ||||
1200 | /// Keep track of the min and max offsets of the fixups. | |||
1201 | int64_t MinOffset = std::numeric_limits<int64_t>::max(); | |||
1202 | int64_t MaxOffset = std::numeric_limits<int64_t>::min(); | |||
1203 | ||||
1204 | /// This records whether all of the fixups using this LSRUse are outside of | |||
1205 | /// the loop, in which case some special-case heuristics may be used. | |||
1206 | bool AllFixupsOutsideLoop = true; | |||
1207 | ||||
1208 | /// RigidFormula is set to true to guarantee that this use will be associated | |||
1209 | /// with a single formula--the one that initially matched. Some SCEV | |||
1210 | /// expressions cannot be expanded. This allows LSR to consider the registers | |||
1211 | /// used by those expressions without the need to expand them later after | |||
1212 | /// changing the formula. | |||
1213 | bool RigidFormula = false; | |||
1214 | ||||
1215 | /// This records the widest use type for any fixup using this | |||
1216 | /// LSRUse. FindUseWithSimilarFormula can't consider uses with different max | |||
1217 | /// fixup widths to be equivalent, because the narrower one may be relying on | |||
1218 | /// the implicit truncation to truncate away bogus bits. | |||
1219 | Type *WidestFixupType = nullptr; | |||
1220 | ||||
1221 | /// A list of ways to build a value that can satisfy this user. After the | |||
1222 | /// list is populated, one of these is selected heuristically and used to | |||
1223 | /// formulate a replacement for OperandValToReplace in UserInst. | |||
1224 | SmallVector<Formula, 12> Formulae; | |||
1225 | ||||
1226 | /// The set of register candidates used by all formulae in this LSRUse. | |||
1227 | SmallPtrSet<const SCEV *, 4> Regs; | |||
1228 | ||||
1229 | LSRUse(KindType K, MemAccessTy AT) : Kind(K), AccessTy(AT) {} | |||
1230 | ||||
1231 | LSRFixup &getNewFixup() { | |||
1232 | Fixups.push_back(LSRFixup()); | |||
1233 | return Fixups.back(); | |||
1234 | } | |||
1235 | ||||
1236 | void pushFixup(LSRFixup &f) { | |||
1237 | Fixups.push_back(f); | |||
1238 | if (f.Offset > MaxOffset) | |||
1239 | MaxOffset = f.Offset; | |||
1240 | if (f.Offset < MinOffset) | |||
1241 | MinOffset = f.Offset; | |||
1242 | } | |||
1243 | ||||
1244 | bool HasFormulaWithSameRegs(const Formula &F) const; | |||
1245 | float getNotSelectedProbability(const SCEV *Reg) const; | |||
1246 | bool InsertFormula(const Formula &F, const Loop &L); | |||
1247 | void DeleteFormula(Formula &F); | |||
1248 | void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses); | |||
1249 | ||||
1250 | void print(raw_ostream &OS) const; | |||
1251 | void dump() const; | |||
1252 | }; | |||
1253 | ||||
1254 | } // end anonymous namespace | |||
1255 | ||||
1256 | static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, | |||
1257 | LSRUse::KindType Kind, MemAccessTy AccessTy, | |||
1258 | GlobalValue *BaseGV, int64_t BaseOffset, | |||
1259 | bool HasBaseReg, int64_t Scale, | |||
1260 | Instruction *Fixup = nullptr); | |||
1261 | ||||
1262 | static unsigned getSetupCost(const SCEV *Reg, unsigned Depth) { | |||
1263 | if (isa<SCEVUnknown>(Reg) || isa<SCEVConstant>(Reg)) | |||
1264 | return 1; | |||
1265 | if (Depth == 0) | |||
1266 | return 0; | |||
1267 | if (const auto *S = dyn_cast<SCEVAddRecExpr>(Reg)) | |||
1268 | return getSetupCost(S->getStart(), Depth - 1); | |||
1269 | if (auto S = dyn_cast<SCEVIntegralCastExpr>(Reg)) | |||
1270 | return getSetupCost(S->getOperand(), Depth - 1); | |||
1271 | if (auto S = dyn_cast<SCEVNAryExpr>(Reg)) | |||
1272 | return std::accumulate(S->operands().begin(), S->operands().end(), 0, | |||
1273 | [&](unsigned i, const SCEV *Reg) { | |||
1274 | return i + getSetupCost(Reg, Depth - 1); | |||
1275 | }); | |||
1276 | if (auto S = dyn_cast<SCEVUDivExpr>(Reg)) | |||
1277 | return getSetupCost(S->getLHS(), Depth - 1) + | |||
1278 | getSetupCost(S->getRHS(), Depth - 1); | |||
1279 | return 0; | |||
1280 | } | |||
1281 | ||||
1282 | /// Tally up interesting quantities from the given register. | |||
1283 | void Cost::RateRegister(const Formula &F, const SCEV *Reg, | |||
1284 | SmallPtrSetImpl<const SCEV *> &Regs) { | |||
1285 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) { | |||
1286 | // If this is an addrec for another loop, it should be an invariant | |||
1287 | // with respect to L since L is the innermost loop (at least | |||
1288 | // for now LSR only handles innermost loops). | |||
1289 | if (AR->getLoop() != L) { | |||
1290 | // If the AddRec exists, consider it's register free and leave it alone. | |||
1291 | if (isExistingPhi(AR, *SE) && AMK != TTI::AMK_PostIndexed) | |||
1292 | return; | |||
1293 | ||||
1294 | // It is bad to allow LSR for current loop to add induction variables | |||
1295 | // for its sibling loops. | |||
1296 | if (!AR->getLoop()->contains(L)) { | |||
1297 | Lose(); | |||
1298 | return; | |||
1299 | } | |||
1300 | ||||
1301 | // Otherwise, it will be an invariant with respect to Loop L. | |||
1302 | ++C.NumRegs; | |||
1303 | return; | |||
1304 | } | |||
1305 | ||||
1306 | unsigned LoopCost = 1; | |||
1307 | if (TTI->isIndexedLoadLegal(TTI->MIM_PostInc, AR->getType()) || | |||
1308 | TTI->isIndexedStoreLegal(TTI->MIM_PostInc, AR->getType())) { | |||
1309 | ||||
1310 | // If the step size matches the base offset, we could use pre-indexed | |||
1311 | // addressing. | |||
1312 | if (AMK == TTI::AMK_PreIndexed) { | |||
1313 | if (auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE))) | |||
1314 | if (Step->getAPInt() == F.BaseOffset) | |||
1315 | LoopCost = 0; | |||
1316 | } else if (AMK == TTI::AMK_PostIndexed) { | |||
1317 | const SCEV *LoopStep = AR->getStepRecurrence(*SE); | |||
1318 | if (isa<SCEVConstant>(LoopStep)) { | |||
1319 | const SCEV *LoopStart = AR->getStart(); | |||
1320 | if (!isa<SCEVConstant>(LoopStart) && | |||
1321 | SE->isLoopInvariant(LoopStart, L)) | |||
1322 | LoopCost = 0; | |||
1323 | } | |||
1324 | } | |||
1325 | } | |||
1326 | C.AddRecCost += LoopCost; | |||
1327 | ||||
1328 | // Add the step value register, if it needs one. | |||
1329 | // TODO: The non-affine case isn't precisely modeled here. | |||
1330 | if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) { | |||
1331 | if (!Regs.count(AR->getOperand(1))) { | |||
1332 | RateRegister(F, AR->getOperand(1), Regs); | |||
1333 | if (isLoser()) | |||
1334 | return; | |||
1335 | } | |||
1336 | } | |||
1337 | } | |||
1338 | ++C.NumRegs; | |||
1339 | ||||
1340 | // Rough heuristic; favor registers which don't require extra setup | |||
1341 | // instructions in the preheader. | |||
1342 | C.SetupCost += getSetupCost(Reg, SetupCostDepthLimit); | |||
1343 | // Ensure we don't, even with the recusion limit, produce invalid costs. | |||
1344 | C.SetupCost = std::min<unsigned>(C.SetupCost, 1 << 16); | |||
1345 | ||||
1346 | C.NumIVMuls += isa<SCEVMulExpr>(Reg) && | |||
1347 | SE->hasComputableLoopEvolution(Reg, L); | |||
1348 | } | |||
1349 | ||||
1350 | /// Record this register in the set. If we haven't seen it before, rate | |||
1351 | /// it. Optional LoserRegs provides a way to declare any formula that refers to | |||
1352 | /// one of those regs an instant loser. | |||
1353 | void Cost::RatePrimaryRegister(const Formula &F, const SCEV *Reg, | |||
1354 | SmallPtrSetImpl<const SCEV *> &Regs, | |||
1355 | SmallPtrSetImpl<const SCEV *> *LoserRegs) { | |||
1356 | if (LoserRegs && LoserRegs->count(Reg)) { | |||
1357 | Lose(); | |||
1358 | return; | |||
1359 | } | |||
1360 | if (Regs.insert(Reg).second) { | |||
1361 | RateRegister(F, Reg, Regs); | |||
1362 | if (LoserRegs && isLoser()) | |||
1363 | LoserRegs->insert(Reg); | |||
1364 | } | |||
1365 | } | |||
1366 | ||||
1367 | void Cost::RateFormula(const Formula &F, | |||
1368 | SmallPtrSetImpl<const SCEV *> &Regs, | |||
1369 | const DenseSet<const SCEV *> &VisitedRegs, | |||
1370 | const LSRUse &LU, | |||
1371 | SmallPtrSetImpl<const SCEV *> *LoserRegs) { | |||
1372 | if (isLoser()) | |||
1373 | return; | |||
1374 | assert(F.isCanonical(*L) && "Cost is accurate only for canonical formula")(static_cast <bool> (F.isCanonical(*L) && "Cost is accurate only for canonical formula" ) ? void (0) : __assert_fail ("F.isCanonical(*L) && \"Cost is accurate only for canonical formula\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 1374, __extension__ __PRETTY_FUNCTION__)); | |||
1375 | // Tally up the registers. | |||
1376 | unsigned PrevAddRecCost = C.AddRecCost; | |||
1377 | unsigned PrevNumRegs = C.NumRegs; | |||
1378 | unsigned PrevNumBaseAdds = C.NumBaseAdds; | |||
1379 | if (const SCEV *ScaledReg = F.ScaledReg) { | |||
1380 | if (VisitedRegs.count(ScaledReg)) { | |||
1381 | Lose(); | |||
1382 | return; | |||
1383 | } | |||
1384 | RatePrimaryRegister(F, ScaledReg, Regs, LoserRegs); | |||
1385 | if (isLoser()) | |||
1386 | return; | |||
1387 | } | |||
1388 | for (const SCEV *BaseReg : F.BaseRegs) { | |||
1389 | if (VisitedRegs.count(BaseReg)) { | |||
1390 | Lose(); | |||
1391 | return; | |||
1392 | } | |||
1393 | RatePrimaryRegister(F, BaseReg, Regs, LoserRegs); | |||
1394 | if (isLoser()) | |||
1395 | return; | |||
1396 | } | |||
1397 | ||||
1398 | // Determine how many (unfolded) adds we'll need inside the loop. | |||
1399 | size_t NumBaseParts = F.getNumRegs(); | |||
1400 | if (NumBaseParts > 1) | |||
1401 | // Do not count the base and a possible second register if the target | |||
1402 | // allows to fold 2 registers. | |||
1403 | C.NumBaseAdds += | |||
1404 | NumBaseParts - (1 + (F.Scale && isAMCompletelyFolded(*TTI, LU, F))); | |||
1405 | C.NumBaseAdds += (F.UnfoldedOffset != 0); | |||
1406 | ||||
1407 | // Accumulate non-free scaling amounts. | |||
1408 | C.ScaleCost += *getScalingFactorCost(*TTI, LU, F, *L).getValue(); | |||
1409 | ||||
1410 | // Tally up the non-zero immediates. | |||
1411 | for (const LSRFixup &Fixup : LU.Fixups) { | |||
1412 | int64_t O = Fixup.Offset; | |||
1413 | int64_t Offset = (uint64_t)O + F.BaseOffset; | |||
1414 | if (F.BaseGV) | |||
1415 | C.ImmCost += 64; // Handle symbolic values conservatively. | |||
1416 | // TODO: This should probably be the pointer size. | |||
1417 | else if (Offset != 0) | |||
1418 | C.ImmCost += APInt(64, Offset, true).getSignificantBits(); | |||
1419 | ||||
1420 | // Check with target if this offset with this instruction is | |||
1421 | // specifically not supported. | |||
1422 | if (LU.Kind == LSRUse::Address && Offset != 0 && | |||
1423 | !isAMCompletelyFolded(*TTI, LSRUse::Address, LU.AccessTy, F.BaseGV, | |||
1424 | Offset, F.HasBaseReg, F.Scale, Fixup.UserInst)) | |||
1425 | C.NumBaseAdds++; | |||
1426 | } | |||
1427 | ||||
1428 | // If we don't count instruction cost exit here. | |||
1429 | if (!InsnsCost) { | |||
1430 | assert(isValid() && "invalid cost")(static_cast <bool> (isValid() && "invalid cost" ) ? void (0) : __assert_fail ("isValid() && \"invalid cost\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 1430, __extension__ __PRETTY_FUNCTION__)); | |||
1431 | return; | |||
1432 | } | |||
1433 | ||||
1434 | // Treat every new register that exceeds TTI.getNumberOfRegisters() - 1 as | |||
1435 | // additional instruction (at least fill). | |||
1436 | // TODO: Need distinguish register class? | |||
1437 | unsigned TTIRegNum = TTI->getNumberOfRegisters( | |||
1438 | TTI->getRegisterClassForType(false, F.getType())) - 1; | |||
1439 | if (C.NumRegs > TTIRegNum) { | |||
1440 | // Cost already exceeded TTIRegNum, then only newly added register can add | |||
1441 | // new instructions. | |||
1442 | if (PrevNumRegs > TTIRegNum) | |||
1443 | C.Insns += (C.NumRegs - PrevNumRegs); | |||
1444 | else | |||
1445 | C.Insns += (C.NumRegs - TTIRegNum); | |||
1446 | } | |||
1447 | ||||
1448 | // If ICmpZero formula ends with not 0, it could not be replaced by | |||
1449 | // just add or sub. We'll need to compare final result of AddRec. | |||
1450 | // That means we'll need an additional instruction. But if the target can | |||
1451 | // macro-fuse a compare with a branch, don't count this extra instruction. | |||
1452 | // For -10 + {0, +, 1}: | |||
1453 | // i = i + 1; | |||
1454 | // cmp i, 10 | |||
1455 | // | |||
1456 | // For {-10, +, 1}: | |||
1457 | // i = i + 1; | |||
1458 | if (LU.Kind == LSRUse::ICmpZero && !F.hasZeroEnd() && | |||
1459 | !TTI->canMacroFuseCmp()) | |||
1460 | C.Insns++; | |||
1461 | // Each new AddRec adds 1 instruction to calculation. | |||
1462 | C.Insns += (C.AddRecCost - PrevAddRecCost); | |||
1463 | ||||
1464 | // BaseAdds adds instructions for unfolded registers. | |||
1465 | if (LU.Kind != LSRUse::ICmpZero) | |||
1466 | C.Insns += C.NumBaseAdds - PrevNumBaseAdds; | |||
1467 | assert(isValid() && "invalid cost")(static_cast <bool> (isValid() && "invalid cost" ) ? void (0) : __assert_fail ("isValid() && \"invalid cost\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 1467, __extension__ __PRETTY_FUNCTION__)); | |||
1468 | } | |||
1469 | ||||
1470 | /// Set this cost to a losing value. | |||
1471 | void Cost::Lose() { | |||
1472 | C.Insns = std::numeric_limits<unsigned>::max(); | |||
1473 | C.NumRegs = std::numeric_limits<unsigned>::max(); | |||
1474 | C.AddRecCost = std::numeric_limits<unsigned>::max(); | |||
1475 | C.NumIVMuls = std::numeric_limits<unsigned>::max(); | |||
1476 | C.NumBaseAdds = std::numeric_limits<unsigned>::max(); | |||
1477 | C.ImmCost = std::numeric_limits<unsigned>::max(); | |||
1478 | C.SetupCost = std::numeric_limits<unsigned>::max(); | |||
1479 | C.ScaleCost = std::numeric_limits<unsigned>::max(); | |||
1480 | } | |||
1481 | ||||
1482 | /// Choose the lower cost. | |||
1483 | bool Cost::isLess(const Cost &Other) const { | |||
1484 | if (InsnsCost.getNumOccurrences() > 0 && InsnsCost && | |||
1485 | C.Insns != Other.C.Insns) | |||
1486 | return C.Insns < Other.C.Insns; | |||
1487 | return TTI->isLSRCostLess(C, Other.C); | |||
1488 | } | |||
1489 | ||||
1490 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) | |||
1491 | void Cost::print(raw_ostream &OS) const { | |||
1492 | if (InsnsCost) | |||
1493 | OS << C.Insns << " instruction" << (C.Insns == 1 ? " " : "s "); | |||
1494 | OS << C.NumRegs << " reg" << (C.NumRegs == 1 ? "" : "s"); | |||
1495 | if (C.AddRecCost != 0) | |||
1496 | OS << ", with addrec cost " << C.AddRecCost; | |||
1497 | if (C.NumIVMuls != 0) | |||
1498 | OS << ", plus " << C.NumIVMuls << " IV mul" | |||
1499 | << (C.NumIVMuls == 1 ? "" : "s"); | |||
1500 | if (C.NumBaseAdds != 0) | |||
1501 | OS << ", plus " << C.NumBaseAdds << " base add" | |||
1502 | << (C.NumBaseAdds == 1 ? "" : "s"); | |||
1503 | if (C.ScaleCost != 0) | |||
1504 | OS << ", plus " << C.ScaleCost << " scale cost"; | |||
1505 | if (C.ImmCost != 0) | |||
1506 | OS << ", plus " << C.ImmCost << " imm cost"; | |||
1507 | if (C.SetupCost != 0) | |||
1508 | OS << ", plus " << C.SetupCost << " setup cost"; | |||
1509 | } | |||
1510 | ||||
1511 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void Cost::dump() const { | |||
1512 | print(errs()); errs() << '\n'; | |||
1513 | } | |||
1514 | #endif | |||
1515 | ||||
1516 | /// Test whether this fixup always uses its value outside of the given loop. | |||
1517 | bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const { | |||
1518 | // PHI nodes use their value in their incoming blocks. | |||
1519 | if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) { | |||
1520 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) | |||
1521 | if (PN->getIncomingValue(i) == OperandValToReplace && | |||
1522 | L->contains(PN->getIncomingBlock(i))) | |||
1523 | return false; | |||
1524 | return true; | |||
1525 | } | |||
1526 | ||||
1527 | return !L->contains(UserInst); | |||
1528 | } | |||
1529 | ||||
1530 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) | |||
1531 | void LSRFixup::print(raw_ostream &OS) const { | |||
1532 | OS << "UserInst="; | |||
1533 | // Store is common and interesting enough to be worth special-casing. | |||
1534 | if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) { | |||
1535 | OS << "store "; | |||
1536 | Store->getOperand(0)->printAsOperand(OS, /*PrintType=*/false); | |||
1537 | } else if (UserInst->getType()->isVoidTy()) | |||
1538 | OS << UserInst->getOpcodeName(); | |||
1539 | else | |||
1540 | UserInst->printAsOperand(OS, /*PrintType=*/false); | |||
1541 | ||||
1542 | OS << ", OperandValToReplace="; | |||
1543 | OperandValToReplace->printAsOperand(OS, /*PrintType=*/false); | |||
1544 | ||||
1545 | for (const Loop *PIL : PostIncLoops) { | |||
1546 | OS << ", PostIncLoop="; | |||
1547 | PIL->getHeader()->printAsOperand(OS, /*PrintType=*/false); | |||
1548 | } | |||
1549 | ||||
1550 | if (Offset != 0) | |||
1551 | OS << ", Offset=" << Offset; | |||
1552 | } | |||
1553 | ||||
1554 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void LSRFixup::dump() const { | |||
1555 | print(errs()); errs() << '\n'; | |||
1556 | } | |||
1557 | #endif | |||
1558 | ||||
1559 | /// Test whether this use as a formula which has the same registers as the given | |||
1560 | /// formula. | |||
1561 | bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const { | |||
1562 | SmallVector<const SCEV *, 4> Key = F.BaseRegs; | |||
1563 | if (F.ScaledReg) Key.push_back(F.ScaledReg); | |||
1564 | // Unstable sort by host order ok, because this is only used for uniquifying. | |||
1565 | llvm::sort(Key); | |||
1566 | return Uniquifier.count(Key); | |||
1567 | } | |||
1568 | ||||
1569 | /// The function returns a probability of selecting formula without Reg. | |||
1570 | float LSRUse::getNotSelectedProbability(const SCEV *Reg) const { | |||
1571 | unsigned FNum = 0; | |||
1572 | for (const Formula &F : Formulae) | |||
1573 | if (F.referencesReg(Reg)) | |||
1574 | FNum++; | |||
1575 | return ((float)(Formulae.size() - FNum)) / Formulae.size(); | |||
1576 | } | |||
1577 | ||||
1578 | /// If the given formula has not yet been inserted, add it to the list, and | |||
1579 | /// return true. Return false otherwise. The formula must be in canonical form. | |||
1580 | bool LSRUse::InsertFormula(const Formula &F, const Loop &L) { | |||
1581 | assert(F.isCanonical(L) && "Invalid canonical representation")(static_cast <bool> (F.isCanonical(L) && "Invalid canonical representation" ) ? void (0) : __assert_fail ("F.isCanonical(L) && \"Invalid canonical representation\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 1581, __extension__ __PRETTY_FUNCTION__)); | |||
1582 | ||||
1583 | if (!Formulae.empty() && RigidFormula) | |||
1584 | return false; | |||
1585 | ||||
1586 | SmallVector<const SCEV *, 4> Key = F.BaseRegs; | |||
1587 | if (F.ScaledReg) Key.push_back(F.ScaledReg); | |||
1588 | // Unstable sort by host order ok, because this is only used for uniquifying. | |||
1589 | llvm::sort(Key); | |||
1590 | ||||
1591 | if (!Uniquifier.insert(Key).second) | |||
1592 | return false; | |||
1593 | ||||
1594 | // Using a register to hold the value of 0 is not profitable. | |||
1595 | assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&(static_cast <bool> ((!F.ScaledReg || !F.ScaledReg-> isZero()) && "Zero allocated in a scaled register!") ? void (0) : __assert_fail ("(!F.ScaledReg || !F.ScaledReg->isZero()) && \"Zero allocated in a scaled register!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 1596, __extension__ __PRETTY_FUNCTION__)) | |||
1596 | "Zero allocated in a scaled register!")(static_cast <bool> ((!F.ScaledReg || !F.ScaledReg-> isZero()) && "Zero allocated in a scaled register!") ? void (0) : __assert_fail ("(!F.ScaledReg || !F.ScaledReg->isZero()) && \"Zero allocated in a scaled register!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 1596, __extension__ __PRETTY_FUNCTION__)); | |||
1597 | #ifndef NDEBUG | |||
1598 | for (const SCEV *BaseReg : F.BaseRegs) | |||
1599 | assert(!BaseReg->isZero() && "Zero allocated in a base register!")(static_cast <bool> (!BaseReg->isZero() && "Zero allocated in a base register!" ) ? void (0) : __assert_fail ("!BaseReg->isZero() && \"Zero allocated in a base register!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 1599, __extension__ __PRETTY_FUNCTION__)); | |||
1600 | #endif | |||
1601 | ||||
1602 | // Add the formula to the list. | |||
1603 | Formulae.push_back(F); | |||
1604 | ||||
1605 | // Record registers now being used by this use. | |||
1606 | Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end()); | |||
1607 | if (F.ScaledReg) | |||
1608 | Regs.insert(F.ScaledReg); | |||
1609 | ||||
1610 | return true; | |||
1611 | } | |||
1612 | ||||
1613 | /// Remove the given formula from this use's list. | |||
1614 | void LSRUse::DeleteFormula(Formula &F) { | |||
1615 | if (&F != &Formulae.back()) | |||
1616 | std::swap(F, Formulae.back()); | |||
1617 | Formulae.pop_back(); | |||
1618 | } | |||
1619 | ||||
1620 | /// Recompute the Regs field, and update RegUses. | |||
1621 | void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) { | |||
1622 | // Now that we've filtered out some formulae, recompute the Regs set. | |||
1623 | SmallPtrSet<const SCEV *, 4> OldRegs = std::move(Regs); | |||
1624 | Regs.clear(); | |||
1625 | for (const Formula &F : Formulae) { | |||
1626 | if (F.ScaledReg) Regs.insert(F.ScaledReg); | |||
1627 | Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end()); | |||
1628 | } | |||
1629 | ||||
1630 | // Update the RegTracker. | |||
1631 | for (const SCEV *S : OldRegs) | |||
1632 | if (!Regs.count(S)) | |||
1633 | RegUses.dropRegister(S, LUIdx); | |||
1634 | } | |||
1635 | ||||
1636 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) | |||
1637 | void LSRUse::print(raw_ostream &OS) const { | |||
1638 | OS << "LSR Use: Kind="; | |||
1639 | switch (Kind) { | |||
1640 | case Basic: OS << "Basic"; break; | |||
1641 | case Special: OS << "Special"; break; | |||
1642 | case ICmpZero: OS << "ICmpZero"; break; | |||
1643 | case Address: | |||
1644 | OS << "Address of "; | |||
1645 | if (AccessTy.MemTy->isPointerTy()) | |||
1646 | OS << "pointer"; // the full pointer type could be really verbose | |||
1647 | else { | |||
1648 | OS << *AccessTy.MemTy; | |||
1649 | } | |||
1650 | ||||
1651 | OS << " in addrspace(" << AccessTy.AddrSpace << ')'; | |||
1652 | } | |||
1653 | ||||
1654 | OS << ", Offsets={"; | |||
1655 | bool NeedComma = false; | |||
1656 | for (const LSRFixup &Fixup : Fixups) { | |||
1657 | if (NeedComma) OS << ','; | |||
1658 | OS << Fixup.Offset; | |||
1659 | NeedComma = true; | |||
1660 | } | |||
1661 | OS << '}'; | |||
1662 | ||||
1663 | if (AllFixupsOutsideLoop) | |||
1664 | OS << ", all-fixups-outside-loop"; | |||
1665 | ||||
1666 | if (WidestFixupType) | |||
1667 | OS << ", widest fixup type: " << *WidestFixupType; | |||
1668 | } | |||
1669 | ||||
1670 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void LSRUse::dump() const { | |||
1671 | print(errs()); errs() << '\n'; | |||
1672 | } | |||
1673 | #endif | |||
1674 | ||||
1675 | static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, | |||
1676 | LSRUse::KindType Kind, MemAccessTy AccessTy, | |||
1677 | GlobalValue *BaseGV, int64_t BaseOffset, | |||
1678 | bool HasBaseReg, int64_t Scale, | |||
1679 | Instruction *Fixup/*= nullptr*/) { | |||
1680 | switch (Kind) { | |||
1681 | case LSRUse::Address: | |||
1682 | return TTI.isLegalAddressingMode(AccessTy.MemTy, BaseGV, BaseOffset, | |||
1683 | HasBaseReg, Scale, AccessTy.AddrSpace, Fixup); | |||
1684 | ||||
1685 | case LSRUse::ICmpZero: | |||
1686 | // There's not even a target hook for querying whether it would be legal to | |||
1687 | // fold a GV into an ICmp. | |||
1688 | if (BaseGV) | |||
1689 | return false; | |||
1690 | ||||
1691 | // ICmp only has two operands; don't allow more than two non-trivial parts. | |||
1692 | if (Scale != 0 && HasBaseReg && BaseOffset != 0) | |||
1693 | return false; | |||
1694 | ||||
1695 | // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by | |||
1696 | // putting the scaled register in the other operand of the icmp. | |||
1697 | if (Scale != 0 && Scale != -1) | |||
1698 | return false; | |||
1699 | ||||
1700 | // If we have low-level target information, ask the target if it can fold an | |||
1701 | // integer immediate on an icmp. | |||
1702 | if (BaseOffset != 0) { | |||
1703 | // We have one of: | |||
1704 | // ICmpZero BaseReg + BaseOffset => ICmp BaseReg, -BaseOffset | |||
1705 | // ICmpZero -1*ScaleReg + BaseOffset => ICmp ScaleReg, BaseOffset | |||
1706 | // Offs is the ICmp immediate. | |||
1707 | if (Scale == 0) | |||
1708 | // The cast does the right thing with | |||
1709 | // std::numeric_limits<int64_t>::min(). | |||
1710 | BaseOffset = -(uint64_t)BaseOffset; | |||
1711 | return TTI.isLegalICmpImmediate(BaseOffset); | |||
1712 | } | |||
1713 | ||||
1714 | // ICmpZero BaseReg + -1*ScaleReg => ICmp BaseReg, ScaleReg | |||
1715 | return true; | |||
1716 | ||||
1717 | case LSRUse::Basic: | |||
1718 | // Only handle single-register values. | |||
1719 | return !BaseGV && Scale == 0 && BaseOffset == 0; | |||
1720 | ||||
1721 | case LSRUse::Special: | |||
1722 | // Special case Basic to handle -1 scales. | |||
1723 | return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset == 0; | |||
1724 | } | |||
1725 | ||||
1726 | llvm_unreachable("Invalid LSRUse Kind!")::llvm::llvm_unreachable_internal("Invalid LSRUse Kind!", "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp" , 1726); | |||
1727 | } | |||
1728 | ||||
1729 | static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, | |||
1730 | int64_t MinOffset, int64_t MaxOffset, | |||
1731 | LSRUse::KindType Kind, MemAccessTy AccessTy, | |||
1732 | GlobalValue *BaseGV, int64_t BaseOffset, | |||
1733 | bool HasBaseReg, int64_t Scale) { | |||
1734 | // Check for overflow. | |||
1735 | if (((int64_t)((uint64_t)BaseOffset + MinOffset) > BaseOffset) != | |||
1736 | (MinOffset > 0)) | |||
1737 | return false; | |||
1738 | MinOffset = (uint64_t)BaseOffset + MinOffset; | |||
1739 | if (((int64_t)((uint64_t)BaseOffset + MaxOffset) > BaseOffset) != | |||
1740 | (MaxOffset > 0)) | |||
1741 | return false; | |||
1742 | MaxOffset = (uint64_t)BaseOffset + MaxOffset; | |||
1743 | ||||
1744 | return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MinOffset, | |||
1745 | HasBaseReg, Scale) && | |||
1746 | isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MaxOffset, | |||
1747 | HasBaseReg, Scale); | |||
1748 | } | |||
1749 | ||||
1750 | static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, | |||
1751 | int64_t MinOffset, int64_t MaxOffset, | |||
1752 | LSRUse::KindType Kind, MemAccessTy AccessTy, | |||
1753 | const Formula &F, const Loop &L) { | |||
1754 | // For the purpose of isAMCompletelyFolded either having a canonical formula | |||
1755 | // or a scale not equal to zero is correct. | |||
1756 | // Problems may arise from non canonical formulae having a scale == 0. | |||
1757 | // Strictly speaking it would best to just rely on canonical formulae. | |||
1758 | // However, when we generate the scaled formulae, we first check that the | |||
1759 | // scaling factor is profitable before computing the actual ScaledReg for | |||
1760 | // compile time sake. | |||
1761 | assert((F.isCanonical(L) || F.Scale != 0))(static_cast <bool> ((F.isCanonical(L) || F.Scale != 0) ) ? void (0) : __assert_fail ("(F.isCanonical(L) || F.Scale != 0)" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 1761, __extension__ __PRETTY_FUNCTION__)); | |||
1762 | return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, | |||
1763 | F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale); | |||
1764 | } | |||
1765 | ||||
1766 | /// Test whether we know how to expand the current formula. | |||
1767 | static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset, | |||
1768 | int64_t MaxOffset, LSRUse::KindType Kind, | |||
1769 | MemAccessTy AccessTy, GlobalValue *BaseGV, | |||
1770 | int64_t BaseOffset, bool HasBaseReg, int64_t Scale) { | |||
1771 | // We know how to expand completely foldable formulae. | |||
1772 | return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV, | |||
1773 | BaseOffset, HasBaseReg, Scale) || | |||
1774 | // Or formulae that use a base register produced by a sum of base | |||
1775 | // registers. | |||
1776 | (Scale == 1 && | |||
1777 | isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, | |||
1778 | BaseGV, BaseOffset, true, 0)); | |||
1779 | } | |||
1780 | ||||
1781 | static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset, | |||
1782 | int64_t MaxOffset, LSRUse::KindType Kind, | |||
1783 | MemAccessTy AccessTy, const Formula &F) { | |||
1784 | return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV, | |||
1785 | F.BaseOffset, F.HasBaseReg, F.Scale); | |||
1786 | } | |||
1787 | ||||
1788 | static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, | |||
1789 | const LSRUse &LU, const Formula &F) { | |||
1790 | // Target may want to look at the user instructions. | |||
1791 | if (LU.Kind == LSRUse::Address && TTI.LSRWithInstrQueries()) { | |||
1792 | for (const LSRFixup &Fixup : LU.Fixups) | |||
1793 | if (!isAMCompletelyFolded(TTI, LSRUse::Address, LU.AccessTy, F.BaseGV, | |||
1794 | (F.BaseOffset + Fixup.Offset), F.HasBaseReg, | |||
1795 | F.Scale, Fixup.UserInst)) | |||
1796 | return false; | |||
1797 | return true; | |||
1798 | } | |||
1799 | ||||
1800 | return isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, | |||
1801 | LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg, | |||
1802 | F.Scale); | |||
1803 | } | |||
1804 | ||||
1805 | static InstructionCost getScalingFactorCost(const TargetTransformInfo &TTI, | |||
1806 | const LSRUse &LU, const Formula &F, | |||
1807 | const Loop &L) { | |||
1808 | if (!F.Scale) | |||
1809 | return 0; | |||
1810 | ||||
1811 | // If the use is not completely folded in that instruction, we will have to | |||
1812 | // pay an extra cost only for scale != 1. | |||
1813 | if (!isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, | |||
1814 | LU.AccessTy, F, L)) | |||
1815 | return F.Scale != 1; | |||
1816 | ||||
1817 | switch (LU.Kind) { | |||
1818 | case LSRUse::Address: { | |||
1819 | // Check the scaling factor cost with both the min and max offsets. | |||
1820 | InstructionCost ScaleCostMinOffset = TTI.getScalingFactorCost( | |||
1821 | LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MinOffset, F.HasBaseReg, | |||
1822 | F.Scale, LU.AccessTy.AddrSpace); | |||
1823 | InstructionCost ScaleCostMaxOffset = TTI.getScalingFactorCost( | |||
1824 | LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MaxOffset, F.HasBaseReg, | |||
1825 | F.Scale, LU.AccessTy.AddrSpace); | |||
1826 | ||||
1827 | assert(ScaleCostMinOffset.isValid() && ScaleCostMaxOffset.isValid() &&(static_cast <bool> (ScaleCostMinOffset.isValid() && ScaleCostMaxOffset.isValid() && "Legal addressing mode has an illegal cost!" ) ? void (0) : __assert_fail ("ScaleCostMinOffset.isValid() && ScaleCostMaxOffset.isValid() && \"Legal addressing mode has an illegal cost!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 1828, __extension__ __PRETTY_FUNCTION__)) | |||
1828 | "Legal addressing mode has an illegal cost!")(static_cast <bool> (ScaleCostMinOffset.isValid() && ScaleCostMaxOffset.isValid() && "Legal addressing mode has an illegal cost!" ) ? void (0) : __assert_fail ("ScaleCostMinOffset.isValid() && ScaleCostMaxOffset.isValid() && \"Legal addressing mode has an illegal cost!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 1828, __extension__ __PRETTY_FUNCTION__)); | |||
1829 | return std::max(ScaleCostMinOffset, ScaleCostMaxOffset); | |||
1830 | } | |||
1831 | case LSRUse::ICmpZero: | |||
1832 | case LSRUse::Basic: | |||
1833 | case LSRUse::Special: | |||
1834 | // The use is completely folded, i.e., everything is folded into the | |||
1835 | // instruction. | |||
1836 | return 0; | |||
1837 | } | |||
1838 | ||||
1839 | llvm_unreachable("Invalid LSRUse Kind!")::llvm::llvm_unreachable_internal("Invalid LSRUse Kind!", "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp" , 1839); | |||
1840 | } | |||
1841 | ||||
1842 | static bool isAlwaysFoldable(const TargetTransformInfo &TTI, | |||
1843 | LSRUse::KindType Kind, MemAccessTy AccessTy, | |||
1844 | GlobalValue *BaseGV, int64_t BaseOffset, | |||
1845 | bool HasBaseReg) { | |||
1846 | // Fast-path: zero is always foldable. | |||
1847 | if (BaseOffset == 0 && !BaseGV) return true; | |||
1848 | ||||
1849 | // Conservatively, create an address with an immediate and a | |||
1850 | // base and a scale. | |||
1851 | int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1; | |||
1852 | ||||
1853 | // Canonicalize a scale of 1 to a base register if the formula doesn't | |||
1854 | // already have a base register. | |||
1855 | if (!HasBaseReg && Scale == 1) { | |||
1856 | Scale = 0; | |||
1857 | HasBaseReg = true; | |||
1858 | } | |||
1859 | ||||
1860 | return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset, | |||
1861 | HasBaseReg, Scale); | |||
1862 | } | |||
1863 | ||||
1864 | static bool isAlwaysFoldable(const TargetTransformInfo &TTI, | |||
1865 | ScalarEvolution &SE, int64_t MinOffset, | |||
1866 | int64_t MaxOffset, LSRUse::KindType Kind, | |||
1867 | MemAccessTy AccessTy, const SCEV *S, | |||
1868 | bool HasBaseReg) { | |||
1869 | // Fast-path: zero is always foldable. | |||
1870 | if (S->isZero()) return true; | |||
1871 | ||||
1872 | // Conservatively, create an address with an immediate and a | |||
1873 | // base and a scale. | |||
1874 | int64_t BaseOffset = ExtractImmediate(S, SE); | |||
1875 | GlobalValue *BaseGV = ExtractSymbol(S, SE); | |||
1876 | ||||
1877 | // If there's anything else involved, it's not foldable. | |||
1878 | if (!S->isZero()) return false; | |||
1879 | ||||
1880 | // Fast-path: zero is always foldable. | |||
1881 | if (BaseOffset == 0 && !BaseGV) return true; | |||
1882 | ||||
1883 | // Conservatively, create an address with an immediate and a | |||
1884 | // base and a scale. | |||
1885 | int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1; | |||
1886 | ||||
1887 | return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV, | |||
1888 | BaseOffset, HasBaseReg, Scale); | |||
1889 | } | |||
1890 | ||||
1891 | namespace { | |||
1892 | ||||
1893 | /// An individual increment in a Chain of IV increments. Relate an IV user to | |||
1894 | /// an expression that computes the IV it uses from the IV used by the previous | |||
1895 | /// link in the Chain. | |||
1896 | /// | |||
1897 | /// For the head of a chain, IncExpr holds the absolute SCEV expression for the | |||
1898 | /// original IVOperand. The head of the chain's IVOperand is only valid during | |||
1899 | /// chain collection, before LSR replaces IV users. During chain generation, | |||
1900 | /// IncExpr can be used to find the new IVOperand that computes the same | |||
1901 | /// expression. | |||
1902 | struct IVInc { | |||
1903 | Instruction *UserInst; | |||
1904 | Value* IVOperand; | |||
1905 | const SCEV *IncExpr; | |||
1906 | ||||
1907 | IVInc(Instruction *U, Value *O, const SCEV *E) | |||
1908 | : UserInst(U), IVOperand(O), IncExpr(E) {} | |||
1909 | }; | |||
1910 | ||||
1911 | // The list of IV increments in program order. We typically add the head of a | |||
1912 | // chain without finding subsequent links. | |||
1913 | struct IVChain { | |||
1914 | SmallVector<IVInc, 1> Incs; | |||
1915 | const SCEV *ExprBase = nullptr; | |||
1916 | ||||
1917 | IVChain() = default; | |||
1918 | IVChain(const IVInc &Head, const SCEV *Base) | |||
1919 | : Incs(1, Head), ExprBase(Base) {} | |||
1920 | ||||
1921 | using const_iterator = SmallVectorImpl<IVInc>::const_iterator; | |||
1922 | ||||
1923 | // Return the first increment in the chain. | |||
1924 | const_iterator begin() const { | |||
1925 | assert(!Incs.empty())(static_cast <bool> (!Incs.empty()) ? void (0) : __assert_fail ("!Incs.empty()", "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp" , 1925, __extension__ __PRETTY_FUNCTION__)); | |||
1926 | return std::next(Incs.begin()); | |||
1927 | } | |||
1928 | const_iterator end() const { | |||
1929 | return Incs.end(); | |||
1930 | } | |||
1931 | ||||
1932 | // Returns true if this chain contains any increments. | |||
1933 | bool hasIncs() const { return Incs.size() >= 2; } | |||
1934 | ||||
1935 | // Add an IVInc to the end of this chain. | |||
1936 | void add(const IVInc &X) { Incs.push_back(X); } | |||
1937 | ||||
1938 | // Returns the last UserInst in the chain. | |||
1939 | Instruction *tailUserInst() const { return Incs.back().UserInst; } | |||
1940 | ||||
1941 | // Returns true if IncExpr can be profitably added to this chain. | |||
1942 | bool isProfitableIncrement(const SCEV *OperExpr, | |||
1943 | const SCEV *IncExpr, | |||
1944 | ScalarEvolution&); | |||
1945 | }; | |||
1946 | ||||
1947 | /// Helper for CollectChains to track multiple IV increment uses. Distinguish | |||
1948 | /// between FarUsers that definitely cross IV increments and NearUsers that may | |||
1949 | /// be used between IV increments. | |||
1950 | struct ChainUsers { | |||
1951 | SmallPtrSet<Instruction*, 4> FarUsers; | |||
1952 | SmallPtrSet<Instruction*, 4> NearUsers; | |||
1953 | }; | |||
1954 | ||||
1955 | /// This class holds state for the main loop strength reduction logic. | |||
1956 | class LSRInstance { | |||
1957 | IVUsers &IU; | |||
1958 | ScalarEvolution &SE; | |||
1959 | DominatorTree &DT; | |||
1960 | LoopInfo &LI; | |||
1961 | AssumptionCache &AC; | |||
1962 | TargetLibraryInfo &TLI; | |||
1963 | const TargetTransformInfo &TTI; | |||
1964 | Loop *const L; | |||
1965 | MemorySSAUpdater *MSSAU; | |||
1966 | TTI::AddressingModeKind AMK; | |||
1967 | mutable SCEVExpander Rewriter; | |||
1968 | bool Changed = false; | |||
1969 | ||||
1970 | /// This is the insert position that the current loop's induction variable | |||
1971 | /// increment should be placed. In simple loops, this is the latch block's | |||
1972 | /// terminator. But in more complicated cases, this is a position which will | |||
1973 | /// dominate all the in-loop post-increment users. | |||
1974 | Instruction *IVIncInsertPos = nullptr; | |||
1975 | ||||
1976 | /// Interesting factors between use strides. | |||
1977 | /// | |||
1978 | /// We explicitly use a SetVector which contains a SmallSet, instead of the | |||
1979 | /// default, a SmallDenseSet, because we need to use the full range of | |||
1980 | /// int64_ts, and there's currently no good way of doing that with | |||
1981 | /// SmallDenseSet. | |||
1982 | SetVector<int64_t, SmallVector<int64_t, 8>, SmallSet<int64_t, 8>> Factors; | |||
1983 | ||||
1984 | /// The cost of the current SCEV, the best solution by LSR will be dropped if | |||
1985 | /// the solution is not profitable. | |||
1986 | Cost BaselineCost; | |||
1987 | ||||
1988 | /// Interesting use types, to facilitate truncation reuse. | |||
1989 | SmallSetVector<Type *, 4> Types; | |||
1990 | ||||
1991 | /// The list of interesting uses. | |||
1992 | mutable SmallVector<LSRUse, 16> Uses; | |||
1993 | ||||
1994 | /// Track which uses use which register candidates. | |||
1995 | RegUseTracker RegUses; | |||
1996 | ||||
1997 | // Limit the number of chains to avoid quadratic behavior. We don't expect to | |||
1998 | // have more than a few IV increment chains in a loop. Missing a Chain falls | |||
1999 | // back to normal LSR behavior for those uses. | |||
2000 | static const unsigned MaxChains = 8; | |||
2001 | ||||
2002 | /// IV users can form a chain of IV increments. | |||
2003 | SmallVector<IVChain, MaxChains> IVChainVec; | |||
2004 | ||||
2005 | /// IV users that belong to profitable IVChains. | |||
2006 | SmallPtrSet<Use*, MaxChains> IVIncSet; | |||
2007 | ||||
2008 | /// Induction variables that were generated and inserted by the SCEV Expander. | |||
2009 | SmallVector<llvm::WeakVH, 2> ScalarEvolutionIVs; | |||
2010 | ||||
2011 | void OptimizeShadowIV(); | |||
2012 | bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse); | |||
2013 | ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse); | |||
2014 | void OptimizeLoopTermCond(); | |||
2015 | ||||
2016 | void ChainInstruction(Instruction *UserInst, Instruction *IVOper, | |||
2017 | SmallVectorImpl<ChainUsers> &ChainUsersVec); | |||
2018 | void FinalizeChain(IVChain &Chain); | |||
2019 | void CollectChains(); | |||
2020 | void GenerateIVChain(const IVChain &Chain, | |||
2021 | SmallVectorImpl<WeakTrackingVH> &DeadInsts); | |||
2022 | ||||
2023 | void CollectInterestingTypesAndFactors(); | |||
2024 | void CollectFixupsAndInitialFormulae(); | |||
2025 | ||||
2026 | // Support for sharing of LSRUses between LSRFixups. | |||
2027 | using UseMapTy = DenseMap<LSRUse::SCEVUseKindPair, size_t>; | |||
2028 | UseMapTy UseMap; | |||
2029 | ||||
2030 | bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg, | |||
2031 | LSRUse::KindType Kind, MemAccessTy AccessTy); | |||
2032 | ||||
2033 | std::pair<size_t, int64_t> getUse(const SCEV *&Expr, LSRUse::KindType Kind, | |||
2034 | MemAccessTy AccessTy); | |||
2035 | ||||
2036 | void DeleteUse(LSRUse &LU, size_t LUIdx); | |||
2037 | ||||
2038 | LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU); | |||
2039 | ||||
2040 | void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx); | |||
2041 | void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx); | |||
2042 | void CountRegisters(const Formula &F, size_t LUIdx); | |||
2043 | bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F); | |||
2044 | ||||
2045 | void CollectLoopInvariantFixupsAndFormulae(); | |||
2046 | ||||
2047 | void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base, | |||
2048 | unsigned Depth = 0); | |||
2049 | ||||
2050 | void GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx, | |||
2051 | const Formula &Base, unsigned Depth, | |||
2052 | size_t Idx, bool IsScaledReg = false); | |||
2053 | void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base); | |||
2054 | void GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx, | |||
2055 | const Formula &Base, size_t Idx, | |||
2056 | bool IsScaledReg = false); | |||
2057 | void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base); | |||
2058 | void GenerateConstantOffsetsImpl(LSRUse &LU, unsigned LUIdx, | |||
2059 | const Formula &Base, | |||
2060 | const SmallVectorImpl<int64_t> &Worklist, | |||
2061 | size_t Idx, bool IsScaledReg = false); | |||
2062 | void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base); | |||
2063 | void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base); | |||
2064 | void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base); | |||
2065 | void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base); | |||
2066 | void GenerateCrossUseConstantOffsets(); | |||
2067 | void GenerateAllReuseFormulae(); | |||
2068 | ||||
2069 | void FilterOutUndesirableDedicatedRegisters(); | |||
2070 | ||||
2071 | size_t EstimateSearchSpaceComplexity() const; | |||
2072 | void NarrowSearchSpaceByDetectingSupersets(); | |||
2073 | void NarrowSearchSpaceByCollapsingUnrolledCode(); | |||
2074 | void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(); | |||
2075 | void NarrowSearchSpaceByFilterFormulaWithSameScaledReg(); | |||
2076 | void NarrowSearchSpaceByFilterPostInc(); | |||
2077 | void NarrowSearchSpaceByDeletingCostlyFormulas(); | |||
2078 | void NarrowSearchSpaceByPickingWinnerRegs(); | |||
2079 | void NarrowSearchSpaceUsingHeuristics(); | |||
2080 | ||||
2081 | void SolveRecurse(SmallVectorImpl<const Formula *> &Solution, | |||
2082 | Cost &SolutionCost, | |||
2083 | SmallVectorImpl<const Formula *> &Workspace, | |||
2084 | const Cost &CurCost, | |||
2085 | const SmallPtrSet<const SCEV *, 16> &CurRegs, | |||
2086 | DenseSet<const SCEV *> &VisitedRegs) const; | |||
2087 | void Solve(SmallVectorImpl<const Formula *> &Solution) const; | |||
2088 | ||||
2089 | BasicBlock::iterator | |||
2090 | HoistInsertPosition(BasicBlock::iterator IP, | |||
2091 | const SmallVectorImpl<Instruction *> &Inputs) const; | |||
2092 | BasicBlock::iterator AdjustInsertPositionForExpand(BasicBlock::iterator IP, | |||
2093 | const LSRFixup &LF, | |||
2094 | const LSRUse &LU) const; | |||
2095 | ||||
2096 | Value *Expand(const LSRUse &LU, const LSRFixup &LF, const Formula &F, | |||
2097 | BasicBlock::iterator IP, | |||
2098 | SmallVectorImpl<WeakTrackingVH> &DeadInsts) const; | |||
2099 | void RewriteForPHI(PHINode *PN, const LSRUse &LU, const LSRFixup &LF, | |||
2100 | const Formula &F, | |||
2101 | SmallVectorImpl<WeakTrackingVH> &DeadInsts) const; | |||
2102 | void Rewrite(const LSRUse &LU, const LSRFixup &LF, const Formula &F, | |||
2103 | SmallVectorImpl<WeakTrackingVH> &DeadInsts) const; | |||
2104 | void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution); | |||
2105 | ||||
2106 | public: | |||
2107 | LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE, DominatorTree &DT, | |||
2108 | LoopInfo &LI, const TargetTransformInfo &TTI, AssumptionCache &AC, | |||
2109 | TargetLibraryInfo &TLI, MemorySSAUpdater *MSSAU); | |||
2110 | ||||
2111 | bool getChanged() const { return Changed; } | |||
2112 | const SmallVectorImpl<WeakVH> &getScalarEvolutionIVs() const { | |||
2113 | return ScalarEvolutionIVs; | |||
2114 | } | |||
2115 | ||||
2116 | void print_factors_and_types(raw_ostream &OS) const; | |||
2117 | void print_fixups(raw_ostream &OS) const; | |||
2118 | void print_uses(raw_ostream &OS) const; | |||
2119 | void print(raw_ostream &OS) const; | |||
2120 | void dump() const; | |||
2121 | }; | |||
2122 | ||||
2123 | } // end anonymous namespace | |||
2124 | ||||
2125 | /// If IV is used in a int-to-float cast inside the loop then try to eliminate | |||
2126 | /// the cast operation. | |||
2127 | void LSRInstance::OptimizeShadowIV() { | |||
2128 | const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L); | |||
2129 | if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) | |||
2130 | return; | |||
2131 | ||||
2132 | for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); | |||
2133 | UI != E; /* empty */) { | |||
2134 | IVUsers::const_iterator CandidateUI = UI; | |||
2135 | ++UI; | |||
2136 | Instruction *ShadowUse = CandidateUI->getUser(); | |||
2137 | Type *DestTy = nullptr; | |||
2138 | bool IsSigned = false; | |||
2139 | ||||
2140 | /* If shadow use is a int->float cast then insert a second IV | |||
2141 | to eliminate this cast. | |||
2142 | ||||
2143 | for (unsigned i = 0; i < n; ++i) | |||
2144 | foo((double)i); | |||
2145 | ||||
2146 | is transformed into | |||
2147 | ||||
2148 | double d = 0.0; | |||
2149 | for (unsigned i = 0; i < n; ++i, ++d) | |||
2150 | foo(d); | |||
2151 | */ | |||
2152 | if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) { | |||
2153 | IsSigned = false; | |||
2154 | DestTy = UCast->getDestTy(); | |||
2155 | } | |||
2156 | else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) { | |||
2157 | IsSigned = true; | |||
2158 | DestTy = SCast->getDestTy(); | |||
2159 | } | |||
2160 | if (!DestTy) continue; | |||
2161 | ||||
2162 | // If target does not support DestTy natively then do not apply | |||
2163 | // this transformation. | |||
2164 | if (!TTI.isTypeLegal(DestTy)) continue; | |||
2165 | ||||
2166 | PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0)); | |||
2167 | if (!PH) continue; | |||
2168 | if (PH->getNumIncomingValues() != 2) continue; | |||
2169 | ||||
2170 | // If the calculation in integers overflows, the result in FP type will | |||
2171 | // differ. So we only can do this transformation if we are guaranteed to not | |||
2172 | // deal with overflowing values | |||
2173 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PH)); | |||
2174 | if (!AR) continue; | |||
2175 | if (IsSigned && !AR->hasNoSignedWrap()) continue; | |||
2176 | if (!IsSigned && !AR->hasNoUnsignedWrap()) continue; | |||
2177 | ||||
2178 | Type *SrcTy = PH->getType(); | |||
2179 | int Mantissa = DestTy->getFPMantissaWidth(); | |||
2180 | if (Mantissa == -1) continue; | |||
2181 | if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa) | |||
2182 | continue; | |||
2183 | ||||
2184 | unsigned Entry, Latch; | |||
2185 | if (PH->getIncomingBlock(0) == L->getLoopPreheader()) { | |||
2186 | Entry = 0; | |||
2187 | Latch = 1; | |||
2188 | } else { | |||
2189 | Entry = 1; | |||
2190 | Latch = 0; | |||
2191 | } | |||
2192 | ||||
2193 | ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry)); | |||
2194 | if (!Init) continue; | |||
2195 | Constant *NewInit = ConstantFP::get(DestTy, IsSigned ? | |||
2196 | (double)Init->getSExtValue() : | |||
2197 | (double)Init->getZExtValue()); | |||
2198 | ||||
2199 | BinaryOperator *Incr = | |||
2200 | dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch)); | |||
2201 | if (!Incr) continue; | |||
2202 | if (Incr->getOpcode() != Instruction::Add | |||
2203 | && Incr->getOpcode() != Instruction::Sub) | |||
2204 | continue; | |||
2205 | ||||
2206 | /* Initialize new IV, double d = 0.0 in above example. */ | |||
2207 | ConstantInt *C = nullptr; | |||
2208 | if (Incr->getOperand(0) == PH) | |||
2209 | C = dyn_cast<ConstantInt>(Incr->getOperand(1)); | |||
2210 | else if (Incr->getOperand(1) == PH) | |||
2211 | C = dyn_cast<ConstantInt>(Incr->getOperand(0)); | |||
2212 | else | |||
2213 | continue; | |||
2214 | ||||
2215 | if (!C) continue; | |||
2216 | ||||
2217 | // Ignore negative constants, as the code below doesn't handle them | |||
2218 | // correctly. TODO: Remove this restriction. | |||
2219 | if (!C->getValue().isStrictlyPositive()) continue; | |||
2220 | ||||
2221 | /* Add new PHINode. */ | |||
2222 | PHINode *NewPH = PHINode::Create(DestTy, 2, "IV.S.", PH); | |||
2223 | ||||
2224 | /* create new increment. '++d' in above example. */ | |||
2225 | Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue()); | |||
2226 | BinaryOperator *NewIncr = | |||
2227 | BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ? | |||
2228 | Instruction::FAdd : Instruction::FSub, | |||
2229 | NewPH, CFP, "IV.S.next.", Incr); | |||
2230 | ||||
2231 | NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry)); | |||
2232 | NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch)); | |||
2233 | ||||
2234 | /* Remove cast operation */ | |||
2235 | ShadowUse->replaceAllUsesWith(NewPH); | |||
2236 | ShadowUse->eraseFromParent(); | |||
2237 | Changed = true; | |||
2238 | break; | |||
2239 | } | |||
2240 | } | |||
2241 | ||||
2242 | /// If Cond has an operand that is an expression of an IV, set the IV user and | |||
2243 | /// stride information and return true, otherwise return false. | |||
2244 | bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) { | |||
2245 | for (IVStrideUse &U : IU) | |||
2246 | if (U.getUser() == Cond) { | |||
2247 | // NOTE: we could handle setcc instructions with multiple uses here, but | |||
2248 | // InstCombine does it as well for simple uses, it's not clear that it | |||
2249 | // occurs enough in real life to handle. | |||
2250 | CondUse = &U; | |||
2251 | return true; | |||
2252 | } | |||
2253 | return false; | |||
2254 | } | |||
2255 | ||||
2256 | /// Rewrite the loop's terminating condition if it uses a max computation. | |||
2257 | /// | |||
2258 | /// This is a narrow solution to a specific, but acute, problem. For loops | |||
2259 | /// like this: | |||
2260 | /// | |||
2261 | /// i = 0; | |||
2262 | /// do { | |||
2263 | /// p[i] = 0.0; | |||
2264 | /// } while (++i < n); | |||
2265 | /// | |||
2266 | /// the trip count isn't just 'n', because 'n' might not be positive. And | |||
2267 | /// unfortunately this can come up even for loops where the user didn't use | |||
2268 | /// a C do-while loop. For example, seemingly well-behaved top-test loops | |||
2269 | /// will commonly be lowered like this: | |||
2270 | /// | |||
2271 | /// if (n > 0) { | |||
2272 | /// i = 0; | |||
2273 | /// do { | |||
2274 | /// p[i] = 0.0; | |||
2275 | /// } while (++i < n); | |||
2276 | /// } | |||
2277 | /// | |||
2278 | /// and then it's possible for subsequent optimization to obscure the if | |||
2279 | /// test in such a way that indvars can't find it. | |||
2280 | /// | |||
2281 | /// When indvars can't find the if test in loops like this, it creates a | |||
2282 | /// max expression, which allows it to give the loop a canonical | |||
2283 | /// induction variable: | |||
2284 | /// | |||
2285 | /// i = 0; | |||
2286 | /// max = n < 1 ? 1 : n; | |||
2287 | /// do { | |||
2288 | /// p[i] = 0.0; | |||
2289 | /// } while (++i != max); | |||
2290 | /// | |||
2291 | /// Canonical induction variables are necessary because the loop passes | |||
2292 | /// are designed around them. The most obvious example of this is the | |||
2293 | /// LoopInfo analysis, which doesn't remember trip count values. It | |||
2294 | /// expects to be able to rediscover the trip count each time it is | |||
2295 | /// needed, and it does this using a simple analysis that only succeeds if | |||
2296 | /// the loop has a canonical induction variable. | |||
2297 | /// | |||
2298 | /// However, when it comes time to generate code, the maximum operation | |||
2299 | /// can be quite costly, especially if it's inside of an outer loop. | |||
2300 | /// | |||
2301 | /// This function solves this problem by detecting this type of loop and | |||
2302 | /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting | |||
2303 | /// the instructions for the maximum computation. | |||
2304 | ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) { | |||
2305 | // Check that the loop matches the pattern we're looking for. | |||
2306 | if (Cond->getPredicate() != CmpInst::ICMP_EQ && | |||
2307 | Cond->getPredicate() != CmpInst::ICMP_NE) | |||
2308 | return Cond; | |||
2309 | ||||
2310 | SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1)); | |||
2311 | if (!Sel || !Sel->hasOneUse()) return Cond; | |||
2312 | ||||
2313 | const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L); | |||
2314 | if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) | |||
2315 | return Cond; | |||
2316 | const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1); | |||
2317 | ||||
2318 | // Add one to the backedge-taken count to get the trip count. | |||
2319 | const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount); | |||
2320 | if (IterationCount != SE.getSCEV(Sel)) return Cond; | |||
2321 | ||||
2322 | // Check for a max calculation that matches the pattern. There's no check | |||
2323 | // for ICMP_ULE here because the comparison would be with zero, which | |||
2324 | // isn't interesting. | |||
2325 | CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE; | |||
2326 | const SCEVNAryExpr *Max = nullptr; | |||
2327 | if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) { | |||
2328 | Pred = ICmpInst::ICMP_SLE; | |||
2329 | Max = S; | |||
2330 | } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) { | |||
2331 | Pred = ICmpInst::ICMP_SLT; | |||
2332 | Max = S; | |||
2333 | } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) { | |||
2334 | Pred = ICmpInst::ICMP_ULT; | |||
2335 | Max = U; | |||
2336 | } else { | |||
2337 | // No match; bail. | |||
2338 | return Cond; | |||
2339 | } | |||
2340 | ||||
2341 | // To handle a max with more than two operands, this optimization would | |||
2342 | // require additional checking and setup. | |||
2343 | if (Max->getNumOperands() != 2) | |||
2344 | return Cond; | |||
2345 | ||||
2346 | const SCEV *MaxLHS = Max->getOperand(0); | |||
2347 | const SCEV *MaxRHS = Max->getOperand(1); | |||
2348 | ||||
2349 | // ScalarEvolution canonicalizes constants to the left. For < and >, look | |||
2350 | // for a comparison with 1. For <= and >=, a comparison with zero. | |||
2351 | if (!MaxLHS || | |||
2352 | (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One))) | |||
2353 | return Cond; | |||
2354 | ||||
2355 | // Check the relevant induction variable for conformance to | |||
2356 | // the pattern. | |||
2357 | const SCEV *IV = SE.getSCEV(Cond->getOperand(0)); | |||
2358 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV); | |||
2359 | if (!AR || !AR->isAffine() || | |||
2360 | AR->getStart() != One || | |||
2361 | AR->getStepRecurrence(SE) != One) | |||
2362 | return Cond; | |||
2363 | ||||
2364 | assert(AR->getLoop() == L &&(static_cast <bool> (AR->getLoop() == L && "Loop condition operand is an addrec in a different loop!" ) ? void (0) : __assert_fail ("AR->getLoop() == L && \"Loop condition operand is an addrec in a different loop!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 2365, __extension__ __PRETTY_FUNCTION__)) | |||
2365 | "Loop condition operand is an addrec in a different loop!")(static_cast <bool> (AR->getLoop() == L && "Loop condition operand is an addrec in a different loop!" ) ? void (0) : __assert_fail ("AR->getLoop() == L && \"Loop condition operand is an addrec in a different loop!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 2365, __extension__ __PRETTY_FUNCTION__)); | |||
2366 | ||||
2367 | // Check the right operand of the select, and remember it, as it will | |||
2368 | // be used in the new comparison instruction. | |||
2369 | Value *NewRHS = nullptr; | |||
2370 | if (ICmpInst::isTrueWhenEqual(Pred)) { | |||
2371 | // Look for n+1, and grab n. | |||
2372 | if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1))) | |||
2373 | if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1))) | |||
2374 | if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS) | |||
2375 | NewRHS = BO->getOperand(0); | |||
2376 | if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2))) | |||
2377 | if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1))) | |||
2378 | if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS) | |||
2379 | NewRHS = BO->getOperand(0); | |||
2380 | if (!NewRHS) | |||
2381 | return Cond; | |||
2382 | } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS) | |||
2383 | NewRHS = Sel->getOperand(1); | |||
2384 | else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS) | |||
2385 | NewRHS = Sel->getOperand(2); | |||
2386 | else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS)) | |||
2387 | NewRHS = SU->getValue(); | |||
2388 | else | |||
2389 | // Max doesn't match expected pattern. | |||
2390 | return Cond; | |||
2391 | ||||
2392 | // Determine the new comparison opcode. It may be signed or unsigned, | |||
2393 | // and the original comparison may be either equality or inequality. | |||
2394 | if (Cond->getPredicate() == CmpInst::ICMP_EQ) | |||
2395 | Pred = CmpInst::getInversePredicate(Pred); | |||
2396 | ||||
2397 | // Ok, everything looks ok to change the condition into an SLT or SGE and | |||
2398 | // delete the max calculation. | |||
2399 | ICmpInst *NewCond = | |||
2400 | new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp"); | |||
2401 | ||||
2402 | // Delete the max calculation instructions. | |||
2403 | NewCond->setDebugLoc(Cond->getDebugLoc()); | |||
2404 | Cond->replaceAllUsesWith(NewCond); | |||
2405 | CondUse->setUser(NewCond); | |||
2406 | Instruction *Cmp = cast<Instruction>(Sel->getOperand(0)); | |||
2407 | Cond->eraseFromParent(); | |||
2408 | Sel->eraseFromParent(); | |||
2409 | if (Cmp->use_empty()) | |||
2410 | Cmp->eraseFromParent(); | |||
2411 | return NewCond; | |||
2412 | } | |||
2413 | ||||
2414 | /// Change loop terminating condition to use the postinc iv when possible. | |||
2415 | void | |||
2416 | LSRInstance::OptimizeLoopTermCond() { | |||
2417 | SmallPtrSet<Instruction *, 4> PostIncs; | |||
2418 | ||||
2419 | // We need a different set of heuristics for rotated and non-rotated loops. | |||
2420 | // If a loop is rotated then the latch is also the backedge, so inserting | |||
2421 | // post-inc expressions just before the latch is ideal. To reduce live ranges | |||
2422 | // it also makes sense to rewrite terminating conditions to use post-inc | |||
2423 | // expressions. | |||
2424 | // | |||
2425 | // If the loop is not rotated then the latch is not a backedge; the latch | |||
2426 | // check is done in the loop head. Adding post-inc expressions before the | |||
2427 | // latch will cause overlapping live-ranges of pre-inc and post-inc expressions | |||
2428 | // in the loop body. In this case we do *not* want to use post-inc expressions | |||
2429 | // in the latch check, and we want to insert post-inc expressions before | |||
2430 | // the backedge. | |||
2431 | BasicBlock *LatchBlock = L->getLoopLatch(); | |||
2432 | SmallVector<BasicBlock*, 8> ExitingBlocks; | |||
2433 | L->getExitingBlocks(ExitingBlocks); | |||
2434 | if (!llvm::is_contained(ExitingBlocks, LatchBlock)) { | |||
2435 | // The backedge doesn't exit the loop; treat this as a head-tested loop. | |||
2436 | IVIncInsertPos = LatchBlock->getTerminator(); | |||
2437 | return; | |||
2438 | } | |||
2439 | ||||
2440 | // Otherwise treat this as a rotated loop. | |||
2441 | for (BasicBlock *ExitingBlock : ExitingBlocks) { | |||
2442 | // Get the terminating condition for the loop if possible. If we | |||
2443 | // can, we want to change it to use a post-incremented version of its | |||
2444 | // induction variable, to allow coalescing the live ranges for the IV into | |||
2445 | // one register value. | |||
2446 | ||||
2447 | BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator()); | |||
2448 | if (!TermBr) | |||
2449 | continue; | |||
2450 | // FIXME: Overly conservative, termination condition could be an 'or' etc.. | |||
2451 | if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition())) | |||
2452 | continue; | |||
2453 | ||||
2454 | // Search IVUsesByStride to find Cond's IVUse if there is one. | |||
2455 | IVStrideUse *CondUse = nullptr; | |||
2456 | ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition()); | |||
2457 | if (!FindIVUserForCond(Cond, CondUse)) | |||
2458 | continue; | |||
2459 | ||||
2460 | // If the trip count is computed in terms of a max (due to ScalarEvolution | |||
2461 | // being unable to find a sufficient guard, for example), change the loop | |||
2462 | // comparison to use SLT or ULT instead of NE. | |||
2463 | // One consequence of doing this now is that it disrupts the count-down | |||
2464 | // optimization. That's not always a bad thing though, because in such | |||
2465 | // cases it may still be worthwhile to avoid a max. | |||
2466 | Cond = OptimizeMax(Cond, CondUse); | |||
2467 | ||||
2468 | // If this exiting block dominates the latch block, it may also use | |||
2469 | // the post-inc value if it won't be shared with other uses. | |||
2470 | // Check for dominance. | |||
2471 | if (!DT.dominates(ExitingBlock, LatchBlock)) | |||
2472 | continue; | |||
2473 | ||||
2474 | // Conservatively avoid trying to use the post-inc value in non-latch | |||
2475 | // exits if there may be pre-inc users in intervening blocks. | |||
2476 | if (LatchBlock != ExitingBlock) | |||
2477 | for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) | |||
2478 | // Test if the use is reachable from the exiting block. This dominator | |||
2479 | // query is a conservative approximation of reachability. | |||
2480 | if (&*UI != CondUse && | |||
2481 | !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) { | |||
2482 | // Conservatively assume there may be reuse if the quotient of their | |||
2483 | // strides could be a legal scale. | |||
2484 | const SCEV *A = IU.getStride(*CondUse, L); | |||
2485 | const SCEV *B = IU.getStride(*UI, L); | |||
2486 | if (!A || !B) continue; | |||
2487 | if (SE.getTypeSizeInBits(A->getType()) != | |||
2488 | SE.getTypeSizeInBits(B->getType())) { | |||
2489 | if (SE.getTypeSizeInBits(A->getType()) > | |||
2490 | SE.getTypeSizeInBits(B->getType())) | |||
2491 | B = SE.getSignExtendExpr(B, A->getType()); | |||
2492 | else | |||
2493 | A = SE.getSignExtendExpr(A, B->getType()); | |||
2494 | } | |||
2495 | if (const SCEVConstant *D = | |||
2496 | dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) { | |||
2497 | const ConstantInt *C = D->getValue(); | |||
2498 | // Stride of one or negative one can have reuse with non-addresses. | |||
2499 | if (C->isOne() || C->isMinusOne()) | |||
2500 | goto decline_post_inc; | |||
2501 | // Avoid weird situations. | |||
2502 | if (C->getValue().getSignificantBits() >= 64 || | |||
2503 | C->getValue().isMinSignedValue()) | |||
2504 | goto decline_post_inc; | |||
2505 | // Check for possible scaled-address reuse. | |||
2506 | if (isAddressUse(TTI, UI->getUser(), UI->getOperandValToReplace())) { | |||
2507 | MemAccessTy AccessTy = getAccessType( | |||
2508 | TTI, UI->getUser(), UI->getOperandValToReplace()); | |||
2509 | int64_t Scale = C->getSExtValue(); | |||
2510 | if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr, | |||
2511 | /*BaseOffset=*/0, | |||
2512 | /*HasBaseReg=*/false, Scale, | |||
2513 | AccessTy.AddrSpace)) | |||
2514 | goto decline_post_inc; | |||
2515 | Scale = -Scale; | |||
2516 | if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr, | |||
2517 | /*BaseOffset=*/0, | |||
2518 | /*HasBaseReg=*/false, Scale, | |||
2519 | AccessTy.AddrSpace)) | |||
2520 | goto decline_post_inc; | |||
2521 | } | |||
2522 | } | |||
2523 | } | |||
2524 | ||||
2525 | LLVM_DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Change loop exiting icmp to use postinc iv: " << *Cond << '\n'; } } while (false) | |||
2526 | << *Cond << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Change loop exiting icmp to use postinc iv: " << *Cond << '\n'; } } while (false); | |||
2527 | ||||
2528 | // It's possible for the setcc instruction to be anywhere in the loop, and | |||
2529 | // possible for it to have multiple users. If it is not immediately before | |||
2530 | // the exiting block branch, move it. | |||
2531 | if (Cond->getNextNonDebugInstruction() != TermBr) { | |||
2532 | if (Cond->hasOneUse()) { | |||
2533 | Cond->moveBefore(TermBr); | |||
2534 | } else { | |||
2535 | // Clone the terminating condition and insert into the loopend. | |||
2536 | ICmpInst *OldCond = Cond; | |||
2537 | Cond = cast<ICmpInst>(Cond->clone()); | |||
2538 | Cond->setName(L->getHeader()->getName() + ".termcond"); | |||
2539 | Cond->insertInto(ExitingBlock, TermBr->getIterator()); | |||
2540 | ||||
2541 | // Clone the IVUse, as the old use still exists! | |||
2542 | CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace()); | |||
2543 | TermBr->replaceUsesOfWith(OldCond, Cond); | |||
2544 | } | |||
2545 | } | |||
2546 | ||||
2547 | // If we get to here, we know that we can transform the setcc instruction to | |||
2548 | // use the post-incremented version of the IV, allowing us to coalesce the | |||
2549 | // live ranges for the IV correctly. | |||
2550 | CondUse->transformToPostInc(L); | |||
2551 | Changed = true; | |||
2552 | ||||
2553 | PostIncs.insert(Cond); | |||
2554 | decline_post_inc:; | |||
2555 | } | |||
2556 | ||||
2557 | // Determine an insertion point for the loop induction variable increment. It | |||
2558 | // must dominate all the post-inc comparisons we just set up, and it must | |||
2559 | // dominate the loop latch edge. | |||
2560 | IVIncInsertPos = L->getLoopLatch()->getTerminator(); | |||
2561 | for (Instruction *Inst : PostIncs) | |||
2562 | IVIncInsertPos = DT.findNearestCommonDominator(IVIncInsertPos, Inst); | |||
2563 | } | |||
2564 | ||||
2565 | /// Determine if the given use can accommodate a fixup at the given offset and | |||
2566 | /// other details. If so, update the use and return true. | |||
2567 | bool LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset, | |||
2568 | bool HasBaseReg, LSRUse::KindType Kind, | |||
2569 | MemAccessTy AccessTy) { | |||
2570 | int64_t NewMinOffset = LU.MinOffset; | |||
2571 | int64_t NewMaxOffset = LU.MaxOffset; | |||
2572 | MemAccessTy NewAccessTy = AccessTy; | |||
2573 | ||||
2574 | // Check for a mismatched kind. It's tempting to collapse mismatched kinds to | |||
2575 | // something conservative, however this can pessimize in the case that one of | |||
2576 | // the uses will have all its uses outside the loop, for example. | |||
2577 | if (LU.Kind != Kind) | |||
2578 | return false; | |||
2579 | ||||
2580 | // Check for a mismatched access type, and fall back conservatively as needed. | |||
2581 | // TODO: Be less conservative when the type is similar and can use the same | |||
2582 | // addressing modes. | |||
2583 | if (Kind == LSRUse::Address) { | |||
2584 | if (AccessTy.MemTy != LU.AccessTy.MemTy) { | |||
2585 | NewAccessTy = MemAccessTy::getUnknown(AccessTy.MemTy->getContext(), | |||
2586 | AccessTy.AddrSpace); | |||
2587 | } | |||
2588 | } | |||
2589 | ||||
2590 | // Conservatively assume HasBaseReg is true for now. | |||
2591 | if (NewOffset < LU.MinOffset) { | |||
2592 | if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr, | |||
2593 | LU.MaxOffset - NewOffset, HasBaseReg)) | |||
2594 | return false; | |||
2595 | NewMinOffset = NewOffset; | |||
2596 | } else if (NewOffset > LU.MaxOffset) { | |||
2597 | if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr, | |||
2598 | NewOffset - LU.MinOffset, HasBaseReg)) | |||
2599 | return false; | |||
2600 | NewMaxOffset = NewOffset; | |||
2601 | } | |||
2602 | ||||
2603 | // Update the use. | |||
2604 | LU.MinOffset = NewMinOffset; | |||
2605 | LU.MaxOffset = NewMaxOffset; | |||
2606 | LU.AccessTy = NewAccessTy; | |||
2607 | return true; | |||
2608 | } | |||
2609 | ||||
2610 | /// Return an LSRUse index and an offset value for a fixup which needs the given | |||
2611 | /// expression, with the given kind and optional access type. Either reuse an | |||
2612 | /// existing use or create a new one, as needed. | |||
2613 | std::pair<size_t, int64_t> LSRInstance::getUse(const SCEV *&Expr, | |||
2614 | LSRUse::KindType Kind, | |||
2615 | MemAccessTy AccessTy) { | |||
2616 | const SCEV *Copy = Expr; | |||
2617 | int64_t Offset = ExtractImmediate(Expr, SE); | |||
2618 | ||||
2619 | // Basic uses can't accept any offset, for example. | |||
2620 | if (!isAlwaysFoldable(TTI, Kind, AccessTy, /*BaseGV=*/ nullptr, | |||
2621 | Offset, /*HasBaseReg=*/ true)) { | |||
2622 | Expr = Copy; | |||
2623 | Offset = 0; | |||
2624 | } | |||
2625 | ||||
2626 | std::pair<UseMapTy::iterator, bool> P = | |||
2627 | UseMap.insert(std::make_pair(LSRUse::SCEVUseKindPair(Expr, Kind), 0)); | |||
2628 | if (!P.second) { | |||
2629 | // A use already existed with this base. | |||
2630 | size_t LUIdx = P.first->second; | |||
2631 | LSRUse &LU = Uses[LUIdx]; | |||
2632 | if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy)) | |||
2633 | // Reuse this use. | |||
2634 | return std::make_pair(LUIdx, Offset); | |||
2635 | } | |||
2636 | ||||
2637 | // Create a new use. | |||
2638 | size_t LUIdx = Uses.size(); | |||
2639 | P.first->second = LUIdx; | |||
2640 | Uses.push_back(LSRUse(Kind, AccessTy)); | |||
2641 | LSRUse &LU = Uses[LUIdx]; | |||
2642 | ||||
2643 | LU.MinOffset = Offset; | |||
2644 | LU.MaxOffset = Offset; | |||
2645 | return std::make_pair(LUIdx, Offset); | |||
2646 | } | |||
2647 | ||||
2648 | /// Delete the given use from the Uses list. | |||
2649 | void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) { | |||
2650 | if (&LU != &Uses.back()) | |||
2651 | std::swap(LU, Uses.back()); | |||
2652 | Uses.pop_back(); | |||
2653 | ||||
2654 | // Update RegUses. | |||
2655 | RegUses.swapAndDropUse(LUIdx, Uses.size()); | |||
2656 | } | |||
2657 | ||||
2658 | /// Look for a use distinct from OrigLU which is has a formula that has the same | |||
2659 | /// registers as the given formula. | |||
2660 | LSRUse * | |||
2661 | LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF, | |||
2662 | const LSRUse &OrigLU) { | |||
2663 | // Search all uses for the formula. This could be more clever. | |||
2664 | for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { | |||
2665 | LSRUse &LU = Uses[LUIdx]; | |||
2666 | // Check whether this use is close enough to OrigLU, to see whether it's | |||
2667 | // worthwhile looking through its formulae. | |||
2668 | // Ignore ICmpZero uses because they may contain formulae generated by | |||
2669 | // GenerateICmpZeroScales, in which case adding fixup offsets may | |||
2670 | // be invalid. | |||
2671 | if (&LU != &OrigLU && | |||
2672 | LU.Kind != LSRUse::ICmpZero && | |||
2673 | LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy && | |||
2674 | LU.WidestFixupType == OrigLU.WidestFixupType && | |||
2675 | LU.HasFormulaWithSameRegs(OrigF)) { | |||
2676 | // Scan through this use's formulae. | |||
2677 | for (const Formula &F : LU.Formulae) { | |||
2678 | // Check to see if this formula has the same registers and symbols | |||
2679 | // as OrigF. | |||
2680 | if (F.BaseRegs == OrigF.BaseRegs && | |||
2681 | F.ScaledReg == OrigF.ScaledReg && | |||
2682 | F.BaseGV == OrigF.BaseGV && | |||
2683 | F.Scale == OrigF.Scale && | |||
2684 | F.UnfoldedOffset == OrigF.UnfoldedOffset) { | |||
2685 | if (F.BaseOffset == 0) | |||
2686 | return &LU; | |||
2687 | // This is the formula where all the registers and symbols matched; | |||
2688 | // there aren't going to be any others. Since we declined it, we | |||
2689 | // can skip the rest of the formulae and proceed to the next LSRUse. | |||
2690 | break; | |||
2691 | } | |||
2692 | } | |||
2693 | } | |||
2694 | } | |||
2695 | ||||
2696 | // Nothing looked good. | |||
2697 | return nullptr; | |||
2698 | } | |||
2699 | ||||
2700 | void LSRInstance::CollectInterestingTypesAndFactors() { | |||
2701 | SmallSetVector<const SCEV *, 4> Strides; | |||
2702 | ||||
2703 | // Collect interesting types and strides. | |||
2704 | SmallVector<const SCEV *, 4> Worklist; | |||
2705 | for (const IVStrideUse &U : IU) { | |||
2706 | const SCEV *Expr = IU.getExpr(U); | |||
2707 | ||||
2708 | // Collect interesting types. | |||
2709 | Types.insert(SE.getEffectiveSCEVType(Expr->getType())); | |||
2710 | ||||
2711 | // Add strides for mentioned loops. | |||
2712 | Worklist.push_back(Expr); | |||
2713 | do { | |||
2714 | const SCEV *S = Worklist.pop_back_val(); | |||
2715 | if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { | |||
2716 | if (AR->getLoop() == L) | |||
2717 | Strides.insert(AR->getStepRecurrence(SE)); | |||
2718 | Worklist.push_back(AR->getStart()); | |||
2719 | } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { | |||
2720 | append_range(Worklist, Add->operands()); | |||
2721 | } | |||
2722 | } while (!Worklist.empty()); | |||
2723 | } | |||
2724 | ||||
2725 | // Compute interesting factors from the set of interesting strides. | |||
2726 | for (SmallSetVector<const SCEV *, 4>::const_iterator | |||
2727 | I = Strides.begin(), E = Strides.end(); I != E; ++I) | |||
2728 | for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter = | |||
2729 | std::next(I); NewStrideIter != E; ++NewStrideIter) { | |||
2730 | const SCEV *OldStride = *I; | |||
2731 | const SCEV *NewStride = *NewStrideIter; | |||
2732 | ||||
2733 | if (SE.getTypeSizeInBits(OldStride->getType()) != | |||
2734 | SE.getTypeSizeInBits(NewStride->getType())) { | |||
2735 | if (SE.getTypeSizeInBits(OldStride->getType()) > | |||
2736 | SE.getTypeSizeInBits(NewStride->getType())) | |||
2737 | NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType()); | |||
2738 | else | |||
2739 | OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType()); | |||
2740 | } | |||
2741 | if (const SCEVConstant *Factor = | |||
2742 | dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride, | |||
2743 | SE, true))) { | |||
2744 | if (Factor->getAPInt().getSignificantBits() <= 64 && !Factor->isZero()) | |||
2745 | Factors.insert(Factor->getAPInt().getSExtValue()); | |||
2746 | } else if (const SCEVConstant *Factor = | |||
2747 | dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride, | |||
2748 | NewStride, | |||
2749 | SE, true))) { | |||
2750 | if (Factor->getAPInt().getSignificantBits() <= 64 && !Factor->isZero()) | |||
2751 | Factors.insert(Factor->getAPInt().getSExtValue()); | |||
2752 | } | |||
2753 | } | |||
2754 | ||||
2755 | // If all uses use the same type, don't bother looking for truncation-based | |||
2756 | // reuse. | |||
2757 | if (Types.size() == 1) | |||
2758 | Types.clear(); | |||
2759 | ||||
2760 | LLVM_DEBUG(print_factors_and_types(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { print_factors_and_types(dbgs()); } } while (false); | |||
2761 | } | |||
2762 | ||||
2763 | /// Helper for CollectChains that finds an IV operand (computed by an AddRec in | |||
2764 | /// this loop) within [OI,OE) or returns OE. If IVUsers mapped Instructions to | |||
2765 | /// IVStrideUses, we could partially skip this. | |||
2766 | static User::op_iterator | |||
2767 | findIVOperand(User::op_iterator OI, User::op_iterator OE, | |||
2768 | Loop *L, ScalarEvolution &SE) { | |||
2769 | for(; OI != OE; ++OI) { | |||
2770 | if (Instruction *Oper = dyn_cast<Instruction>(*OI)) { | |||
2771 | if (!SE.isSCEVable(Oper->getType())) | |||
2772 | continue; | |||
2773 | ||||
2774 | if (const SCEVAddRecExpr *AR = | |||
2775 | dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Oper))) { | |||
2776 | if (AR->getLoop() == L) | |||
2777 | break; | |||
2778 | } | |||
2779 | } | |||
2780 | } | |||
2781 | return OI; | |||
2782 | } | |||
2783 | ||||
2784 | /// IVChain logic must consistently peek base TruncInst operands, so wrap it in | |||
2785 | /// a convenient helper. | |||
2786 | static Value *getWideOperand(Value *Oper) { | |||
2787 | if (TruncInst *Trunc = dyn_cast<TruncInst>(Oper)) | |||
2788 | return Trunc->getOperand(0); | |||
2789 | return Oper; | |||
2790 | } | |||
2791 | ||||
2792 | /// Return true if we allow an IV chain to include both types. | |||
2793 | static bool isCompatibleIVType(Value *LVal, Value *RVal) { | |||
2794 | Type *LType = LVal->getType(); | |||
2795 | Type *RType = RVal->getType(); | |||
2796 | return (LType == RType) || (LType->isPointerTy() && RType->isPointerTy() && | |||
2797 | // Different address spaces means (possibly) | |||
2798 | // different types of the pointer implementation, | |||
2799 | // e.g. i16 vs i32 so disallow that. | |||
2800 | (LType->getPointerAddressSpace() == | |||
2801 | RType->getPointerAddressSpace())); | |||
2802 | } | |||
2803 | ||||
2804 | /// Return an approximation of this SCEV expression's "base", or NULL for any | |||
2805 | /// constant. Returning the expression itself is conservative. Returning a | |||
2806 | /// deeper subexpression is more precise and valid as long as it isn't less | |||
2807 | /// complex than another subexpression. For expressions involving multiple | |||
2808 | /// unscaled values, we need to return the pointer-type SCEVUnknown. This avoids | |||
2809 | /// forming chains across objects, such as: PrevOper==a[i], IVOper==b[i], | |||
2810 | /// IVInc==b-a. | |||
2811 | /// | |||
2812 | /// Since SCEVUnknown is the rightmost type, and pointers are the rightmost | |||
2813 | /// SCEVUnknown, we simply return the rightmost SCEV operand. | |||
2814 | static const SCEV *getExprBase(const SCEV *S) { | |||
2815 | switch (S->getSCEVType()) { | |||
2816 | default: // including scUnknown. | |||
2817 | return S; | |||
2818 | case scConstant: | |||
2819 | case scVScale: | |||
2820 | return nullptr; | |||
2821 | case scTruncate: | |||
2822 | return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand()); | |||
2823 | case scZeroExtend: | |||
2824 | return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand()); | |||
2825 | case scSignExtend: | |||
2826 | return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand()); | |||
2827 | case scAddExpr: { | |||
2828 | // Skip over scaled operands (scMulExpr) to follow add operands as long as | |||
2829 | // there's nothing more complex. | |||
2830 | // FIXME: not sure if we want to recognize negation. | |||
2831 | const SCEVAddExpr *Add = cast<SCEVAddExpr>(S); | |||
2832 | for (const SCEV *SubExpr : reverse(Add->operands())) { | |||
2833 | if (SubExpr->getSCEVType() == scAddExpr) | |||
2834 | return getExprBase(SubExpr); | |||
2835 | ||||
2836 | if (SubExpr->getSCEVType() != scMulExpr) | |||
2837 | return SubExpr; | |||
2838 | } | |||
2839 | return S; // all operands are scaled, be conservative. | |||
2840 | } | |||
2841 | case scAddRecExpr: | |||
2842 | return getExprBase(cast<SCEVAddRecExpr>(S)->getStart()); | |||
2843 | } | |||
2844 | llvm_unreachable("Unknown SCEV kind!")::llvm::llvm_unreachable_internal("Unknown SCEV kind!", "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp" , 2844); | |||
2845 | } | |||
2846 | ||||
2847 | /// Return true if the chain increment is profitable to expand into a loop | |||
2848 | /// invariant value, which may require its own register. A profitable chain | |||
2849 | /// increment will be an offset relative to the same base. We allow such offsets | |||
2850 | /// to potentially be used as chain increment as long as it's not obviously | |||
2851 | /// expensive to expand using real instructions. | |||
2852 | bool IVChain::isProfitableIncrement(const SCEV *OperExpr, | |||
2853 | const SCEV *IncExpr, | |||
2854 | ScalarEvolution &SE) { | |||
2855 | // Aggressively form chains when -stress-ivchain. | |||
2856 | if (StressIVChain) | |||
2857 | return true; | |||
2858 | ||||
2859 | // Do not replace a constant offset from IV head with a nonconstant IV | |||
2860 | // increment. | |||
2861 | if (!isa<SCEVConstant>(IncExpr)) { | |||
2862 | const SCEV *HeadExpr = SE.getSCEV(getWideOperand(Incs[0].IVOperand)); | |||
2863 | if (isa<SCEVConstant>(SE.getMinusSCEV(OperExpr, HeadExpr))) | |||
2864 | return false; | |||
2865 | } | |||
2866 | ||||
2867 | SmallPtrSet<const SCEV*, 8> Processed; | |||
2868 | return !isHighCostExpansion(IncExpr, Processed, SE); | |||
2869 | } | |||
2870 | ||||
2871 | /// Return true if the number of registers needed for the chain is estimated to | |||
2872 | /// be less than the number required for the individual IV users. First prohibit | |||
2873 | /// any IV users that keep the IV live across increments (the Users set should | |||
2874 | /// be empty). Next count the number and type of increments in the chain. | |||
2875 | /// | |||
2876 | /// Chaining IVs can lead to considerable code bloat if ISEL doesn't | |||
2877 | /// effectively use postinc addressing modes. Only consider it profitable it the | |||
2878 | /// increments can be computed in fewer registers when chained. | |||
2879 | /// | |||
2880 | /// TODO: Consider IVInc free if it's already used in another chains. | |||
2881 | static bool isProfitableChain(IVChain &Chain, | |||
2882 | SmallPtrSetImpl<Instruction *> &Users, | |||
2883 | ScalarEvolution &SE, | |||
2884 | const TargetTransformInfo &TTI) { | |||
2885 | if (StressIVChain) | |||
2886 | return true; | |||
2887 | ||||
2888 | if (!Chain.hasIncs()) | |||
2889 | return false; | |||
2890 | ||||
2891 | if (!Users.empty()) { | |||
2892 | LLVM_DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " users:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Chain: " << *Chain. Incs[0].UserInst << " users:\n"; for (Instruction *Inst : Users) { dbgs() << " " << *Inst << "\n" ; }; } } while (false) | |||
2893 | for (Instruction *Instdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Chain: " << *Chain. Incs[0].UserInst << " users:\n"; for (Instruction *Inst : Users) { dbgs() << " " << *Inst << "\n" ; }; } } while (false) | |||
2894 | : Users) { dbgs() << " " << *Inst << "\n"; })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Chain: " << *Chain. Incs[0].UserInst << " users:\n"; for (Instruction *Inst : Users) { dbgs() << " " << *Inst << "\n" ; }; } } while (false); | |||
2895 | return false; | |||
2896 | } | |||
2897 | assert(!Chain.Incs.empty() && "empty IV chains are not allowed")(static_cast <bool> (!Chain.Incs.empty() && "empty IV chains are not allowed" ) ? void (0) : __assert_fail ("!Chain.Incs.empty() && \"empty IV chains are not allowed\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 2897, __extension__ __PRETTY_FUNCTION__)); | |||
2898 | ||||
2899 | // The chain itself may require a register, so intialize cost to 1. | |||
2900 | int cost = 1; | |||
2901 | ||||
2902 | // A complete chain likely eliminates the need for keeping the original IV in | |||
2903 | // a register. LSR does not currently know how to form a complete chain unless | |||
2904 | // the header phi already exists. | |||
2905 | if (isa<PHINode>(Chain.tailUserInst()) | |||
2906 | && SE.getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) { | |||
2907 | --cost; | |||
2908 | } | |||
2909 | const SCEV *LastIncExpr = nullptr; | |||
2910 | unsigned NumConstIncrements = 0; | |||
2911 | unsigned NumVarIncrements = 0; | |||
2912 | unsigned NumReusedIncrements = 0; | |||
2913 | ||||
2914 | if (TTI.isProfitableLSRChainElement(Chain.Incs[0].UserInst)) | |||
2915 | return true; | |||
2916 | ||||
2917 | for (const IVInc &Inc : Chain) { | |||
2918 | if (TTI.isProfitableLSRChainElement(Inc.UserInst)) | |||
2919 | return true; | |||
2920 | if (Inc.IncExpr->isZero()) | |||
2921 | continue; | |||
2922 | ||||
2923 | // Incrementing by zero or some constant is neutral. We assume constants can | |||
2924 | // be folded into an addressing mode or an add's immediate operand. | |||
2925 | if (isa<SCEVConstant>(Inc.IncExpr)) { | |||
2926 | ++NumConstIncrements; | |||
2927 | continue; | |||
2928 | } | |||
2929 | ||||
2930 | if (Inc.IncExpr == LastIncExpr) | |||
2931 | ++NumReusedIncrements; | |||
2932 | else | |||
2933 | ++NumVarIncrements; | |||
2934 | ||||
2935 | LastIncExpr = Inc.IncExpr; | |||
2936 | } | |||
2937 | // An IV chain with a single increment is handled by LSR's postinc | |||
2938 | // uses. However, a chain with multiple increments requires keeping the IV's | |||
2939 | // value live longer than it needs to be if chained. | |||
2940 | if (NumConstIncrements > 1) | |||
2941 | --cost; | |||
2942 | ||||
2943 | // Materializing increment expressions in the preheader that didn't exist in | |||
2944 | // the original code may cost a register. For example, sign-extended array | |||
2945 | // indices can produce ridiculous increments like this: | |||
2946 | // IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64))) | |||
2947 | cost += NumVarIncrements; | |||
2948 | ||||
2949 | // Reusing variable increments likely saves a register to hold the multiple of | |||
2950 | // the stride. | |||
2951 | cost -= NumReusedIncrements; | |||
2952 | ||||
2953 | LLVM_DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " Cost: " << costdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Chain: " << *Chain. Incs[0].UserInst << " Cost: " << cost << "\n" ; } } while (false) | |||
2954 | << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Chain: " << *Chain. Incs[0].UserInst << " Cost: " << cost << "\n" ; } } while (false); | |||
2955 | ||||
2956 | return cost < 0; | |||
2957 | } | |||
2958 | ||||
2959 | /// Add this IV user to an existing chain or make it the head of a new chain. | |||
2960 | void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVOper, | |||
2961 | SmallVectorImpl<ChainUsers> &ChainUsersVec) { | |||
2962 | // When IVs are used as types of varying widths, they are generally converted | |||
2963 | // to a wider type with some uses remaining narrow under a (free) trunc. | |||
2964 | Value *const NextIV = getWideOperand(IVOper); | |||
2965 | const SCEV *const OperExpr = SE.getSCEV(NextIV); | |||
2966 | const SCEV *const OperExprBase = getExprBase(OperExpr); | |||
2967 | ||||
2968 | // Visit all existing chains. Check if its IVOper can be computed as a | |||
2969 | // profitable loop invariant increment from the last link in the Chain. | |||
2970 | unsigned ChainIdx = 0, NChains = IVChainVec.size(); | |||
2971 | const SCEV *LastIncExpr = nullptr; | |||
2972 | for (; ChainIdx < NChains; ++ChainIdx) { | |||
2973 | IVChain &Chain = IVChainVec[ChainIdx]; | |||
2974 | ||||
2975 | // Prune the solution space aggressively by checking that both IV operands | |||
2976 | // are expressions that operate on the same unscaled SCEVUnknown. This | |||
2977 | // "base" will be canceled by the subsequent getMinusSCEV call. Checking | |||
2978 | // first avoids creating extra SCEV expressions. | |||
2979 | if (!StressIVChain && Chain.ExprBase != OperExprBase) | |||
2980 | continue; | |||
2981 | ||||
2982 | Value *PrevIV = getWideOperand(Chain.Incs.back().IVOperand); | |||
2983 | if (!isCompatibleIVType(PrevIV, NextIV)) | |||
2984 | continue; | |||
2985 | ||||
2986 | // A phi node terminates a chain. | |||
2987 | if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst())) | |||
2988 | continue; | |||
2989 | ||||
2990 | // The increment must be loop-invariant so it can be kept in a register. | |||
2991 | const SCEV *PrevExpr = SE.getSCEV(PrevIV); | |||
2992 | const SCEV *IncExpr = SE.getMinusSCEV(OperExpr, PrevExpr); | |||
2993 | if (isa<SCEVCouldNotCompute>(IncExpr) || !SE.isLoopInvariant(IncExpr, L)) | |||
2994 | continue; | |||
2995 | ||||
2996 | if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) { | |||
2997 | LastIncExpr = IncExpr; | |||
2998 | break; | |||
2999 | } | |||
3000 | } | |||
3001 | // If we haven't found a chain, create a new one, unless we hit the max. Don't | |||
3002 | // bother for phi nodes, because they must be last in the chain. | |||
3003 | if (ChainIdx == NChains) { | |||
3004 | if (isa<PHINode>(UserInst)) | |||
3005 | return; | |||
3006 | if (NChains >= MaxChains && !StressIVChain) { | |||
3007 | LLVM_DEBUG(dbgs() << "IV Chain Limit\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "IV Chain Limit\n"; } } while (false); | |||
3008 | return; | |||
3009 | } | |||
3010 | LastIncExpr = OperExpr; | |||
3011 | // IVUsers may have skipped over sign/zero extensions. We don't currently | |||
3012 | // attempt to form chains involving extensions unless they can be hoisted | |||
3013 | // into this loop's AddRec. | |||
3014 | if (!isa<SCEVAddRecExpr>(LastIncExpr)) | |||
3015 | return; | |||
3016 | ++NChains; | |||
3017 | IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr), | |||
3018 | OperExprBase)); | |||
3019 | ChainUsersVec.resize(NChains); | |||
3020 | LLVM_DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInstdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInst << ") IV=" << *LastIncExpr << "\n"; } } while (false) | |||
3021 | << ") IV=" << *LastIncExpr << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInst << ") IV=" << *LastIncExpr << "\n"; } } while (false); | |||
3022 | } else { | |||
3023 | LLVM_DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Inc: (" << *UserInstdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "IV Chain#" << ChainIdx << " Inc: (" << *UserInst << ") IV+" << *LastIncExpr << "\n"; } } while (false) | |||
3024 | << ") IV+" << *LastIncExpr << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "IV Chain#" << ChainIdx << " Inc: (" << *UserInst << ") IV+" << *LastIncExpr << "\n"; } } while (false); | |||
3025 | // Add this IV user to the end of the chain. | |||
3026 | IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr)); | |||
3027 | } | |||
3028 | IVChain &Chain = IVChainVec[ChainIdx]; | |||
3029 | ||||
3030 | SmallPtrSet<Instruction*,4> &NearUsers = ChainUsersVec[ChainIdx].NearUsers; | |||
3031 | // This chain's NearUsers become FarUsers. | |||
3032 | if (!LastIncExpr->isZero()) { | |||
3033 | ChainUsersVec[ChainIdx].FarUsers.insert(NearUsers.begin(), | |||
3034 | NearUsers.end()); | |||
3035 | NearUsers.clear(); | |||
3036 | } | |||
3037 | ||||
3038 | // All other uses of IVOperand become near uses of the chain. | |||
3039 | // We currently ignore intermediate values within SCEV expressions, assuming | |||
3040 | // they will eventually be used be the current chain, or can be computed | |||
3041 | // from one of the chain increments. To be more precise we could | |||
3042 | // transitively follow its user and only add leaf IV users to the set. | |||
3043 | for (User *U : IVOper->users()) { | |||
3044 | Instruction *OtherUse = dyn_cast<Instruction>(U); | |||
3045 | if (!OtherUse) | |||
3046 | continue; | |||
3047 | // Uses in the chain will no longer be uses if the chain is formed. | |||
3048 | // Include the head of the chain in this iteration (not Chain.begin()). | |||
3049 | IVChain::const_iterator IncIter = Chain.Incs.begin(); | |||
3050 | IVChain::const_iterator IncEnd = Chain.Incs.end(); | |||
3051 | for( ; IncIter != IncEnd; ++IncIter) { | |||
3052 | if (IncIter->UserInst == OtherUse) | |||
3053 | break; | |||
3054 | } | |||
3055 | if (IncIter != IncEnd) | |||
3056 | continue; | |||
3057 | ||||
3058 | if (SE.isSCEVable(OtherUse->getType()) | |||
3059 | && !isa<SCEVUnknown>(SE.getSCEV(OtherUse)) | |||
3060 | && IU.isIVUserOrOperand(OtherUse)) { | |||
3061 | continue; | |||
3062 | } | |||
3063 | NearUsers.insert(OtherUse); | |||
3064 | } | |||
3065 | ||||
3066 | // Since this user is part of the chain, it's no longer considered a use | |||
3067 | // of the chain. | |||
3068 | ChainUsersVec[ChainIdx].FarUsers.erase(UserInst); | |||
3069 | } | |||
3070 | ||||
3071 | /// Populate the vector of Chains. | |||
3072 | /// | |||
3073 | /// This decreases ILP at the architecture level. Targets with ample registers, | |||
3074 | /// multiple memory ports, and no register renaming probably don't want | |||
3075 | /// this. However, such targets should probably disable LSR altogether. | |||
3076 | /// | |||
3077 | /// The job of LSR is to make a reasonable choice of induction variables across | |||
3078 | /// the loop. Subsequent passes can easily "unchain" computation exposing more | |||
3079 | /// ILP *within the loop* if the target wants it. | |||
3080 | /// | |||
3081 | /// Finding the best IV chain is potentially a scheduling problem. Since LSR | |||
3082 | /// will not reorder memory operations, it will recognize this as a chain, but | |||
3083 | /// will generate redundant IV increments. Ideally this would be corrected later | |||
3084 | /// by a smart scheduler: | |||
3085 | /// = A[i] | |||
3086 | /// = A[i+x] | |||
3087 | /// A[i] = | |||
3088 | /// A[i+x] = | |||
3089 | /// | |||
3090 | /// TODO: Walk the entire domtree within this loop, not just the path to the | |||
3091 | /// loop latch. This will discover chains on side paths, but requires | |||
3092 | /// maintaining multiple copies of the Chains state. | |||
3093 | void LSRInstance::CollectChains() { | |||
3094 | LLVM_DEBUG(dbgs() << "Collecting IV Chains.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Collecting IV Chains.\n"; } } while (false); | |||
3095 | SmallVector<ChainUsers, 8> ChainUsersVec; | |||
3096 | ||||
3097 | SmallVector<BasicBlock *,8> LatchPath; | |||
3098 | BasicBlock *LoopHeader = L->getHeader(); | |||
3099 | for (DomTreeNode *Rung = DT.getNode(L->getLoopLatch()); | |||
3100 | Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) { | |||
3101 | LatchPath.push_back(Rung->getBlock()); | |||
3102 | } | |||
3103 | LatchPath.push_back(LoopHeader); | |||
3104 | ||||
3105 | // Walk the instruction stream from the loop header to the loop latch. | |||
3106 | for (BasicBlock *BB : reverse(LatchPath)) { | |||
3107 | for (Instruction &I : *BB) { | |||
3108 | // Skip instructions that weren't seen by IVUsers analysis. | |||
3109 | if (isa<PHINode>(I) || !IU.isIVUserOrOperand(&I)) | |||
3110 | continue; | |||
3111 | ||||
3112 | // Ignore users that are part of a SCEV expression. This way we only | |||
3113 | // consider leaf IV Users. This effectively rediscovers a portion of | |||
3114 | // IVUsers analysis but in program order this time. | |||
3115 | if (SE.isSCEVable(I.getType()) && !isa<SCEVUnknown>(SE.getSCEV(&I))) | |||
3116 | continue; | |||
3117 | ||||
3118 | // Remove this instruction from any NearUsers set it may be in. | |||
3119 | for (unsigned ChainIdx = 0, NChains = IVChainVec.size(); | |||
3120 | ChainIdx < NChains; ++ChainIdx) { | |||
3121 | ChainUsersVec[ChainIdx].NearUsers.erase(&I); | |||
3122 | } | |||
3123 | // Search for operands that can be chained. | |||
3124 | SmallPtrSet<Instruction*, 4> UniqueOperands; | |||
3125 | User::op_iterator IVOpEnd = I.op_end(); | |||
3126 | User::op_iterator IVOpIter = findIVOperand(I.op_begin(), IVOpEnd, L, SE); | |||
3127 | while (IVOpIter != IVOpEnd) { | |||
3128 | Instruction *IVOpInst = cast<Instruction>(*IVOpIter); | |||
3129 | if (UniqueOperands.insert(IVOpInst).second) | |||
3130 | ChainInstruction(&I, IVOpInst, ChainUsersVec); | |||
3131 | IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE); | |||
3132 | } | |||
3133 | } // Continue walking down the instructions. | |||
3134 | } // Continue walking down the domtree. | |||
3135 | // Visit phi backedges to determine if the chain can generate the IV postinc. | |||
3136 | for (PHINode &PN : L->getHeader()->phis()) { | |||
3137 | if (!SE.isSCEVable(PN.getType())) | |||
3138 | continue; | |||
3139 | ||||
3140 | Instruction *IncV = | |||
3141 | dyn_cast<Instruction>(PN.getIncomingValueForBlock(L->getLoopLatch())); | |||
3142 | if (IncV) | |||
3143 | ChainInstruction(&PN, IncV, ChainUsersVec); | |||
3144 | } | |||
3145 | // Remove any unprofitable chains. | |||
3146 | unsigned ChainIdx = 0; | |||
3147 | for (unsigned UsersIdx = 0, NChains = IVChainVec.size(); | |||
3148 | UsersIdx < NChains; ++UsersIdx) { | |||
3149 | if (!isProfitableChain(IVChainVec[UsersIdx], | |||
3150 | ChainUsersVec[UsersIdx].FarUsers, SE, TTI)) | |||
3151 | continue; | |||
3152 | // Preserve the chain at UsesIdx. | |||
3153 | if (ChainIdx != UsersIdx) | |||
3154 | IVChainVec[ChainIdx] = IVChainVec[UsersIdx]; | |||
3155 | FinalizeChain(IVChainVec[ChainIdx]); | |||
3156 | ++ChainIdx; | |||
3157 | } | |||
3158 | IVChainVec.resize(ChainIdx); | |||
3159 | } | |||
3160 | ||||
3161 | void LSRInstance::FinalizeChain(IVChain &Chain) { | |||
3162 | assert(!Chain.Incs.empty() && "empty IV chains are not allowed")(static_cast <bool> (!Chain.Incs.empty() && "empty IV chains are not allowed" ) ? void (0) : __assert_fail ("!Chain.Incs.empty() && \"empty IV chains are not allowed\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 3162, __extension__ __PRETTY_FUNCTION__)); | |||
3163 | LLVM_DEBUG(dbgs() << "Final Chain: " << *Chain.Incs[0].UserInst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Final Chain: " << * Chain.Incs[0].UserInst << "\n"; } } while (false); | |||
3164 | ||||
3165 | for (const IVInc &Inc : Chain) { | |||
3166 | LLVM_DEBUG(dbgs() << " Inc: " << *Inc.UserInst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Inc: " << * Inc.UserInst << "\n"; } } while (false); | |||
3167 | auto UseI = find(Inc.UserInst->operands(), Inc.IVOperand); | |||
3168 | assert(UseI != Inc.UserInst->op_end() && "cannot find IV operand")(static_cast <bool> (UseI != Inc.UserInst->op_end() && "cannot find IV operand") ? void (0) : __assert_fail ("UseI != Inc.UserInst->op_end() && \"cannot find IV operand\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 3168, __extension__ __PRETTY_FUNCTION__)); | |||
3169 | IVIncSet.insert(UseI); | |||
3170 | } | |||
3171 | } | |||
3172 | ||||
3173 | /// Return true if the IVInc can be folded into an addressing mode. | |||
3174 | static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst, | |||
3175 | Value *Operand, const TargetTransformInfo &TTI) { | |||
3176 | const SCEVConstant *IncConst = dyn_cast<SCEVConstant>(IncExpr); | |||
3177 | if (!IncConst || !isAddressUse(TTI, UserInst, Operand)) | |||
3178 | return false; | |||
3179 | ||||
3180 | if (IncConst->getAPInt().getSignificantBits() > 64) | |||
3181 | return false; | |||
3182 | ||||
3183 | MemAccessTy AccessTy = getAccessType(TTI, UserInst, Operand); | |||
3184 | int64_t IncOffset = IncConst->getValue()->getSExtValue(); | |||
3185 | if (!isAlwaysFoldable(TTI, LSRUse::Address, AccessTy, /*BaseGV=*/nullptr, | |||
3186 | IncOffset, /*HasBaseReg=*/false)) | |||
3187 | return false; | |||
3188 | ||||
3189 | return true; | |||
3190 | } | |||
3191 | ||||
3192 | /// Generate an add or subtract for each IVInc in a chain to materialize the IV | |||
3193 | /// user's operand from the previous IV user's operand. | |||
3194 | void LSRInstance::GenerateIVChain(const IVChain &Chain, | |||
3195 | SmallVectorImpl<WeakTrackingVH> &DeadInsts) { | |||
3196 | // Find the new IVOperand for the head of the chain. It may have been replaced | |||
3197 | // by LSR. | |||
3198 | const IVInc &Head = Chain.Incs[0]; | |||
3199 | User::op_iterator IVOpEnd = Head.UserInst->op_end(); | |||
3200 | // findIVOperand returns IVOpEnd if it can no longer find a valid IV user. | |||
3201 | User::op_iterator IVOpIter = findIVOperand(Head.UserInst->op_begin(), | |||
3202 | IVOpEnd, L, SE); | |||
3203 | Value *IVSrc = nullptr; | |||
3204 | while (IVOpIter != IVOpEnd) { | |||
3205 | IVSrc = getWideOperand(*IVOpIter); | |||
3206 | ||||
3207 | // If this operand computes the expression that the chain needs, we may use | |||
3208 | // it. (Check this after setting IVSrc which is used below.) | |||
3209 | // | |||
3210 | // Note that if Head.IncExpr is wider than IVSrc, then this phi is too | |||
3211 | // narrow for the chain, so we can no longer use it. We do allow using a | |||
3212 | // wider phi, assuming the LSR checked for free truncation. In that case we | |||
3213 | // should already have a truncate on this operand such that | |||
3214 | // getSCEV(IVSrc) == IncExpr. | |||
3215 | if (SE.getSCEV(*IVOpIter) == Head.IncExpr | |||
3216 | || SE.getSCEV(IVSrc) == Head.IncExpr) { | |||
3217 | break; | |||
3218 | } | |||
3219 | IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE); | |||
3220 | } | |||
3221 | if (IVOpIter == IVOpEnd) { | |||
3222 | // Gracefully give up on this chain. | |||
3223 | LLVM_DEBUG(dbgs() << "Concealed chain head: " << *Head.UserInst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Concealed chain head: " << *Head.UserInst << "\n"; } } while (false); | |||
3224 | return; | |||
3225 | } | |||
3226 | assert(IVSrc && "Failed to find IV chain source")(static_cast <bool> (IVSrc && "Failed to find IV chain source" ) ? void (0) : __assert_fail ("IVSrc && \"Failed to find IV chain source\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 3226, __extension__ __PRETTY_FUNCTION__)); | |||
3227 | ||||
3228 | LLVM_DEBUG(dbgs() << "Generate chain at: " << *IVSrc << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Generate chain at: " << *IVSrc << "\n"; } } while (false); | |||
3229 | Type *IVTy = IVSrc->getType(); | |||
3230 | Type *IntTy = SE.getEffectiveSCEVType(IVTy); | |||
3231 | const SCEV *LeftOverExpr = nullptr; | |||
3232 | for (const IVInc &Inc : Chain) { | |||
3233 | Instruction *InsertPt = Inc.UserInst; | |||
3234 | if (isa<PHINode>(InsertPt)) | |||
3235 | InsertPt = L->getLoopLatch()->getTerminator(); | |||
3236 | ||||
3237 | // IVOper will replace the current IV User's operand. IVSrc is the IV | |||
3238 | // value currently held in a register. | |||
3239 | Value *IVOper = IVSrc; | |||
3240 | if (!Inc.IncExpr->isZero()) { | |||
3241 | // IncExpr was the result of subtraction of two narrow values, so must | |||
3242 | // be signed. | |||
3243 | const SCEV *IncExpr = SE.getNoopOrSignExtend(Inc.IncExpr, IntTy); | |||
3244 | LeftOverExpr = LeftOverExpr ? | |||
3245 | SE.getAddExpr(LeftOverExpr, IncExpr) : IncExpr; | |||
3246 | } | |||
3247 | if (LeftOverExpr && !LeftOverExpr->isZero()) { | |||
3248 | // Expand the IV increment. | |||
3249 | Rewriter.clearPostInc(); | |||
3250 | Value *IncV = Rewriter.expandCodeFor(LeftOverExpr, IntTy, InsertPt); | |||
3251 | const SCEV *IVOperExpr = SE.getAddExpr(SE.getUnknown(IVSrc), | |||
3252 | SE.getUnknown(IncV)); | |||
3253 | IVOper = Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt); | |||
3254 | ||||
3255 | // If an IV increment can't be folded, use it as the next IV value. | |||
3256 | if (!canFoldIVIncExpr(LeftOverExpr, Inc.UserInst, Inc.IVOperand, TTI)) { | |||
3257 | assert(IVTy == IVOper->getType() && "inconsistent IV increment type")(static_cast <bool> (IVTy == IVOper->getType() && "inconsistent IV increment type") ? void (0) : __assert_fail ("IVTy == IVOper->getType() && \"inconsistent IV increment type\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 3257, __extension__ __PRETTY_FUNCTION__)); | |||
3258 | IVSrc = IVOper; | |||
3259 | LeftOverExpr = nullptr; | |||
3260 | } | |||
3261 | } | |||
3262 | Type *OperTy = Inc.IVOperand->getType(); | |||
3263 | if (IVTy != OperTy) { | |||
3264 | assert(SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) &&(static_cast <bool> (SE.getTypeSizeInBits(IVTy) >= SE .getTypeSizeInBits(OperTy) && "cannot extend a chained IV" ) ? void (0) : __assert_fail ("SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) && \"cannot extend a chained IV\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 3265, __extension__ __PRETTY_FUNCTION__)) | |||
3265 | "cannot extend a chained IV")(static_cast <bool> (SE.getTypeSizeInBits(IVTy) >= SE .getTypeSizeInBits(OperTy) && "cannot extend a chained IV" ) ? void (0) : __assert_fail ("SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) && \"cannot extend a chained IV\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 3265, __extension__ __PRETTY_FUNCTION__)); | |||
3266 | IRBuilder<> Builder(InsertPt); | |||
3267 | IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy, "lsr.chain"); | |||
3268 | } | |||
3269 | Inc.UserInst->replaceUsesOfWith(Inc.IVOperand, IVOper); | |||
3270 | if (auto *OperandIsInstr = dyn_cast<Instruction>(Inc.IVOperand)) | |||
3271 | DeadInsts.emplace_back(OperandIsInstr); | |||
3272 | } | |||
3273 | // If LSR created a new, wider phi, we may also replace its postinc. We only | |||
3274 | // do this if we also found a wide value for the head of the chain. | |||
3275 | if (isa<PHINode>(Chain.tailUserInst())) { | |||
3276 | for (PHINode &Phi : L->getHeader()->phis()) { | |||
3277 | if (!isCompatibleIVType(&Phi, IVSrc)) | |||
3278 | continue; | |||
3279 | Instruction *PostIncV = dyn_cast<Instruction>( | |||
3280 | Phi.getIncomingValueForBlock(L->getLoopLatch())); | |||
3281 | if (!PostIncV || (SE.getSCEV(PostIncV) != SE.getSCEV(IVSrc))) | |||
3282 | continue; | |||
3283 | Value *IVOper = IVSrc; | |||
3284 | Type *PostIncTy = PostIncV->getType(); | |||
3285 | if (IVTy != PostIncTy) { | |||
3286 | assert(PostIncTy->isPointerTy() && "mixing int/ptr IV types")(static_cast <bool> (PostIncTy->isPointerTy() && "mixing int/ptr IV types") ? void (0) : __assert_fail ("PostIncTy->isPointerTy() && \"mixing int/ptr IV types\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 3286, __extension__ __PRETTY_FUNCTION__)); | |||
3287 | IRBuilder<> Builder(L->getLoopLatch()->getTerminator()); | |||
3288 | Builder.SetCurrentDebugLocation(PostIncV->getDebugLoc()); | |||
3289 | IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy, "lsr.chain"); | |||
3290 | } | |||
3291 | Phi.replaceUsesOfWith(PostIncV, IVOper); | |||
3292 | DeadInsts.emplace_back(PostIncV); | |||
3293 | } | |||
3294 | } | |||
3295 | } | |||
3296 | ||||
3297 | void LSRInstance::CollectFixupsAndInitialFormulae() { | |||
3298 | BranchInst *ExitBranch = nullptr; | |||
3299 | bool SaveCmp = TTI.canSaveCmp(L, &ExitBranch, &SE, &LI, &DT, &AC, &TLI); | |||
3300 | ||||
3301 | // For calculating baseline cost | |||
3302 | SmallPtrSet<const SCEV *, 16> Regs; | |||
3303 | DenseSet<const SCEV *> VisitedRegs; | |||
3304 | DenseSet<size_t> VisitedLSRUse; | |||
3305 | ||||
3306 | for (const IVStrideUse &U : IU) { | |||
3307 | Instruction *UserInst = U.getUser(); | |||
3308 | // Skip IV users that are part of profitable IV Chains. | |||
3309 | User::op_iterator UseI = | |||
3310 | find(UserInst->operands(), U.getOperandValToReplace()); | |||
3311 | assert(UseI != UserInst->op_end() && "cannot find IV operand")(static_cast <bool> (UseI != UserInst->op_end() && "cannot find IV operand") ? void (0) : __assert_fail ("UseI != UserInst->op_end() && \"cannot find IV operand\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 3311, __extension__ __PRETTY_FUNCTION__)); | |||
3312 | if (IVIncSet.count(UseI)) { | |||
3313 | LLVM_DEBUG(dbgs() << "Use is in profitable chain: " << **UseI << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Use is in profitable chain: " << **UseI << '\n'; } } while (false); | |||
3314 | continue; | |||
3315 | } | |||
3316 | ||||
3317 | LSRUse::KindType Kind = LSRUse::Basic; | |||
3318 | MemAccessTy AccessTy; | |||
3319 | if (isAddressUse(TTI, UserInst, U.getOperandValToReplace())) { | |||
3320 | Kind = LSRUse::Address; | |||
3321 | AccessTy = getAccessType(TTI, UserInst, U.getOperandValToReplace()); | |||
3322 | } | |||
3323 | ||||
3324 | const SCEV *S = IU.getExpr(U); | |||
3325 | PostIncLoopSet TmpPostIncLoops = U.getPostIncLoops(); | |||
3326 | ||||
3327 | // Equality (== and !=) ICmps are special. We can rewrite (i == N) as | |||
3328 | // (N - i == 0), and this allows (N - i) to be the expression that we work | |||
3329 | // with rather than just N or i, so we can consider the register | |||
3330 | // requirements for both N and i at the same time. Limiting this code to | |||
3331 | // equality icmps is not a problem because all interesting loops use | |||
3332 | // equality icmps, thanks to IndVarSimplify. | |||
3333 | if (ICmpInst *CI = dyn_cast<ICmpInst>(UserInst)) { | |||
3334 | // If CI can be saved in some target, like replaced inside hardware loop | |||
3335 | // in PowerPC, no need to generate initial formulae for it. | |||
3336 | if (SaveCmp && CI == dyn_cast<ICmpInst>(ExitBranch->getCondition())) | |||
3337 | continue; | |||
3338 | if (CI->isEquality()) { | |||
3339 | // Swap the operands if needed to put the OperandValToReplace on the | |||
3340 | // left, for consistency. | |||
3341 | Value *NV = CI->getOperand(1); | |||
3342 | if (NV == U.getOperandValToReplace()) { | |||
3343 | CI->setOperand(1, CI->getOperand(0)); | |||
3344 | CI->setOperand(0, NV); | |||
3345 | NV = CI->getOperand(1); | |||
3346 | Changed = true; | |||
3347 | } | |||
3348 | ||||
3349 | // x == y --> x - y == 0 | |||
3350 | const SCEV *N = SE.getSCEV(NV); | |||
3351 | if (SE.isLoopInvariant(N, L) && Rewriter.isSafeToExpand(N) && | |||
3352 | (!NV->getType()->isPointerTy() || | |||
3353 | SE.getPointerBase(N) == SE.getPointerBase(S))) { | |||
3354 | // S is normalized, so normalize N before folding it into S | |||
3355 | // to keep the result normalized. | |||
3356 | N = normalizeForPostIncUse(N, TmpPostIncLoops, SE); | |||
3357 | Kind = LSRUse::ICmpZero; | |||
3358 | S = SE.getMinusSCEV(N, S); | |||
3359 | } else if (L->isLoopInvariant(NV) && | |||
3360 | (!isa<Instruction>(NV) || | |||
3361 | DT.dominates(cast<Instruction>(NV), L->getHeader())) && | |||
3362 | !NV->getType()->isPointerTy()) { | |||
3363 | // If we can't generally expand the expression (e.g. it contains | |||
3364 | // a divide), but it is already at a loop invariant point before the | |||
3365 | // loop, wrap it in an unknown (to prevent the expander from trying | |||
3366 | // to re-expand in a potentially unsafe way.) The restriction to | |||
3367 | // integer types is required because the unknown hides the base, and | |||
3368 | // SCEV can't compute the difference of two unknown pointers. | |||
3369 | N = SE.getUnknown(NV); | |||
3370 | N = normalizeForPostIncUse(N, TmpPostIncLoops, SE); | |||
3371 | Kind = LSRUse::ICmpZero; | |||
3372 | S = SE.getMinusSCEV(N, S); | |||
3373 | assert(!isa<SCEVCouldNotCompute>(S))(static_cast <bool> (!isa<SCEVCouldNotCompute>(S) ) ? void (0) : __assert_fail ("!isa<SCEVCouldNotCompute>(S)" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 3373, __extension__ __PRETTY_FUNCTION__)); | |||
3374 | } | |||
3375 | ||||
3376 | // -1 and the negations of all interesting strides (except the negation | |||
3377 | // of -1) are now also interesting. | |||
3378 | for (size_t i = 0, e = Factors.size(); i != e; ++i) | |||
3379 | if (Factors[i] != -1) | |||
3380 | Factors.insert(-(uint64_t)Factors[i]); | |||
3381 | Factors.insert(-1); | |||
3382 | } | |||
3383 | } | |||
3384 | ||||
3385 | // Get or create an LSRUse. | |||
3386 | std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy); | |||
3387 | size_t LUIdx = P.first; | |||
3388 | int64_t Offset = P.second; | |||
3389 | LSRUse &LU = Uses[LUIdx]; | |||
3390 | ||||
3391 | // Record the fixup. | |||
3392 | LSRFixup &LF = LU.getNewFixup(); | |||
3393 | LF.UserInst = UserInst; | |||
3394 | LF.OperandValToReplace = U.getOperandValToReplace(); | |||
3395 | LF.PostIncLoops = TmpPostIncLoops; | |||
3396 | LF.Offset = Offset; | |||
3397 | LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L); | |||
3398 | ||||
3399 | // Create SCEV as Formula for calculating baseline cost | |||
3400 | if (!VisitedLSRUse.count(LUIdx) && !LF.isUseFullyOutsideLoop(L)) { | |||
3401 | Formula F; | |||
3402 | F.initialMatch(S, L, SE); | |||
3403 | BaselineCost.RateFormula(F, Regs, VisitedRegs, LU); | |||
3404 | VisitedLSRUse.insert(LUIdx); | |||
3405 | } | |||
3406 | ||||
3407 | if (!LU.WidestFixupType || | |||
3408 | SE.getTypeSizeInBits(LU.WidestFixupType) < | |||
3409 | SE.getTypeSizeInBits(LF.OperandValToReplace->getType())) | |||
3410 | LU.WidestFixupType = LF.OperandValToReplace->getType(); | |||
3411 | ||||
3412 | // If this is the first use of this LSRUse, give it a formula. | |||
3413 | if (LU.Formulae.empty()) { | |||
3414 | InsertInitialFormula(S, LU, LUIdx); | |||
3415 | CountRegisters(LU.Formulae.back(), LUIdx); | |||
3416 | } | |||
3417 | } | |||
3418 | ||||
3419 | LLVM_DEBUG(print_fixups(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { print_fixups(dbgs()); } } while (false); | |||
3420 | } | |||
3421 | ||||
3422 | /// Insert a formula for the given expression into the given use, separating out | |||
3423 | /// loop-variant portions from loop-invariant and loop-computable portions. | |||
3424 | void LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, | |||
3425 | size_t LUIdx) { | |||
3426 | // Mark uses whose expressions cannot be expanded. | |||
3427 | if (!Rewriter.isSafeToExpand(S)) | |||
3428 | LU.RigidFormula = true; | |||
3429 | ||||
3430 | Formula F; | |||
3431 | F.initialMatch(S, L, SE); | |||
3432 | bool Inserted = InsertFormula(LU, LUIdx, F); | |||
3433 | assert(Inserted && "Initial formula already exists!")(static_cast <bool> (Inserted && "Initial formula already exists!" ) ? void (0) : __assert_fail ("Inserted && \"Initial formula already exists!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 3433, __extension__ __PRETTY_FUNCTION__)); (void)Inserted; | |||
3434 | } | |||
3435 | ||||
3436 | /// Insert a simple single-register formula for the given expression into the | |||
3437 | /// given use. | |||
3438 | void | |||
3439 | LSRInstance::InsertSupplementalFormula(const SCEV *S, | |||
3440 | LSRUse &LU, size_t LUIdx) { | |||
3441 | Formula F; | |||
3442 | F.BaseRegs.push_back(S); | |||
3443 | F.HasBaseReg = true; | |||
3444 | bool Inserted = InsertFormula(LU, LUIdx, F); | |||
3445 | assert(Inserted && "Supplemental formula already exists!")(static_cast <bool> (Inserted && "Supplemental formula already exists!" ) ? void (0) : __assert_fail ("Inserted && \"Supplemental formula already exists!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 3445, __extension__ __PRETTY_FUNCTION__)); (void)Inserted; | |||
3446 | } | |||
3447 | ||||
3448 | /// Note which registers are used by the given formula, updating RegUses. | |||
3449 | void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) { | |||
3450 | if (F.ScaledReg) | |||
3451 | RegUses.countRegister(F.ScaledReg, LUIdx); | |||
3452 | for (const SCEV *BaseReg : F.BaseRegs) | |||
3453 | RegUses.countRegister(BaseReg, LUIdx); | |||
3454 | } | |||
3455 | ||||
3456 | /// If the given formula has not yet been inserted, add it to the list, and | |||
3457 | /// return true. Return false otherwise. | |||
3458 | bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) { | |||
3459 | // Do not insert formula that we will not be able to expand. | |||
3460 | assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) &&(static_cast <bool> (isLegalUse(TTI, LU.MinOffset, LU.MaxOffset , LU.Kind, LU.AccessTy, F) && "Formula is illegal") ? void (0) : __assert_fail ("isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) && \"Formula is illegal\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 3461, __extension__ __PRETTY_FUNCTION__)) | |||
3461 | "Formula is illegal")(static_cast <bool> (isLegalUse(TTI, LU.MinOffset, LU.MaxOffset , LU.Kind, LU.AccessTy, F) && "Formula is illegal") ? void (0) : __assert_fail ("isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) && \"Formula is illegal\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 3461, __extension__ __PRETTY_FUNCTION__)); | |||
3462 | ||||
3463 | if (!LU.InsertFormula(F, *L)) | |||
3464 | return false; | |||
3465 | ||||
3466 | CountRegisters(F, LUIdx); | |||
3467 | return true; | |||
3468 | } | |||
3469 | ||||
3470 | /// Check for other uses of loop-invariant values which we're tracking. These | |||
3471 | /// other uses will pin these values in registers, making them less profitable | |||
3472 | /// for elimination. | |||
3473 | /// TODO: This currently misses non-constant addrec step registers. | |||
3474 | /// TODO: Should this give more weight to users inside the loop? | |||
3475 | void | |||
3476 | LSRInstance::CollectLoopInvariantFixupsAndFormulae() { | |||
3477 | SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end()); | |||
3478 | SmallPtrSet<const SCEV *, 32> Visited; | |||
3479 | ||||
3480 | while (!Worklist.empty()) { | |||
3481 | const SCEV *S = Worklist.pop_back_val(); | |||
3482 | ||||
3483 | // Don't process the same SCEV twice | |||
3484 | if (!Visited.insert(S).second) | |||
3485 | continue; | |||
3486 | ||||
3487 | if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S)) | |||
3488 | append_range(Worklist, N->operands()); | |||
3489 | else if (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(S)) | |||
3490 | Worklist.push_back(C->getOperand()); | |||
3491 | else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) { | |||
3492 | Worklist.push_back(D->getLHS()); | |||
3493 | Worklist.push_back(D->getRHS()); | |||
3494 | } else if (const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) { | |||
3495 | const Value *V = US->getValue(); | |||
3496 | if (const Instruction *Inst = dyn_cast<Instruction>(V)) { | |||
3497 | // Look for instructions defined outside the loop. | |||
3498 | if (L->contains(Inst)) continue; | |||
3499 | } else if (isa<UndefValue>(V)) | |||
3500 | // Undef doesn't have a live range, so it doesn't matter. | |||
3501 | continue; | |||
3502 | for (const Use &U : V->uses()) { | |||
3503 | const Instruction *UserInst = dyn_cast<Instruction>(U.getUser()); | |||
3504 | // Ignore non-instructions. | |||
3505 | if (!UserInst) | |||
3506 | continue; | |||
3507 | // Don't bother if the instruction is an EHPad. | |||
3508 | if (UserInst->isEHPad()) | |||
3509 | continue; | |||
3510 | // Ignore instructions in other functions (as can happen with | |||
3511 | // Constants). | |||
3512 | if (UserInst->getParent()->getParent() != L->getHeader()->getParent()) | |||
3513 | continue; | |||
3514 | // Ignore instructions not dominated by the loop. | |||
3515 | const BasicBlock *UseBB = !isa<PHINode>(UserInst) ? | |||
3516 | UserInst->getParent() : | |||
3517 | cast<PHINode>(UserInst)->getIncomingBlock( | |||
3518 | PHINode::getIncomingValueNumForOperand(U.getOperandNo())); | |||
3519 | if (!DT.dominates(L->getHeader(), UseBB)) | |||
3520 | continue; | |||
3521 | // Don't bother if the instruction is in a BB which ends in an EHPad. | |||
3522 | if (UseBB->getTerminator()->isEHPad()) | |||
3523 | continue; | |||
3524 | ||||
3525 | // Ignore cases in which the currently-examined value could come from | |||
3526 | // a basic block terminated with an EHPad. This checks all incoming | |||
3527 | // blocks of the phi node since it is possible that the same incoming | |||
3528 | // value comes from multiple basic blocks, only some of which may end | |||
3529 | // in an EHPad. If any of them do, a subsequent rewrite attempt by this | |||
3530 | // pass would try to insert instructions into an EHPad, hitting an | |||
3531 | // assertion. | |||
3532 | if (isa<PHINode>(UserInst)) { | |||
3533 | const auto *PhiNode = cast<PHINode>(UserInst); | |||
3534 | bool HasIncompatibleEHPTerminatedBlock = false; | |||
3535 | llvm::Value *ExpectedValue = U; | |||
3536 | for (unsigned int I = 0; I < PhiNode->getNumIncomingValues(); I++) { | |||
3537 | if (PhiNode->getIncomingValue(I) == ExpectedValue) { | |||
3538 | if (PhiNode->getIncomingBlock(I)->getTerminator()->isEHPad()) { | |||
3539 | HasIncompatibleEHPTerminatedBlock = true; | |||
3540 | break; | |||
3541 | } | |||
3542 | } | |||
3543 | } | |||
3544 | if (HasIncompatibleEHPTerminatedBlock) { | |||
3545 | continue; | |||
3546 | } | |||
3547 | } | |||
3548 | ||||
3549 | // Don't bother rewriting PHIs in catchswitch blocks. | |||
3550 | if (isa<CatchSwitchInst>(UserInst->getParent()->getTerminator())) | |||
3551 | continue; | |||
3552 | // Ignore uses which are part of other SCEV expressions, to avoid | |||
3553 | // analyzing them multiple times. | |||
3554 | if (SE.isSCEVable(UserInst->getType())) { | |||
3555 | const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst)); | |||
3556 | // If the user is a no-op, look through to its uses. | |||
3557 | if (!isa<SCEVUnknown>(UserS)) | |||
3558 | continue; | |||
3559 | if (UserS == US) { | |||
3560 | Worklist.push_back( | |||
3561 | SE.getUnknown(const_cast<Instruction *>(UserInst))); | |||
3562 | continue; | |||
3563 | } | |||
3564 | } | |||
3565 | // Ignore icmp instructions which are already being analyzed. | |||
3566 | if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) { | |||
3567 | unsigned OtherIdx = !U.getOperandNo(); | |||
3568 | Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx)); | |||
3569 | if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L)) | |||
3570 | continue; | |||
3571 | } | |||
3572 | ||||
3573 | std::pair<size_t, int64_t> P = getUse( | |||
3574 | S, LSRUse::Basic, MemAccessTy()); | |||
3575 | size_t LUIdx = P.first; | |||
3576 | int64_t Offset = P.second; | |||
3577 | LSRUse &LU = Uses[LUIdx]; | |||
3578 | LSRFixup &LF = LU.getNewFixup(); | |||
3579 | LF.UserInst = const_cast<Instruction *>(UserInst); | |||
3580 | LF.OperandValToReplace = U; | |||
3581 | LF.Offset = Offset; | |||
3582 | LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L); | |||
3583 | if (!LU.WidestFixupType || | |||
3584 | SE.getTypeSizeInBits(LU.WidestFixupType) < | |||
3585 | SE.getTypeSizeInBits(LF.OperandValToReplace->getType())) | |||
3586 | LU.WidestFixupType = LF.OperandValToReplace->getType(); | |||
3587 | InsertSupplementalFormula(US, LU, LUIdx); | |||
3588 | CountRegisters(LU.Formulae.back(), Uses.size() - 1); | |||
3589 | break; | |||
3590 | } | |||
3591 | } | |||
3592 | } | |||
3593 | } | |||
3594 | ||||
3595 | /// Split S into subexpressions which can be pulled out into separate | |||
3596 | /// registers. If C is non-null, multiply each subexpression by C. | |||
3597 | /// | |||
3598 | /// Return remainder expression after factoring the subexpressions captured by | |||
3599 | /// Ops. If Ops is complete, return NULL. | |||
3600 | static const SCEV *CollectSubexprs(const SCEV *S, const SCEVConstant *C, | |||
3601 | SmallVectorImpl<const SCEV *> &Ops, | |||
3602 | const Loop *L, | |||
3603 | ScalarEvolution &SE, | |||
3604 | unsigned Depth = 0) { | |||
3605 | // Arbitrarily cap recursion to protect compile time. | |||
3606 | if (Depth >= 3) | |||
3607 | return S; | |||
3608 | ||||
3609 | if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) { | |||
3610 | // Break out add operands. | |||
3611 | for (const SCEV *S : Add->operands()) { | |||
3612 | const SCEV *Remainder = CollectSubexprs(S, C, Ops, L, SE, Depth+1); | |||
3613 | if (Remainder) | |||
3614 | Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder); | |||
3615 | } | |||
3616 | return nullptr; | |||
3617 | } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) { | |||
3618 | // Split a non-zero base out of an addrec. | |||
3619 | if (AR->getStart()->isZero() || !AR->isAffine()) | |||
3620 | return S; | |||
3621 | ||||
3622 | const SCEV *Remainder = CollectSubexprs(AR->getStart(), | |||
3623 | C, Ops, L, SE, Depth+1); | |||
3624 | // Split the non-zero AddRec unless it is part of a nested recurrence that | |||
3625 | // does not pertain to this loop. | |||
3626 | if (Remainder && (AR->getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) { | |||
3627 | Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder); | |||
3628 | Remainder = nullptr; | |||
3629 | } | |||
3630 | if (Remainder != AR->getStart()) { | |||
3631 | if (!Remainder) | |||
3632 | Remainder = SE.getConstant(AR->getType(), 0); | |||
3633 | return SE.getAddRecExpr(Remainder, | |||
3634 | AR->getStepRecurrence(SE), | |||
3635 | AR->getLoop(), | |||
3636 | //FIXME: AR->getNoWrapFlags(SCEV::FlagNW) | |||
3637 | SCEV::FlagAnyWrap); | |||
3638 | } | |||
3639 | } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) { | |||
3640 | // Break (C * (a + b + c)) into C*a + C*b + C*c. | |||
3641 | if (Mul->getNumOperands() != 2) | |||
3642 | return S; | |||
3643 | if (const SCEVConstant *Op0 = | |||
3644 | dyn_cast<SCEVConstant>(Mul->getOperand(0))) { | |||
3645 | C = C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0; | |||
3646 | const SCEV *Remainder = | |||
3647 | CollectSubexprs(Mul->getOperand(1), C, Ops, L, SE, Depth+1); | |||
3648 | if (Remainder) | |||
3649 | Ops.push_back(SE.getMulExpr(C, Remainder)); | |||
3650 | return nullptr; | |||
3651 | } | |||
3652 | } | |||
3653 | return S; | |||
3654 | } | |||
3655 | ||||
3656 | /// Return true if the SCEV represents a value that may end up as a | |||
3657 | /// post-increment operation. | |||
3658 | static bool mayUsePostIncMode(const TargetTransformInfo &TTI, | |||
3659 | LSRUse &LU, const SCEV *S, const Loop *L, | |||
3660 | ScalarEvolution &SE) { | |||
3661 | if (LU.Kind != LSRUse::Address || | |||
3662 | !LU.AccessTy.getType()->isIntOrIntVectorTy()) | |||
3663 | return false; | |||
3664 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S); | |||
3665 | if (!AR) | |||
3666 | return false; | |||
3667 | const SCEV *LoopStep = AR->getStepRecurrence(SE); | |||
3668 | if (!isa<SCEVConstant>(LoopStep)) | |||
3669 | return false; | |||
3670 | // Check if a post-indexed load/store can be used. | |||
3671 | if (TTI.isIndexedLoadLegal(TTI.MIM_PostInc, AR->getType()) || | |||
3672 | TTI.isIndexedStoreLegal(TTI.MIM_PostInc, AR->getType())) { | |||
3673 | const SCEV *LoopStart = AR->getStart(); | |||
3674 | if (!isa<SCEVConstant>(LoopStart) && SE.isLoopInvariant(LoopStart, L)) | |||
3675 | return true; | |||
3676 | } | |||
3677 | return false; | |||
3678 | } | |||
3679 | ||||
3680 | /// Helper function for LSRInstance::GenerateReassociations. | |||
3681 | void LSRInstance::GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx, | |||
3682 | const Formula &Base, | |||
3683 | unsigned Depth, size_t Idx, | |||
3684 | bool IsScaledReg) { | |||
3685 | const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx]; | |||
3686 | // Don't generate reassociations for the base register of a value that | |||
3687 | // may generate a post-increment operator. The reason is that the | |||
3688 | // reassociations cause extra base+register formula to be created, | |||
3689 | // and possibly chosen, but the post-increment is more efficient. | |||
3690 | if (AMK == TTI::AMK_PostIndexed && mayUsePostIncMode(TTI, LU, BaseReg, L, SE)) | |||
3691 | return; | |||
3692 | SmallVector<const SCEV *, 8> AddOps; | |||
3693 | const SCEV *Remainder = CollectSubexprs(BaseReg, nullptr, AddOps, L, SE); | |||
3694 | if (Remainder) | |||
3695 | AddOps.push_back(Remainder); | |||
3696 | ||||
3697 | if (AddOps.size() == 1) | |||
3698 | return; | |||
3699 | ||||
3700 | for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(), | |||
3701 | JE = AddOps.end(); | |||
3702 | J != JE; ++J) { | |||
3703 | // Loop-variant "unknown" values are uninteresting; we won't be able to | |||
3704 | // do anything meaningful with them. | |||
3705 | if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L)) | |||
3706 | continue; | |||
3707 | ||||
3708 | // Don't pull a constant into a register if the constant could be folded | |||
3709 | // into an immediate field. | |||
3710 | if (isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind, | |||
3711 | LU.AccessTy, *J, Base.getNumRegs() > 1)) | |||
3712 | continue; | |||
3713 | ||||
3714 | // Collect all operands except *J. | |||
3715 | SmallVector<const SCEV *, 8> InnerAddOps( | |||
3716 | ((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J); | |||
3717 | InnerAddOps.append(std::next(J), | |||
3718 | ((const SmallVector<const SCEV *, 8> &)AddOps).end()); | |||
3719 | ||||
3720 | // Don't leave just a constant behind in a register if the constant could | |||
3721 | // be folded into an immediate field. | |||
3722 | if (InnerAddOps.size() == 1 && | |||
3723 | isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind, | |||
3724 | LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1)) | |||
3725 | continue; | |||
3726 | ||||
3727 | const SCEV *InnerSum = SE.getAddExpr(InnerAddOps); | |||
3728 | if (InnerSum->isZero()) | |||
3729 | continue; | |||
3730 | Formula F = Base; | |||
3731 | ||||
3732 | // Add the remaining pieces of the add back into the new formula. | |||
3733 | const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(InnerSum); | |||
3734 | if (InnerSumSC && SE.getTypeSizeInBits(InnerSumSC->getType()) <= 64 && | |||
3735 | TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset + | |||
3736 | InnerSumSC->getValue()->getZExtValue())) { | |||
3737 | F.UnfoldedOffset = | |||
3738 | (uint64_t)F.UnfoldedOffset + InnerSumSC->getValue()->getZExtValue(); | |||
3739 | if (IsScaledReg) | |||
3740 | F.ScaledReg = nullptr; | |||
3741 | else | |||
3742 | F.BaseRegs.erase(F.BaseRegs.begin() + Idx); | |||
3743 | } else if (IsScaledReg) | |||
3744 | F.ScaledReg = InnerSum; | |||
3745 | else | |||
3746 | F.BaseRegs[Idx] = InnerSum; | |||
3747 | ||||
3748 | // Add J as its own register, or an unfolded immediate. | |||
3749 | const SCEVConstant *SC = dyn_cast<SCEVConstant>(*J); | |||
3750 | if (SC && SE.getTypeSizeInBits(SC->getType()) <= 64 && | |||
3751 | TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset + | |||
3752 | SC->getValue()->getZExtValue())) | |||
3753 | F.UnfoldedOffset = | |||
3754 | (uint64_t)F.UnfoldedOffset + SC->getValue()->getZExtValue(); | |||
3755 | else | |||
3756 | F.BaseRegs.push_back(*J); | |||
3757 | // We may have changed the number of register in base regs, adjust the | |||
3758 | // formula accordingly. | |||
3759 | F.canonicalize(*L); | |||
3760 | ||||
3761 | if (InsertFormula(LU, LUIdx, F)) | |||
3762 | // If that formula hadn't been seen before, recurse to find more like | |||
3763 | // it. | |||
3764 | // Add check on Log16(AddOps.size()) - same as Log2_32(AddOps.size()) >> 2) | |||
3765 | // Because just Depth is not enough to bound compile time. | |||
3766 | // This means that every time AddOps.size() is greater 16^x we will add | |||
3767 | // x to Depth. | |||
3768 | GenerateReassociations(LU, LUIdx, LU.Formulae.back(), | |||
3769 | Depth + 1 + (Log2_32(AddOps.size()) >> 2)); | |||
3770 | } | |||
3771 | } | |||
3772 | ||||
3773 | /// Split out subexpressions from adds and the bases of addrecs. | |||
3774 | void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx, | |||
3775 | Formula Base, unsigned Depth) { | |||
3776 | assert(Base.isCanonical(*L) && "Input must be in the canonical form")(static_cast <bool> (Base.isCanonical(*L) && "Input must be in the canonical form" ) ? void (0) : __assert_fail ("Base.isCanonical(*L) && \"Input must be in the canonical form\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 3776, __extension__ __PRETTY_FUNCTION__)); | |||
3777 | // Arbitrarily cap recursion to protect compile time. | |||
3778 | if (Depth >= 3) | |||
3779 | return; | |||
3780 | ||||
3781 | for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) | |||
3782 | GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i); | |||
3783 | ||||
3784 | if (Base.Scale == 1) | |||
3785 | GenerateReassociationsImpl(LU, LUIdx, Base, Depth, | |||
3786 | /* Idx */ -1, /* IsScaledReg */ true); | |||
3787 | } | |||
3788 | ||||
3789 | /// Generate a formula consisting of all of the loop-dominating registers added | |||
3790 | /// into a single register. | |||
3791 | void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx, | |||
3792 | Formula Base) { | |||
3793 | // This method is only interesting on a plurality of registers. | |||
3794 | if (Base.BaseRegs.size() + (Base.Scale == 1) + | |||
3795 | (Base.UnfoldedOffset != 0) <= 1) | |||
3796 | return; | |||
3797 | ||||
3798 | // Flatten the representation, i.e., reg1 + 1*reg2 => reg1 + reg2, before | |||
3799 | // processing the formula. | |||
3800 | Base.unscale(); | |||
3801 | SmallVector<const SCEV *, 4> Ops; | |||
3802 | Formula NewBase = Base; | |||
3803 | NewBase.BaseRegs.clear(); | |||
3804 | Type *CombinedIntegerType = nullptr; | |||
3805 | for (const SCEV *BaseReg : Base.BaseRegs) { | |||
3806 | if (SE.properlyDominates(BaseReg, L->getHeader()) && | |||
3807 | !SE.hasComputableLoopEvolution(BaseReg, L)) { | |||
3808 | if (!CombinedIntegerType) | |||
3809 | CombinedIntegerType = SE.getEffectiveSCEVType(BaseReg->getType()); | |||
3810 | Ops.push_back(BaseReg); | |||
3811 | } | |||
3812 | else | |||
3813 | NewBase.BaseRegs.push_back(BaseReg); | |||
3814 | } | |||
3815 | ||||
3816 | // If no register is relevant, we're done. | |||
3817 | if (Ops.size() == 0) | |||
3818 | return; | |||
3819 | ||||
3820 | // Utility function for generating the required variants of the combined | |||
3821 | // registers. | |||
3822 | auto GenerateFormula = [&](const SCEV *Sum) { | |||
3823 | Formula F = NewBase; | |||
3824 | ||||
3825 | // TODO: If Sum is zero, it probably means ScalarEvolution missed an | |||
3826 | // opportunity to fold something. For now, just ignore such cases | |||
3827 | // rather than proceed with zero in a register. | |||
3828 | if (Sum->isZero()) | |||
3829 | return; | |||
3830 | ||||
3831 | F.BaseRegs.push_back(Sum); | |||
3832 | F.canonicalize(*L); | |||
3833 | (void)InsertFormula(LU, LUIdx, F); | |||
3834 | }; | |||
3835 | ||||
3836 | // If we collected at least two registers, generate a formula combining them. | |||
3837 | if (Ops.size() > 1) { | |||
3838 | SmallVector<const SCEV *, 4> OpsCopy(Ops); // Don't let SE modify Ops. | |||
3839 | GenerateFormula(SE.getAddExpr(OpsCopy)); | |||
3840 | } | |||
3841 | ||||
3842 | // If we have an unfolded offset, generate a formula combining it with the | |||
3843 | // registers collected. | |||
3844 | if (NewBase.UnfoldedOffset) { | |||
3845 | assert(CombinedIntegerType && "Missing a type for the unfolded offset")(static_cast <bool> (CombinedIntegerType && "Missing a type for the unfolded offset" ) ? void (0) : __assert_fail ("CombinedIntegerType && \"Missing a type for the unfolded offset\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 3845, __extension__ __PRETTY_FUNCTION__)); | |||
3846 | Ops.push_back(SE.getConstant(CombinedIntegerType, NewBase.UnfoldedOffset, | |||
3847 | true)); | |||
3848 | NewBase.UnfoldedOffset = 0; | |||
3849 | GenerateFormula(SE.getAddExpr(Ops)); | |||
3850 | } | |||
3851 | } | |||
3852 | ||||
3853 | /// Helper function for LSRInstance::GenerateSymbolicOffsets. | |||
3854 | void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx, | |||
3855 | const Formula &Base, size_t Idx, | |||
3856 | bool IsScaledReg) { | |||
3857 | const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx]; | |||
3858 | GlobalValue *GV = ExtractSymbol(G, SE); | |||
3859 | if (G->isZero() || !GV) | |||
3860 | return; | |||
3861 | Formula F = Base; | |||
3862 | F.BaseGV = GV; | |||
3863 | if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F)) | |||
3864 | return; | |||
3865 | if (IsScaledReg) | |||
3866 | F.ScaledReg = G; | |||
3867 | else | |||
3868 | F.BaseRegs[Idx] = G; | |||
3869 | (void)InsertFormula(LU, LUIdx, F); | |||
3870 | } | |||
3871 | ||||
3872 | /// Generate reuse formulae using symbolic offsets. | |||
3873 | void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, | |||
3874 | Formula Base) { | |||
3875 | // We can't add a symbolic offset if the address already contains one. | |||
3876 | if (Base.BaseGV) return; | |||
3877 | ||||
3878 | for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) | |||
3879 | GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i); | |||
3880 | if (Base.Scale == 1) | |||
3881 | GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, /* Idx */ -1, | |||
3882 | /* IsScaledReg */ true); | |||
3883 | } | |||
3884 | ||||
3885 | /// Helper function for LSRInstance::GenerateConstantOffsets. | |||
3886 | void LSRInstance::GenerateConstantOffsetsImpl( | |||
3887 | LSRUse &LU, unsigned LUIdx, const Formula &Base, | |||
3888 | const SmallVectorImpl<int64_t> &Worklist, size_t Idx, bool IsScaledReg) { | |||
3889 | ||||
3890 | auto GenerateOffset = [&](const SCEV *G, int64_t Offset) { | |||
3891 | Formula F = Base; | |||
3892 | F.BaseOffset = (uint64_t)Base.BaseOffset - Offset; | |||
3893 | ||||
3894 | if (isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F)) { | |||
3895 | // Add the offset to the base register. | |||
3896 | const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), Offset), G); | |||
3897 | // If it cancelled out, drop the base register, otherwise update it. | |||
3898 | if (NewG->isZero()) { | |||
3899 | if (IsScaledReg) { | |||
3900 | F.Scale = 0; | |||
3901 | F.ScaledReg = nullptr; | |||
3902 | } else | |||
3903 | F.deleteBaseReg(F.BaseRegs[Idx]); | |||
3904 | F.canonicalize(*L); | |||
3905 | } else if (IsScaledReg) | |||
3906 | F.ScaledReg = NewG; | |||
3907 | else | |||
3908 | F.BaseRegs[Idx] = NewG; | |||
3909 | ||||
3910 | (void)InsertFormula(LU, LUIdx, F); | |||
3911 | } | |||
3912 | }; | |||
3913 | ||||
3914 | const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx]; | |||
3915 | ||||
3916 | // With constant offsets and constant steps, we can generate pre-inc | |||
3917 | // accesses by having the offset equal the step. So, for access #0 with a | |||
3918 | // step of 8, we generate a G - 8 base which would require the first access | |||
3919 | // to be ((G - 8) + 8),+,8. The pre-indexed access then updates the pointer | |||
3920 | // for itself and hopefully becomes the base for other accesses. This means | |||
3921 | // means that a single pre-indexed access can be generated to become the new | |||
3922 | // base pointer for each iteration of the loop, resulting in no extra add/sub | |||
3923 | // instructions for pointer updating. | |||
3924 | if (AMK == TTI::AMK_PreIndexed && LU.Kind == LSRUse::Address) { | |||
3925 | if (auto *GAR = dyn_cast<SCEVAddRecExpr>(G)) { | |||
3926 | if (auto *StepRec = | |||
3927 | dyn_cast<SCEVConstant>(GAR->getStepRecurrence(SE))) { | |||
3928 | const APInt &StepInt = StepRec->getAPInt(); | |||
3929 | int64_t Step = StepInt.isNegative() ? | |||
3930 | StepInt.getSExtValue() : StepInt.getZExtValue(); | |||
3931 | ||||
3932 | for (int64_t Offset : Worklist) { | |||
3933 | Offset -= Step; | |||
3934 | GenerateOffset(G, Offset); | |||
3935 | } | |||
3936 | } | |||
3937 | } | |||
3938 | } | |||
3939 | for (int64_t Offset : Worklist) | |||
3940 | GenerateOffset(G, Offset); | |||
3941 | ||||
3942 | int64_t Imm = ExtractImmediate(G, SE); | |||
3943 | if (G->isZero() || Imm == 0) | |||
3944 | return; | |||
3945 | Formula F = Base; | |||
3946 | F.BaseOffset = (uint64_t)F.BaseOffset + Imm; | |||
3947 | if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F)) | |||
3948 | return; | |||
3949 | if (IsScaledReg) { | |||
3950 | F.ScaledReg = G; | |||
3951 | } else { | |||
3952 | F.BaseRegs[Idx] = G; | |||
3953 | // We may generate non canonical Formula if G is a recurrent expr reg | |||
3954 | // related with current loop while F.ScaledReg is not. | |||
3955 | F.canonicalize(*L); | |||
3956 | } | |||
3957 | (void)InsertFormula(LU, LUIdx, F); | |||
3958 | } | |||
3959 | ||||
3960 | /// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets. | |||
3961 | void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, | |||
3962 | Formula Base) { | |||
3963 | // TODO: For now, just add the min and max offset, because it usually isn't | |||
3964 | // worthwhile looking at everything inbetween. | |||
3965 | SmallVector<int64_t, 2> Worklist; | |||
3966 | Worklist.push_back(LU.MinOffset); | |||
3967 | if (LU.MaxOffset != LU.MinOffset) | |||
3968 | Worklist.push_back(LU.MaxOffset); | |||
3969 | ||||
3970 | for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) | |||
3971 | GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i); | |||
3972 | if (Base.Scale == 1) | |||
3973 | GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, /* Idx */ -1, | |||
3974 | /* IsScaledReg */ true); | |||
3975 | } | |||
3976 | ||||
3977 | /// For ICmpZero, check to see if we can scale up the comparison. For example, x | |||
3978 | /// == y -> x*c == y*c. | |||
3979 | void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, | |||
3980 | Formula Base) { | |||
3981 | if (LU.Kind != LSRUse::ICmpZero) return; | |||
3982 | ||||
3983 | // Determine the integer type for the base formula. | |||
3984 | Type *IntTy = Base.getType(); | |||
3985 | if (!IntTy) return; | |||
3986 | if (SE.getTypeSizeInBits(IntTy) > 64) return; | |||
3987 | ||||
3988 | // Don't do this if there is more than one offset. | |||
3989 | if (LU.MinOffset != LU.MaxOffset) return; | |||
3990 | ||||
3991 | // Check if transformation is valid. It is illegal to multiply pointer. | |||
3992 | if (Base.ScaledReg && Base.ScaledReg->getType()->isPointerTy()) | |||
3993 | return; | |||
3994 | for (const SCEV *BaseReg : Base.BaseRegs) | |||
3995 | if (BaseReg->getType()->isPointerTy()) | |||
3996 | return; | |||
3997 | assert(!Base.BaseGV && "ICmpZero use is not legal!")(static_cast <bool> (!Base.BaseGV && "ICmpZero use is not legal!" ) ? void (0) : __assert_fail ("!Base.BaseGV && \"ICmpZero use is not legal!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 3997, __extension__ __PRETTY_FUNCTION__)); | |||
3998 | ||||
3999 | // Check each interesting stride. | |||
4000 | for (int64_t Factor : Factors) { | |||
4001 | // Check that Factor can be represented by IntTy | |||
4002 | if (!ConstantInt::isValueValidForType(IntTy, Factor)) | |||
4003 | continue; | |||
4004 | // Check that the multiplication doesn't overflow. | |||
4005 | if (Base.BaseOffset == std::numeric_limits<int64_t>::min() && Factor == -1) | |||
4006 | continue; | |||
4007 | int64_t NewBaseOffset = (uint64_t)Base.BaseOffset * Factor; | |||
4008 | assert(Factor != 0 && "Zero factor not expected!")(static_cast <bool> (Factor != 0 && "Zero factor not expected!" ) ? void (0) : __assert_fail ("Factor != 0 && \"Zero factor not expected!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 4008, __extension__ __PRETTY_FUNCTION__)); | |||
4009 | if (NewBaseOffset / Factor != Base.BaseOffset) | |||
4010 | continue; | |||
4011 | // If the offset will be truncated at this use, check that it is in bounds. | |||
4012 | if (!IntTy->isPointerTy() && | |||
4013 | !ConstantInt::isValueValidForType(IntTy, NewBaseOffset)) | |||
4014 | continue; | |||
4015 | ||||
4016 | // Check that multiplying with the use offset doesn't overflow. | |||
4017 | int64_t Offset = LU.MinOffset; | |||
4018 | if (Offset == std::numeric_limits<int64_t>::min() && Factor == -1) | |||
4019 | continue; | |||
4020 | Offset = (uint64_t)Offset * Factor; | |||
4021 | if (Offset / Factor != LU.MinOffset) | |||
4022 | continue; | |||
4023 | // If the offset will be truncated at this use, check that it is in bounds. | |||
4024 | if (!IntTy->isPointerTy() && | |||
4025 | !ConstantInt::isValueValidForType(IntTy, Offset)) | |||
4026 | continue; | |||
4027 | ||||
4028 | Formula F = Base; | |||
4029 | F.BaseOffset = NewBaseOffset; | |||
4030 | ||||
4031 | // Check that this scale is legal. | |||
4032 | if (!isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F)) | |||
4033 | continue; | |||
4034 | ||||
4035 | // Compensate for the use having MinOffset built into it. | |||
4036 | F.BaseOffset = (uint64_t)F.BaseOffset + Offset - LU.MinOffset; | |||
4037 | ||||
4038 | const SCEV *FactorS = SE.getConstant(IntTy, Factor); | |||
4039 | ||||
4040 | // Check that multiplying with each base register doesn't overflow. | |||
4041 | for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) { | |||
4042 | F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS); | |||
4043 | if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i]) | |||
4044 | goto next; | |||
4045 | } | |||
4046 | ||||
4047 | // Check that multiplying with the scaled register doesn't overflow. | |||
4048 | if (F.ScaledReg) { | |||
4049 | F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS); | |||
4050 | if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg) | |||
4051 | continue; | |||
4052 | } | |||
4053 | ||||
4054 | // Check that multiplying with the unfolded offset doesn't overflow. | |||
4055 | if (F.UnfoldedOffset != 0) { | |||
4056 | if (F.UnfoldedOffset == std::numeric_limits<int64_t>::min() && | |||
4057 | Factor == -1) | |||
4058 | continue; | |||
4059 | F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor; | |||
4060 | if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset) | |||
4061 | continue; | |||
4062 | // If the offset will be truncated, check that it is in bounds. | |||
4063 | if (!IntTy->isPointerTy() && | |||
4064 | !ConstantInt::isValueValidForType(IntTy, F.UnfoldedOffset)) | |||
4065 | continue; | |||
4066 | } | |||
4067 | ||||
4068 | // If we make it here and it's legal, add it. | |||
4069 | (void)InsertFormula(LU, LUIdx, F); | |||
4070 | next:; | |||
4071 | } | |||
4072 | } | |||
4073 | ||||
4074 | /// Generate stride factor reuse formulae by making use of scaled-offset address | |||
4075 | /// modes, for example. | |||
4076 | void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) { | |||
4077 | // Determine the integer type for the base formula. | |||
4078 | Type *IntTy = Base.getType(); | |||
4079 | if (!IntTy) return; | |||
4080 | ||||
4081 | // If this Formula already has a scaled register, we can't add another one. | |||
4082 | // Try to unscale the formula to generate a better scale. | |||
4083 | if (Base.Scale != 0 && !Base.unscale()) | |||
4084 | return; | |||
4085 | ||||
4086 | assert(Base.Scale == 0 && "unscale did not did its job!")(static_cast <bool> (Base.Scale == 0 && "unscale did not did its job!" ) ? void (0) : __assert_fail ("Base.Scale == 0 && \"unscale did not did its job!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 4086, __extension__ __PRETTY_FUNCTION__)); | |||
4087 | ||||
4088 | // Check each interesting stride. | |||
4089 | for (int64_t Factor : Factors) { | |||
4090 | Base.Scale = Factor; | |||
4091 | Base.HasBaseReg = Base.BaseRegs.size() > 1; | |||
4092 | // Check whether this scale is going to be legal. | |||
4093 | if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, | |||
4094 | Base)) { | |||
4095 | // As a special-case, handle special out-of-loop Basic users specially. | |||
4096 | // TODO: Reconsider this special case. | |||
4097 | if (LU.Kind == LSRUse::Basic && | |||
4098 | isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special, | |||
4099 | LU.AccessTy, Base) && | |||
4100 | LU.AllFixupsOutsideLoop) | |||
4101 | LU.Kind = LSRUse::Special; | |||
4102 | else | |||
4103 | continue; | |||
4104 | } | |||
4105 | // For an ICmpZero, negating a solitary base register won't lead to | |||
4106 | // new solutions. | |||
4107 | if (LU.Kind == LSRUse::ICmpZero && | |||
4108 | !Base.HasBaseReg && Base.BaseOffset == 0 && !Base.BaseGV) | |||
4109 | continue; | |||
4110 | // For each addrec base reg, if its loop is current loop, apply the scale. | |||
4111 | for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) { | |||
4112 | const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i]); | |||
4113 | if (AR && (AR->getLoop() == L || LU.AllFixupsOutsideLoop)) { | |||
4114 | const SCEV *FactorS = SE.getConstant(IntTy, Factor); | |||
4115 | if (FactorS->isZero()) | |||
4116 | continue; | |||
4117 | // Divide out the factor, ignoring high bits, since we'll be | |||
4118 | // scaling the value back up in the end. | |||
4119 | if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) | |||
4120 | if (!Quotient->isZero()) { | |||
4121 | // TODO: This could be optimized to avoid all the copying. | |||
4122 | Formula F = Base; | |||
4123 | F.ScaledReg = Quotient; | |||
4124 | F.deleteBaseReg(F.BaseRegs[i]); | |||
4125 | // The canonical representation of 1*reg is reg, which is already in | |||
4126 | // Base. In that case, do not try to insert the formula, it will be | |||
4127 | // rejected anyway. | |||
4128 | if (F.Scale == 1 && (F.BaseRegs.empty() || | |||
4129 | (AR->getLoop() != L && LU.AllFixupsOutsideLoop))) | |||
4130 | continue; | |||
4131 | // If AllFixupsOutsideLoop is true and F.Scale is 1, we may generate | |||
4132 | // non canonical Formula with ScaledReg's loop not being L. | |||
4133 | if (F.Scale == 1 && LU.AllFixupsOutsideLoop) | |||
4134 | F.canonicalize(*L); | |||
4135 | (void)InsertFormula(LU, LUIdx, F); | |||
4136 | } | |||
4137 | } | |||
4138 | } | |||
4139 | } | |||
4140 | } | |||
4141 | ||||
4142 | /// Generate reuse formulae from different IV types. | |||
4143 | void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) { | |||
4144 | // Don't bother truncating symbolic values. | |||
4145 | if (Base.BaseGV) return; | |||
4146 | ||||
4147 | // Determine the integer type for the base formula. | |||
4148 | Type *DstTy = Base.getType(); | |||
4149 | if (!DstTy) return; | |||
4150 | if (DstTy->isPointerTy()) | |||
4151 | return; | |||
4152 | ||||
4153 | // It is invalid to extend a pointer type so exit early if ScaledReg or | |||
4154 | // any of the BaseRegs are pointers. | |||
4155 | if (Base.ScaledReg && Base.ScaledReg->getType()->isPointerTy()) | |||
4156 | return; | |||
4157 | if (any_of(Base.BaseRegs, | |||
4158 | [](const SCEV *S) { return S->getType()->isPointerTy(); })) | |||
4159 | return; | |||
4160 | ||||
4161 | for (Type *SrcTy : Types) { | |||
4162 | if (SrcTy != DstTy && TTI.isTruncateFree(SrcTy, DstTy)) { | |||
4163 | Formula F = Base; | |||
4164 | ||||
4165 | // Sometimes SCEV is able to prove zero during ext transform. It may | |||
4166 | // happen if SCEV did not do all possible transforms while creating the | |||
4167 | // initial node (maybe due to depth limitations), but it can do them while | |||
4168 | // taking ext. | |||
4169 | if (F.ScaledReg) { | |||
4170 | const SCEV *NewScaledReg = SE.getAnyExtendExpr(F.ScaledReg, SrcTy); | |||
4171 | if (NewScaledReg->isZero()) | |||
4172 | continue; | |||
4173 | F.ScaledReg = NewScaledReg; | |||
4174 | } | |||
4175 | bool HasZeroBaseReg = false; | |||
4176 | for (const SCEV *&BaseReg : F.BaseRegs) { | |||
4177 | const SCEV *NewBaseReg = SE.getAnyExtendExpr(BaseReg, SrcTy); | |||
4178 | if (NewBaseReg->isZero()) { | |||
4179 | HasZeroBaseReg = true; | |||
4180 | break; | |||
4181 | } | |||
4182 | BaseReg = NewBaseReg; | |||
4183 | } | |||
4184 | if (HasZeroBaseReg) | |||
4185 | continue; | |||
4186 | ||||
4187 | // TODO: This assumes we've done basic processing on all uses and | |||
4188 | // have an idea what the register usage is. | |||
4189 | if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses)) | |||
4190 | continue; | |||
4191 | ||||
4192 | F.canonicalize(*L); | |||
4193 | (void)InsertFormula(LU, LUIdx, F); | |||
4194 | } | |||
4195 | } | |||
4196 | } | |||
4197 | ||||
4198 | namespace { | |||
4199 | ||||
4200 | /// Helper class for GenerateCrossUseConstantOffsets. It's used to defer | |||
4201 | /// modifications so that the search phase doesn't have to worry about the data | |||
4202 | /// structures moving underneath it. | |||
4203 | struct WorkItem { | |||
4204 | size_t LUIdx; | |||
4205 | int64_t Imm; | |||
4206 | const SCEV *OrigReg; | |||
4207 | ||||
4208 | WorkItem(size_t LI, int64_t I, const SCEV *R) | |||
4209 | : LUIdx(LI), Imm(I), OrigReg(R) {} | |||
4210 | ||||
4211 | void print(raw_ostream &OS) const; | |||
4212 | void dump() const; | |||
4213 | }; | |||
4214 | ||||
4215 | } // end anonymous namespace | |||
4216 | ||||
4217 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) | |||
4218 | void WorkItem::print(raw_ostream &OS) const { | |||
4219 | OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx | |||
4220 | << " , add offset " << Imm; | |||
4221 | } | |||
4222 | ||||
4223 | LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void WorkItem::dump() const { | |||
4224 | print(errs()); errs() << '\n'; | |||
4225 | } | |||
4226 | #endif | |||
4227 | ||||
4228 | /// Look for registers which are a constant distance apart and try to form reuse | |||
4229 | /// opportunities between them. | |||
4230 | void LSRInstance::GenerateCrossUseConstantOffsets() { | |||
4231 | // Group the registers by their value without any added constant offset. | |||
4232 | using ImmMapTy = std::map<int64_t, const SCEV *>; | |||
4233 | ||||
4234 | DenseMap<const SCEV *, ImmMapTy> Map; | |||
4235 | DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap; | |||
4236 | SmallVector<const SCEV *, 8> Sequence; | |||
4237 | for (const SCEV *Use : RegUses) { | |||
4238 | const SCEV *Reg = Use; // Make a copy for ExtractImmediate to modify. | |||
4239 | int64_t Imm = ExtractImmediate(Reg, SE); | |||
4240 | auto Pair = Map.insert(std::make_pair(Reg, ImmMapTy())); | |||
4241 | if (Pair.second) | |||
4242 | Sequence.push_back(Reg); | |||
4243 | Pair.first->second.insert(std::make_pair(Imm, Use)); | |||
4244 | UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(Use); | |||
4245 | } | |||
4246 | ||||
4247 | // Now examine each set of registers with the same base value. Build up | |||
4248 | // a list of work to do and do the work in a separate step so that we're | |||
4249 | // not adding formulae and register counts while we're searching. | |||
4250 | SmallVector<WorkItem, 32> WorkItems; | |||
4251 | SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems; | |||
4252 | for (const SCEV *Reg : Sequence) { | |||
4253 | const ImmMapTy &Imms = Map.find(Reg)->second; | |||
4254 | ||||
4255 | // It's not worthwhile looking for reuse if there's only one offset. | |||
4256 | if (Imms.size() == 1) | |||
4257 | continue; | |||
4258 | ||||
4259 | LLVM_DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Generating cross-use offsets for " << *Reg << ':'; for (const auto &Entry : Imms ) dbgs() << ' ' << Entry.first; dbgs() << '\n' ; } } while (false) | |||
4260 | for (const auto &Entrydo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Generating cross-use offsets for " << *Reg << ':'; for (const auto &Entry : Imms ) dbgs() << ' ' << Entry.first; dbgs() << '\n' ; } } while (false) | |||
4261 | : Imms) dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Generating cross-use offsets for " << *Reg << ':'; for (const auto &Entry : Imms ) dbgs() << ' ' << Entry.first; dbgs() << '\n' ; } } while (false) | |||
4262 | << ' ' << Entry.first;do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Generating cross-use offsets for " << *Reg << ':'; for (const auto &Entry : Imms ) dbgs() << ' ' << Entry.first; dbgs() << '\n' ; } } while (false) | |||
4263 | dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Generating cross-use offsets for " << *Reg << ':'; for (const auto &Entry : Imms ) dbgs() << ' ' << Entry.first; dbgs() << '\n' ; } } while (false); | |||
4264 | ||||
4265 | // Examine each offset. | |||
4266 | for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end(); | |||
4267 | J != JE; ++J) { | |||
4268 | const SCEV *OrigReg = J->second; | |||
4269 | ||||
4270 | int64_t JImm = J->first; | |||
4271 | const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg); | |||
4272 | ||||
4273 | if (!isa<SCEVConstant>(OrigReg) && | |||
4274 | UsedByIndicesMap[Reg].count() == 1) { | |||
4275 | LLVM_DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigRegdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n'; } } while (false) | |||
4276 | << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n'; } } while (false); | |||
4277 | continue; | |||
4278 | } | |||
4279 | ||||
4280 | // Conservatively examine offsets between this orig reg a few selected | |||
4281 | // other orig regs. | |||
4282 | int64_t First = Imms.begin()->first; | |||
4283 | int64_t Last = std::prev(Imms.end())->first; | |||
4284 | // Compute (First + Last) / 2 without overflow using the fact that | |||
4285 | // First + Last = 2 * (First + Last) + (First ^ Last). | |||
4286 | int64_t Avg = (First & Last) + ((First ^ Last) >> 1); | |||
4287 | // If the result is negative and First is odd and Last even (or vice versa), | |||
4288 | // we rounded towards -inf. Add 1 in that case, to round towards 0. | |||
4289 | Avg = Avg + ((First ^ Last) & ((uint64_t)Avg >> 63)); | |||
4290 | ImmMapTy::const_iterator OtherImms[] = { | |||
4291 | Imms.begin(), std::prev(Imms.end()), | |||
4292 | Imms.lower_bound(Avg)}; | |||
4293 | for (const auto &M : OtherImms) { | |||
4294 | if (M == J || M == JE) continue; | |||
4295 | ||||
4296 | // Compute the difference between the two. | |||
4297 | int64_t Imm = (uint64_t)JImm - M->first; | |||
4298 | for (unsigned LUIdx : UsedByIndices.set_bits()) | |||
4299 | // Make a memo of this use, offset, and register tuple. | |||
4300 | if (UniqueItems.insert(std::make_pair(LUIdx, Imm)).second) | |||
4301 | WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg)); | |||
4302 | } | |||
4303 | } | |||
4304 | } | |||
4305 | ||||
4306 | Map.clear(); | |||
4307 | Sequence.clear(); | |||
4308 | UsedByIndicesMap.clear(); | |||
4309 | UniqueItems.clear(); | |||
4310 | ||||
4311 | // Now iterate through the worklist and add new formulae. | |||
4312 | for (const WorkItem &WI : WorkItems) { | |||
4313 | size_t LUIdx = WI.LUIdx; | |||
4314 | LSRUse &LU = Uses[LUIdx]; | |||
4315 | int64_t Imm = WI.Imm; | |||
4316 | const SCEV *OrigReg = WI.OrigReg; | |||
4317 | ||||
4318 | Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType()); | |||
4319 | const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm)); | |||
4320 | unsigned BitWidth = SE.getTypeSizeInBits(IntTy); | |||
4321 | ||||
4322 | // TODO: Use a more targeted data structure. | |||
4323 | for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) { | |||
4324 | Formula F = LU.Formulae[L]; | |||
4325 | // FIXME: The code for the scaled and unscaled registers looks | |||
4326 | // very similar but slightly different. Investigate if they | |||
4327 | // could be merged. That way, we would not have to unscale the | |||
4328 | // Formula. | |||
4329 | F.unscale(); | |||
4330 | // Use the immediate in the scaled register. | |||
4331 | if (F.ScaledReg == OrigReg) { | |||
4332 | int64_t Offset = (uint64_t)F.BaseOffset + Imm * (uint64_t)F.Scale; | |||
4333 | // Don't create 50 + reg(-50). | |||
4334 | if (F.referencesReg(SE.getSCEV( | |||
4335 | ConstantInt::get(IntTy, -(uint64_t)Offset)))) | |||
4336 | continue; | |||
4337 | Formula NewF = F; | |||
4338 | NewF.BaseOffset = Offset; | |||
4339 | if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, | |||
4340 | NewF)) | |||
4341 | continue; | |||
4342 | NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg); | |||
4343 | ||||
4344 | // If the new scale is a constant in a register, and adding the constant | |||
4345 | // value to the immediate would produce a value closer to zero than the | |||
4346 | // immediate itself, then the formula isn't worthwhile. | |||
4347 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg)) | |||
4348 | if (C->getValue()->isNegative() != (NewF.BaseOffset < 0) && | |||
4349 | (C->getAPInt().abs() * APInt(BitWidth, F.Scale)) | |||
4350 | .ule(std::abs(NewF.BaseOffset))) | |||
4351 | continue; | |||
4352 | ||||
4353 | // OK, looks good. | |||
4354 | NewF.canonicalize(*this->L); | |||
4355 | (void)InsertFormula(LU, LUIdx, NewF); | |||
4356 | } else { | |||
4357 | // Use the immediate in a base register. | |||
4358 | for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) { | |||
4359 | const SCEV *BaseReg = F.BaseRegs[N]; | |||
4360 | if (BaseReg != OrigReg) | |||
4361 | continue; | |||
4362 | Formula NewF = F; | |||
4363 | NewF.BaseOffset = (uint64_t)NewF.BaseOffset + Imm; | |||
4364 | if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, | |||
4365 | LU.Kind, LU.AccessTy, NewF)) { | |||
4366 | if (AMK == TTI::AMK_PostIndexed && | |||
4367 | mayUsePostIncMode(TTI, LU, OrigReg, this->L, SE)) | |||
4368 | continue; | |||
4369 | if (!TTI.isLegalAddImmediate((uint64_t)NewF.UnfoldedOffset + Imm)) | |||
4370 | continue; | |||
4371 | NewF = F; | |||
4372 | NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm; | |||
4373 | } | |||
4374 | NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg); | |||
4375 | ||||
4376 | // If the new formula has a constant in a register, and adding the | |||
4377 | // constant value to the immediate would produce a value closer to | |||
4378 | // zero than the immediate itself, then the formula isn't worthwhile. | |||
4379 | for (const SCEV *NewReg : NewF.BaseRegs) | |||
4380 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewReg)) | |||
4381 | if ((C->getAPInt() + NewF.BaseOffset) | |||
4382 | .abs() | |||
4383 | .slt(std::abs(NewF.BaseOffset)) && | |||
4384 | (C->getAPInt() + NewF.BaseOffset).countr_zero() >= | |||
4385 | (unsigned)llvm::countr_zero<uint64_t>(NewF.BaseOffset)) | |||
4386 | goto skip_formula; | |||
4387 | ||||
4388 | // Ok, looks good. | |||
4389 | NewF.canonicalize(*this->L); | |||
4390 | (void)InsertFormula(LU, LUIdx, NewF); | |||
4391 | break; | |||
4392 | skip_formula:; | |||
4393 | } | |||
4394 | } | |||
4395 | } | |||
4396 | } | |||
4397 | } | |||
4398 | ||||
4399 | /// Generate formulae for each use. | |||
4400 | void | |||
4401 | LSRInstance::GenerateAllReuseFormulae() { | |||
4402 | // This is split into multiple loops so that hasRegsUsedByUsesOtherThan | |||
4403 | // queries are more precise. | |||
4404 | for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { | |||
4405 | LSRUse &LU = Uses[LUIdx]; | |||
4406 | for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) | |||
4407 | GenerateReassociations(LU, LUIdx, LU.Formulae[i]); | |||
4408 | for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) | |||
4409 | GenerateCombinations(LU, LUIdx, LU.Formulae[i]); | |||
4410 | } | |||
4411 | for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { | |||
4412 | LSRUse &LU = Uses[LUIdx]; | |||
4413 | for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) | |||
4414 | GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]); | |||
4415 | for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) | |||
4416 | GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]); | |||
4417 | for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) | |||
4418 | GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]); | |||
4419 | for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) | |||
4420 | GenerateScales(LU, LUIdx, LU.Formulae[i]); | |||
4421 | } | |||
4422 | for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { | |||
4423 | LSRUse &LU = Uses[LUIdx]; | |||
4424 | for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i) | |||
4425 | GenerateTruncates(LU, LUIdx, LU.Formulae[i]); | |||
4426 | } | |||
4427 | ||||
4428 | GenerateCrossUseConstantOffsets(); | |||
4429 | ||||
4430 | LLVM_DEBUG(dbgs() << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "\n" "After generating reuse formulae:\n" ; print_uses(dbgs()); } } while (false) | |||
4431 | "After generating reuse formulae:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "\n" "After generating reuse formulae:\n" ; print_uses(dbgs()); } } while (false) | |||
4432 | print_uses(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "\n" "After generating reuse formulae:\n" ; print_uses(dbgs()); } } while (false); | |||
4433 | } | |||
4434 | ||||
4435 | /// If there are multiple formulae with the same set of registers used | |||
4436 | /// by other uses, pick the best one and delete the others. | |||
4437 | void LSRInstance::FilterOutUndesirableDedicatedRegisters() { | |||
4438 | DenseSet<const SCEV *> VisitedRegs; | |||
4439 | SmallPtrSet<const SCEV *, 16> Regs; | |||
4440 | SmallPtrSet<const SCEV *, 16> LoserRegs; | |||
4441 | #ifndef NDEBUG | |||
4442 | bool ChangedFormulae = false; | |||
4443 | #endif | |||
4444 | ||||
4445 | // Collect the best formula for each unique set of shared registers. This | |||
4446 | // is reset for each use. | |||
4447 | using BestFormulaeTy = | |||
4448 | DenseMap<SmallVector<const SCEV *, 4>, size_t, UniquifierDenseMapInfo>; | |||
4449 | ||||
4450 | BestFormulaeTy BestFormulae; | |||
4451 | ||||
4452 | for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { | |||
4453 | LSRUse &LU = Uses[LUIdx]; | |||
4454 | LLVM_DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs());do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Filtering for use "; LU.print (dbgs()); dbgs() << '\n'; } } while (false) | |||
4455 | dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Filtering for use "; LU.print (dbgs()); dbgs() << '\n'; } } while (false); | |||
4456 | ||||
4457 | bool Any = false; | |||
4458 | for (size_t FIdx = 0, NumForms = LU.Formulae.size(); | |||
4459 | FIdx != NumForms; ++FIdx) { | |||
4460 | Formula &F = LU.Formulae[FIdx]; | |||
4461 | ||||
4462 | // Some formulas are instant losers. For example, they may depend on | |||
4463 | // nonexistent AddRecs from other loops. These need to be filtered | |||
4464 | // immediately, otherwise heuristics could choose them over others leading | |||
4465 | // to an unsatisfactory solution. Passing LoserRegs into RateFormula here | |||
4466 | // avoids the need to recompute this information across formulae using the | |||
4467 | // same bad AddRec. Passing LoserRegs is also essential unless we remove | |||
4468 | // the corresponding bad register from the Regs set. | |||
4469 | Cost CostF(L, SE, TTI, AMK); | |||
4470 | Regs.clear(); | |||
4471 | CostF.RateFormula(F, Regs, VisitedRegs, LU, &LoserRegs); | |||
4472 | if (CostF.isLoser()) { | |||
4473 | // During initial formula generation, undesirable formulae are generated | |||
4474 | // by uses within other loops that have some non-trivial address mode or | |||
4475 | // use the postinc form of the IV. LSR needs to provide these formulae | |||
4476 | // as the basis of rediscovering the desired formula that uses an AddRec | |||
4477 | // corresponding to the existing phi. Once all formulae have been | |||
4478 | // generated, these initial losers may be pruned. | |||
4479 | LLVM_DEBUG(dbgs() << " Filtering loser "; F.print(dbgs());do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Filtering loser "; F.print (dbgs()); dbgs() << "\n"; } } while (false) | |||
4480 | dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Filtering loser "; F.print (dbgs()); dbgs() << "\n"; } } while (false); | |||
4481 | } | |||
4482 | else { | |||
4483 | SmallVector<const SCEV *, 4> Key; | |||
4484 | for (const SCEV *Reg : F.BaseRegs) { | |||
4485 | if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx)) | |||
4486 | Key.push_back(Reg); | |||
4487 | } | |||
4488 | if (F.ScaledReg && | |||
4489 | RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx)) | |||
4490 | Key.push_back(F.ScaledReg); | |||
4491 | // Unstable sort by host order ok, because this is only used for | |||
4492 | // uniquifying. | |||
4493 | llvm::sort(Key); | |||
4494 | ||||
4495 | std::pair<BestFormulaeTy::const_iterator, bool> P = | |||
4496 | BestFormulae.insert(std::make_pair(Key, FIdx)); | |||
4497 | if (P.second) | |||
4498 | continue; | |||
4499 | ||||
4500 | Formula &Best = LU.Formulae[P.first->second]; | |||
4501 | ||||
4502 | Cost CostBest(L, SE, TTI, AMK); | |||
4503 | Regs.clear(); | |||
4504 | CostBest.RateFormula(Best, Regs, VisitedRegs, LU); | |||
4505 | if (CostF.isLess(CostBest)) | |||
4506 | std::swap(F, Best); | |||
4507 | LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Filtering out formula " ; F.print(dbgs()); dbgs() << "\n" " in favor of formula " ; Best.print(dbgs()); dbgs() << '\n'; } } while (false) | |||
4508 | dbgs() << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Filtering out formula " ; F.print(dbgs()); dbgs() << "\n" " in favor of formula " ; Best.print(dbgs()); dbgs() << '\n'; } } while (false) | |||
4509 | " in favor of formula ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Filtering out formula " ; F.print(dbgs()); dbgs() << "\n" " in favor of formula " ; Best.print(dbgs()); dbgs() << '\n'; } } while (false) | |||
4510 | Best.print(dbgs()); dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Filtering out formula " ; F.print(dbgs()); dbgs() << "\n" " in favor of formula " ; Best.print(dbgs()); dbgs() << '\n'; } } while (false); | |||
4511 | } | |||
4512 | #ifndef NDEBUG | |||
4513 | ChangedFormulae = true; | |||
4514 | #endif | |||
4515 | LU.DeleteFormula(F); | |||
4516 | --FIdx; | |||
4517 | --NumForms; | |||
4518 | Any = true; | |||
4519 | } | |||
4520 | ||||
4521 | // Now that we've filtered out some formulae, recompute the Regs set. | |||
4522 | if (Any) | |||
4523 | LU.RecomputeRegs(LUIdx, RegUses); | |||
4524 | ||||
4525 | // Reset this to prepare for the next use. | |||
4526 | BestFormulae.clear(); | |||
4527 | } | |||
4528 | ||||
4529 | LLVM_DEBUG(if (ChangedFormulae) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { if (ChangedFormulae) { dbgs() << "\n" "After filtering out undesirable candidates:\n"; print_uses( dbgs()); }; } } while (false) | |||
4530 | dbgs() << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { if (ChangedFormulae) { dbgs() << "\n" "After filtering out undesirable candidates:\n"; print_uses( dbgs()); }; } } while (false) | |||
4531 | "After filtering out undesirable candidates:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { if (ChangedFormulae) { dbgs() << "\n" "After filtering out undesirable candidates:\n"; print_uses( dbgs()); }; } } while (false) | |||
4532 | print_uses(dbgs());do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { if (ChangedFormulae) { dbgs() << "\n" "After filtering out undesirable candidates:\n"; print_uses( dbgs()); }; } } while (false) | |||
4533 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { if (ChangedFormulae) { dbgs() << "\n" "After filtering out undesirable candidates:\n"; print_uses( dbgs()); }; } } while (false); | |||
4534 | } | |||
4535 | ||||
4536 | /// Estimate the worst-case number of solutions the solver might have to | |||
4537 | /// consider. It almost never considers this many solutions because it prune the | |||
4538 | /// search space, but the pruning isn't always sufficient. | |||
4539 | size_t LSRInstance::EstimateSearchSpaceComplexity() const { | |||
4540 | size_t Power = 1; | |||
4541 | for (const LSRUse &LU : Uses) { | |||
4542 | size_t FSize = LU.Formulae.size(); | |||
4543 | if (FSize >= ComplexityLimit) { | |||
4544 | Power = ComplexityLimit; | |||
4545 | break; | |||
4546 | } | |||
4547 | Power *= FSize; | |||
4548 | if (Power >= ComplexityLimit) | |||
4549 | break; | |||
4550 | } | |||
4551 | return Power; | |||
4552 | } | |||
4553 | ||||
4554 | /// When one formula uses a superset of the registers of another formula, it | |||
4555 | /// won't help reduce register pressure (though it may not necessarily hurt | |||
4556 | /// register pressure); remove it to simplify the system. | |||
4557 | void LSRInstance::NarrowSearchSpaceByDetectingSupersets() { | |||
4558 | if (EstimateSearchSpaceComplexity() >= ComplexityLimit) { | |||
4559 | LLVM_DEBUG(dbgs() << "The search space is too complex.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "The search space is too complex.\n" ; } } while (false); | |||
4560 | ||||
4561 | LLVM_DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Narrowing the search space by eliminating formulae " "which use a superset of registers used by other " "formulae.\n" ; } } while (false) | |||
4562 | "which use a superset of registers used by other "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Narrowing the search space by eliminating formulae " "which use a superset of registers used by other " "formulae.\n" ; } } while (false) | |||
4563 | "formulae.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Narrowing the search space by eliminating formulae " "which use a superset of registers used by other " "formulae.\n" ; } } while (false); | |||
4564 | ||||
4565 | for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { | |||
4566 | LSRUse &LU = Uses[LUIdx]; | |||
4567 | bool Any = false; | |||
4568 | for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) { | |||
4569 | Formula &F = LU.Formulae[i]; | |||
4570 | // Look for a formula with a constant or GV in a register. If the use | |||
4571 | // also has a formula with that same value in an immediate field, | |||
4572 | // delete the one that uses a register. | |||
4573 | for (SmallVectorImpl<const SCEV *>::const_iterator | |||
4574 | I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) { | |||
4575 | if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) { | |||
4576 | Formula NewF = F; | |||
4577 | //FIXME: Formulas should store bitwidth to do wrapping properly. | |||
4578 | // See PR41034. | |||
4579 | NewF.BaseOffset += (uint64_t)C->getValue()->getSExtValue(); | |||
4580 | NewF.BaseRegs.erase(NewF.BaseRegs.begin() + | |||
4581 | (I - F.BaseRegs.begin())); | |||
4582 | if (LU.HasFormulaWithSameRegs(NewF)) { | |||
4583 | LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs());do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Deleting "; F.print(dbgs ()); dbgs() << '\n'; } } while (false) | |||
4584 | dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Deleting "; F.print(dbgs ()); dbgs() << '\n'; } } while (false); | |||
4585 | LU.DeleteFormula(F); | |||
4586 | --i; | |||
4587 | --e; | |||
4588 | Any = true; | |||
4589 | break; | |||
4590 | } | |||
4591 | } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) { | |||
4592 | if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) | |||
4593 | if (!F.BaseGV) { | |||
4594 | Formula NewF = F; | |||
4595 | NewF.BaseGV = GV; | |||
4596 | NewF.BaseRegs.erase(NewF.BaseRegs.begin() + | |||
4597 | (I - F.BaseRegs.begin())); | |||
4598 | if (LU.HasFormulaWithSameRegs(NewF)) { | |||
4599 | LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs());do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Deleting "; F.print(dbgs ()); dbgs() << '\n'; } } while (false) | |||
4600 | dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Deleting "; F.print(dbgs ()); dbgs() << '\n'; } } while (false); | |||
4601 | LU.DeleteFormula(F); | |||
4602 | --i; | |||
4603 | --e; | |||
4604 | Any = true; | |||
4605 | break; | |||
4606 | } | |||
4607 | } | |||
4608 | } | |||
4609 | } | |||
4610 | } | |||
4611 | if (Any) | |||
4612 | LU.RecomputeRegs(LUIdx, RegUses); | |||
4613 | } | |||
4614 | ||||
4615 | LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "After pre-selection:\n"; print_uses (dbgs()); } } while (false); | |||
4616 | } | |||
4617 | } | |||
4618 | ||||
4619 | /// When there are many registers for expressions like A, A+1, A+2, etc., | |||
4620 | /// allocate a single register for them. | |||
4621 | void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() { | |||
4622 | if (EstimateSearchSpaceComplexity() < ComplexityLimit) | |||
4623 | return; | |||
4624 | ||||
4625 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "The search space is too complex.\n" "Narrowing the search space by assuming that uses separated " "by a constant offset will use the same registers.\n"; } } while (false) | |||
4626 | dbgs() << "The search space is too complex.\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "The search space is too complex.\n" "Narrowing the search space by assuming that uses separated " "by a constant offset will use the same registers.\n"; } } while (false) | |||
4627 | "Narrowing the search space by assuming that uses separated "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "The search space is too complex.\n" "Narrowing the search space by assuming that uses separated " "by a constant offset will use the same registers.\n"; } } while (false) | |||
4628 | "by a constant offset will use the same registers.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "The search space is too complex.\n" "Narrowing the search space by assuming that uses separated " "by a constant offset will use the same registers.\n"; } } while (false); | |||
4629 | ||||
4630 | // This is especially useful for unrolled loops. | |||
4631 | ||||
4632 | for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { | |||
4633 | LSRUse &LU = Uses[LUIdx]; | |||
4634 | for (const Formula &F : LU.Formulae) { | |||
4635 | if (F.BaseOffset == 0 || (F.Scale != 0 && F.Scale != 1)) | |||
4636 | continue; | |||
4637 | ||||
4638 | LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU); | |||
4639 | if (!LUThatHas) | |||
4640 | continue; | |||
4641 | ||||
4642 | if (!reconcileNewOffset(*LUThatHas, F.BaseOffset, /*HasBaseReg=*/ false, | |||
4643 | LU.Kind, LU.AccessTy)) | |||
4644 | continue; | |||
4645 | ||||
4646 | LLVM_DEBUG(dbgs() << " Deleting use "; LU.print(dbgs()); dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Deleting use "; LU.print (dbgs()); dbgs() << '\n'; } } while (false); | |||
4647 | ||||
4648 | LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop; | |||
4649 | ||||
4650 | // Transfer the fixups of LU to LUThatHas. | |||
4651 | for (LSRFixup &Fixup : LU.Fixups) { | |||
4652 | Fixup.Offset += F.BaseOffset; | |||
4653 | LUThatHas->pushFixup(Fixup); | |||
4654 | LLVM_DEBUG(dbgs() << "New fixup has offset " << Fixup.Offset << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "New fixup has offset " << Fixup.Offset << '\n'; } } while (false); | |||
4655 | } | |||
4656 | ||||
4657 | // Delete formulae from the new use which are no longer legal. | |||
4658 | bool Any = false; | |||
4659 | for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) { | |||
4660 | Formula &F = LUThatHas->Formulae[i]; | |||
4661 | if (!isLegalUse(TTI, LUThatHas->MinOffset, LUThatHas->MaxOffset, | |||
4662 | LUThatHas->Kind, LUThatHas->AccessTy, F)) { | |||
4663 | LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Deleting "; F.print(dbgs ()); dbgs() << '\n'; } } while (false); | |||
4664 | LUThatHas->DeleteFormula(F); | |||
4665 | --i; | |||
4666 | --e; | |||
4667 | Any = true; | |||
4668 | } | |||
4669 | } | |||
4670 | ||||
4671 | if (Any) | |||
4672 | LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses); | |||
4673 | ||||
4674 | // Delete the old use. | |||
4675 | DeleteUse(LU, LUIdx); | |||
4676 | --LUIdx; | |||
4677 | --NumUses; | |||
4678 | break; | |||
4679 | } | |||
4680 | } | |||
4681 | ||||
4682 | LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "After pre-selection:\n"; print_uses (dbgs()); } } while (false); | |||
4683 | } | |||
4684 | ||||
4685 | /// Call FilterOutUndesirableDedicatedRegisters again, if necessary, now that | |||
4686 | /// we've done more filtering, as it may be able to find more formulae to | |||
4687 | /// eliminate. | |||
4688 | void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){ | |||
4689 | if (EstimateSearchSpaceComplexity() >= ComplexityLimit) { | |||
4690 | LLVM_DEBUG(dbgs() << "The search space is too complex.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "The search space is too complex.\n" ; } } while (false); | |||
4691 | ||||
4692 | LLVM_DEBUG(dbgs() << "Narrowing the search space by re-filtering out "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Narrowing the search space by re-filtering out " "undesirable dedicated registers.\n"; } } while (false) | |||
4693 | "undesirable dedicated registers.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Narrowing the search space by re-filtering out " "undesirable dedicated registers.\n"; } } while (false); | |||
4694 | ||||
4695 | FilterOutUndesirableDedicatedRegisters(); | |||
4696 | ||||
4697 | LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "After pre-selection:\n"; print_uses (dbgs()); } } while (false); | |||
4698 | } | |||
4699 | } | |||
4700 | ||||
4701 | /// If a LSRUse has multiple formulae with the same ScaledReg and Scale. | |||
4702 | /// Pick the best one and delete the others. | |||
4703 | /// This narrowing heuristic is to keep as many formulae with different | |||
4704 | /// Scale and ScaledReg pair as possible while narrowing the search space. | |||
4705 | /// The benefit is that it is more likely to find out a better solution | |||
4706 | /// from a formulae set with more Scale and ScaledReg variations than | |||
4707 | /// a formulae set with the same Scale and ScaledReg. The picking winner | |||
4708 | /// reg heuristic will often keep the formulae with the same Scale and | |||
4709 | /// ScaledReg and filter others, and we want to avoid that if possible. | |||
4710 | void LSRInstance::NarrowSearchSpaceByFilterFormulaWithSameScaledReg() { | |||
4711 | if (EstimateSearchSpaceComplexity() < ComplexityLimit) | |||
4712 | return; | |||
4713 | ||||
4714 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "The search space is too complex.\n" "Narrowing the search space by choosing the best Formula " "from the Formulae with the same Scale and ScaledReg.\n" ; } } while (false) | |||
4715 | dbgs() << "The search space is too complex.\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "The search space is too complex.\n" "Narrowing the search space by choosing the best Formula " "from the Formulae with the same Scale and ScaledReg.\n" ; } } while (false) | |||
4716 | "Narrowing the search space by choosing the best Formula "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "The search space is too complex.\n" "Narrowing the search space by choosing the best Formula " "from the Formulae with the same Scale and ScaledReg.\n" ; } } while (false) | |||
4717 | "from the Formulae with the same Scale and ScaledReg.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "The search space is too complex.\n" "Narrowing the search space by choosing the best Formula " "from the Formulae with the same Scale and ScaledReg.\n" ; } } while (false); | |||
4718 | ||||
4719 | // Map the "Scale * ScaledReg" pair to the best formula of current LSRUse. | |||
4720 | using BestFormulaeTy = DenseMap<std::pair<const SCEV *, int64_t>, size_t>; | |||
4721 | ||||
4722 | BestFormulaeTy BestFormulae; | |||
4723 | #ifndef NDEBUG | |||
4724 | bool ChangedFormulae = false; | |||
4725 | #endif | |||
4726 | DenseSet<const SCEV *> VisitedRegs; | |||
4727 | SmallPtrSet<const SCEV *, 16> Regs; | |||
4728 | ||||
4729 | for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { | |||
4730 | LSRUse &LU = Uses[LUIdx]; | |||
4731 | LLVM_DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs());do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Filtering for use "; LU.print (dbgs()); dbgs() << '\n'; } } while (false) | |||
4732 | dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Filtering for use "; LU.print (dbgs()); dbgs() << '\n'; } } while (false); | |||
4733 | ||||
4734 | // Return true if Formula FA is better than Formula FB. | |||
4735 | auto IsBetterThan = [&](Formula &FA, Formula &FB) { | |||
4736 | // First we will try to choose the Formula with fewer new registers. | |||
4737 | // For a register used by current Formula, the more the register is | |||
4738 | // shared among LSRUses, the less we increase the register number | |||
4739 | // counter of the formula. | |||
4740 | size_t FARegNum = 0; | |||
4741 | for (const SCEV *Reg : FA.BaseRegs) { | |||
4742 | const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg); | |||
4743 | FARegNum += (NumUses - UsedByIndices.count() + 1); | |||
4744 | } | |||
4745 | size_t FBRegNum = 0; | |||
4746 | for (const SCEV *Reg : FB.BaseRegs) { | |||
4747 | const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg); | |||
4748 | FBRegNum += (NumUses - UsedByIndices.count() + 1); | |||
4749 | } | |||
4750 | if (FARegNum != FBRegNum) | |||
4751 | return FARegNum < FBRegNum; | |||
4752 | ||||
4753 | // If the new register numbers are the same, choose the Formula with | |||
4754 | // less Cost. | |||
4755 | Cost CostFA(L, SE, TTI, AMK); | |||
4756 | Cost CostFB(L, SE, TTI, AMK); | |||
4757 | Regs.clear(); | |||
4758 | CostFA.RateFormula(FA, Regs, VisitedRegs, LU); | |||
4759 | Regs.clear(); | |||
4760 | CostFB.RateFormula(FB, Regs, VisitedRegs, LU); | |||
4761 | return CostFA.isLess(CostFB); | |||
4762 | }; | |||
4763 | ||||
4764 | bool Any = false; | |||
4765 | for (size_t FIdx = 0, NumForms = LU.Formulae.size(); FIdx != NumForms; | |||
4766 | ++FIdx) { | |||
4767 | Formula &F = LU.Formulae[FIdx]; | |||
4768 | if (!F.ScaledReg) | |||
4769 | continue; | |||
4770 | auto P = BestFormulae.insert({{F.ScaledReg, F.Scale}, FIdx}); | |||
4771 | if (P.second) | |||
4772 | continue; | |||
4773 | ||||
4774 | Formula &Best = LU.Formulae[P.first->second]; | |||
4775 | if (IsBetterThan(F, Best)) | |||
4776 | std::swap(F, Best); | |||
4777 | LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Filtering out formula " ; F.print(dbgs()); dbgs() << "\n" " in favor of formula " ; Best.print(dbgs()); dbgs() << '\n'; } } while (false) | |||
4778 | dbgs() << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Filtering out formula " ; F.print(dbgs()); dbgs() << "\n" " in favor of formula " ; Best.print(dbgs()); dbgs() << '\n'; } } while (false) | |||
4779 | " in favor of formula ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Filtering out formula " ; F.print(dbgs()); dbgs() << "\n" " in favor of formula " ; Best.print(dbgs()); dbgs() << '\n'; } } while (false) | |||
4780 | Best.print(dbgs()); dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Filtering out formula " ; F.print(dbgs()); dbgs() << "\n" " in favor of formula " ; Best.print(dbgs()); dbgs() << '\n'; } } while (false); | |||
4781 | #ifndef NDEBUG | |||
4782 | ChangedFormulae = true; | |||
4783 | #endif | |||
4784 | LU.DeleteFormula(F); | |||
4785 | --FIdx; | |||
4786 | --NumForms; | |||
4787 | Any = true; | |||
4788 | } | |||
4789 | if (Any) | |||
4790 | LU.RecomputeRegs(LUIdx, RegUses); | |||
4791 | ||||
4792 | // Reset this to prepare for the next use. | |||
4793 | BestFormulae.clear(); | |||
4794 | } | |||
4795 | ||||
4796 | LLVM_DEBUG(if (ChangedFormulae) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { if (ChangedFormulae) { dbgs() << "\n" "After filtering out undesirable candidates:\n"; print_uses( dbgs()); }; } } while (false) | |||
4797 | dbgs() << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { if (ChangedFormulae) { dbgs() << "\n" "After filtering out undesirable candidates:\n"; print_uses( dbgs()); }; } } while (false) | |||
4798 | "After filtering out undesirable candidates:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { if (ChangedFormulae) { dbgs() << "\n" "After filtering out undesirable candidates:\n"; print_uses( dbgs()); }; } } while (false) | |||
4799 | print_uses(dbgs());do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { if (ChangedFormulae) { dbgs() << "\n" "After filtering out undesirable candidates:\n"; print_uses( dbgs()); }; } } while (false) | |||
4800 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { if (ChangedFormulae) { dbgs() << "\n" "After filtering out undesirable candidates:\n"; print_uses( dbgs()); }; } } while (false); | |||
4801 | } | |||
4802 | ||||
4803 | /// If we are over the complexity limit, filter out any post-inc prefering | |||
4804 | /// variables to only post-inc values. | |||
4805 | void LSRInstance::NarrowSearchSpaceByFilterPostInc() { | |||
4806 | if (AMK != TTI::AMK_PostIndexed) | |||
4807 | return; | |||
4808 | if (EstimateSearchSpaceComplexity() < ComplexityLimit) | |||
4809 | return; | |||
4810 | ||||
4811 | LLVM_DEBUG(dbgs() << "The search space is too complex.\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "The search space is too complex.\n" "Narrowing the search space by choosing the lowest " "register Formula for PostInc Uses.\n" ; } } while (false) | |||
4812 | "Narrowing the search space by choosing the lowest "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "The search space is too complex.\n" "Narrowing the search space by choosing the lowest " "register Formula for PostInc Uses.\n" ; } } while (false) | |||
4813 | "register Formula for PostInc Uses.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "The search space is too complex.\n" "Narrowing the search space by choosing the lowest " "register Formula for PostInc Uses.\n" ; } } while (false); | |||
4814 | ||||
4815 | for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { | |||
4816 | LSRUse &LU = Uses[LUIdx]; | |||
4817 | ||||
4818 | if (LU.Kind != LSRUse::Address) | |||
4819 | continue; | |||
4820 | if (!TTI.isIndexedLoadLegal(TTI.MIM_PostInc, LU.AccessTy.getType()) && | |||
4821 | !TTI.isIndexedStoreLegal(TTI.MIM_PostInc, LU.AccessTy.getType())) | |||
4822 | continue; | |||
4823 | ||||
4824 | size_t MinRegs = std::numeric_limits<size_t>::max(); | |||
4825 | for (const Formula &F : LU.Formulae) | |||
4826 | MinRegs = std::min(F.getNumRegs(), MinRegs); | |||
4827 | ||||
4828 | bool Any = false; | |||
4829 | for (size_t FIdx = 0, NumForms = LU.Formulae.size(); FIdx != NumForms; | |||
4830 | ++FIdx) { | |||
4831 | Formula &F = LU.Formulae[FIdx]; | |||
4832 | if (F.getNumRegs() > MinRegs) { | |||
4833 | LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Filtering out formula " ; F.print(dbgs()); dbgs() << "\n"; } } while (false) | |||
4834 | dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Filtering out formula " ; F.print(dbgs()); dbgs() << "\n"; } } while (false); | |||
4835 | LU.DeleteFormula(F); | |||
4836 | --FIdx; | |||
4837 | --NumForms; | |||
4838 | Any = true; | |||
4839 | } | |||
4840 | } | |||
4841 | if (Any) | |||
4842 | LU.RecomputeRegs(LUIdx, RegUses); | |||
4843 | ||||
4844 | if (EstimateSearchSpaceComplexity() < ComplexityLimit) | |||
4845 | break; | |||
4846 | } | |||
4847 | ||||
4848 | LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "After pre-selection:\n"; print_uses (dbgs()); } } while (false); | |||
4849 | } | |||
4850 | ||||
4851 | /// The function delete formulas with high registers number expectation. | |||
4852 | /// Assuming we don't know the value of each formula (already delete | |||
4853 | /// all inefficient), generate probability of not selecting for each | |||
4854 | /// register. | |||
4855 | /// For example, | |||
4856 | /// Use1: | |||
4857 | /// reg(a) + reg({0,+,1}) | |||
4858 | /// reg(a) + reg({-1,+,1}) + 1 | |||
4859 | /// reg({a,+,1}) | |||
4860 | /// Use2: | |||
4861 | /// reg(b) + reg({0,+,1}) | |||
4862 | /// reg(b) + reg({-1,+,1}) + 1 | |||
4863 | /// reg({b,+,1}) | |||
4864 | /// Use3: | |||
4865 | /// reg(c) + reg(b) + reg({0,+,1}) | |||
4866 | /// reg(c) + reg({b,+,1}) | |||
4867 | /// | |||
4868 | /// Probability of not selecting | |||
4869 | /// Use1 Use2 Use3 | |||
4870 | /// reg(a) (1/3) * 1 * 1 | |||
4871 | /// reg(b) 1 * (1/3) * (1/2) | |||
4872 | /// reg({0,+,1}) (2/3) * (2/3) * (1/2) | |||
4873 | /// reg({-1,+,1}) (2/3) * (2/3) * 1 | |||
4874 | /// reg({a,+,1}) (2/3) * 1 * 1 | |||
4875 | /// reg({b,+,1}) 1 * (2/3) * (2/3) | |||
4876 | /// reg(c) 1 * 1 * 0 | |||
4877 | /// | |||
4878 | /// Now count registers number mathematical expectation for each formula: | |||
4879 | /// Note that for each use we exclude probability if not selecting for the use. | |||
4880 | /// For example for Use1 probability for reg(a) would be just 1 * 1 (excluding | |||
4881 | /// probabilty 1/3 of not selecting for Use1). | |||
4882 | /// Use1: | |||
4883 | /// reg(a) + reg({0,+,1}) 1 + 1/3 -- to be deleted | |||
4884 | /// reg(a) + reg({-1,+,1}) + 1 1 + 4/9 -- to be deleted | |||
4885 | /// reg({a,+,1}) 1 | |||
4886 | /// Use2: | |||
4887 | /// reg(b) + reg({0,+,1}) 1/2 + 1/3 -- to be deleted | |||
4888 | /// reg(b) + reg({-1,+,1}) + 1 1/2 + 2/3 -- to be deleted | |||
4889 | /// reg({b,+,1}) 2/3 | |||
4890 | /// Use3: | |||
4891 | /// reg(c) + reg(b) + reg({0,+,1}) 1 + 1/3 + 4/9 -- to be deleted | |||
4892 | /// reg(c) + reg({b,+,1}) 1 + 2/3 | |||
4893 | void LSRInstance::NarrowSearchSpaceByDeletingCostlyFormulas() { | |||
4894 | if (EstimateSearchSpaceComplexity() < ComplexityLimit) | |||
4895 | return; | |||
4896 | // Ok, we have too many of formulae on our hands to conveniently handle. | |||
4897 | // Use a rough heuristic to thin out the list. | |||
4898 | ||||
4899 | // Set of Regs wich will be 100% used in final solution. | |||
4900 | // Used in each formula of a solution (in example above this is reg(c)). | |||
4901 | // We can skip them in calculations. | |||
4902 | SmallPtrSet<const SCEV *, 4> UniqRegs; | |||
4903 | LLVM_DEBUG(dbgs() << "The search space is too complex.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "The search space is too complex.\n" ; } } while (false); | |||
4904 | ||||
4905 | // Map each register to probability of not selecting | |||
4906 | DenseMap <const SCEV *, float> RegNumMap; | |||
4907 | for (const SCEV *Reg : RegUses) { | |||
4908 | if (UniqRegs.count(Reg)) | |||
4909 | continue; | |||
4910 | float PNotSel = 1; | |||
4911 | for (const LSRUse &LU : Uses) { | |||
4912 | if (!LU.Regs.count(Reg)) | |||
4913 | continue; | |||
4914 | float P = LU.getNotSelectedProbability(Reg); | |||
4915 | if (P != 0.0) | |||
4916 | PNotSel *= P; | |||
4917 | else | |||
4918 | UniqRegs.insert(Reg); | |||
4919 | } | |||
4920 | RegNumMap.insert(std::make_pair(Reg, PNotSel)); | |||
4921 | } | |||
4922 | ||||
4923 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Narrowing the search space by deleting costly formulas\n" ; } } while (false) | |||
4924 | dbgs() << "Narrowing the search space by deleting costly formulas\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Narrowing the search space by deleting costly formulas\n" ; } } while (false); | |||
4925 | ||||
4926 | // Delete formulas where registers number expectation is high. | |||
4927 | for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { | |||
4928 | LSRUse &LU = Uses[LUIdx]; | |||
4929 | // If nothing to delete - continue. | |||
4930 | if (LU.Formulae.size() < 2) | |||
4931 | continue; | |||
4932 | // This is temporary solution to test performance. Float should be | |||
4933 | // replaced with round independent type (based on integers) to avoid | |||
4934 | // different results for different target builds. | |||
4935 | float FMinRegNum = LU.Formulae[0].getNumRegs(); | |||
4936 | float FMinARegNum = LU.Formulae[0].getNumRegs(); | |||
4937 | size_t MinIdx = 0; | |||
4938 | for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) { | |||
4939 | Formula &F = LU.Formulae[i]; | |||
4940 | float FRegNum = 0; | |||
4941 | float FARegNum = 0; | |||
4942 | for (const SCEV *BaseReg : F.BaseRegs) { | |||
4943 | if (UniqRegs.count(BaseReg)) | |||
4944 | continue; | |||
4945 | FRegNum += RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg); | |||
4946 | if (isa<SCEVAddRecExpr>(BaseReg)) | |||
4947 | FARegNum += | |||
4948 | RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg); | |||
4949 | } | |||
4950 | if (const SCEV *ScaledReg = F.ScaledReg) { | |||
4951 | if (!UniqRegs.count(ScaledReg)) { | |||
4952 | FRegNum += | |||
4953 | RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg); | |||
4954 | if (isa<SCEVAddRecExpr>(ScaledReg)) | |||
4955 | FARegNum += | |||
4956 | RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg); | |||
4957 | } | |||
4958 | } | |||
4959 | if (FMinRegNum > FRegNum || | |||
4960 | (FMinRegNum == FRegNum && FMinARegNum > FARegNum)) { | |||
4961 | FMinRegNum = FRegNum; | |||
4962 | FMinARegNum = FARegNum; | |||
4963 | MinIdx = i; | |||
4964 | } | |||
4965 | } | |||
4966 | LLVM_DEBUG(dbgs() << " The formula "; LU.Formulae[MinIdx].print(dbgs());do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " The formula "; LU.Formulae [MinIdx].print(dbgs()); dbgs() << " with min reg num " << FMinRegNum << '\n'; } } while (false) | |||
4967 | dbgs() << " with min reg num " << FMinRegNum << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " The formula "; LU.Formulae [MinIdx].print(dbgs()); dbgs() << " with min reg num " << FMinRegNum << '\n'; } } while (false); | |||
4968 | if (MinIdx != 0) | |||
4969 | std::swap(LU.Formulae[MinIdx], LU.Formulae[0]); | |||
4970 | while (LU.Formulae.size() != 1) { | |||
4971 | LLVM_DEBUG(dbgs() << " Deleting "; LU.Formulae.back().print(dbgs());do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Deleting "; LU.Formulae .back().print(dbgs()); dbgs() << '\n'; } } while (false ) | |||
4972 | dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Deleting "; LU.Formulae .back().print(dbgs()); dbgs() << '\n'; } } while (false ); | |||
4973 | LU.Formulae.pop_back(); | |||
4974 | } | |||
4975 | LU.RecomputeRegs(LUIdx, RegUses); | |||
4976 | assert(LU.Formulae.size() == 1 && "Should be exactly 1 min regs formula")(static_cast <bool> (LU.Formulae.size() == 1 && "Should be exactly 1 min regs formula") ? void (0) : __assert_fail ("LU.Formulae.size() == 1 && \"Should be exactly 1 min regs formula\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 4976, __extension__ __PRETTY_FUNCTION__)); | |||
4977 | Formula &F = LU.Formulae[0]; | |||
4978 | LLVM_DEBUG(dbgs() << " Leaving only "; F.print(dbgs()); dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Leaving only "; F.print (dbgs()); dbgs() << '\n'; } } while (false); | |||
4979 | // When we choose the formula, the regs become unique. | |||
4980 | UniqRegs.insert(F.BaseRegs.begin(), F.BaseRegs.end()); | |||
4981 | if (F.ScaledReg) | |||
4982 | UniqRegs.insert(F.ScaledReg); | |||
4983 | } | |||
4984 | LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "After pre-selection:\n"; print_uses (dbgs()); } } while (false); | |||
4985 | } | |||
4986 | ||||
4987 | // Check if Best and Reg are SCEVs separated by a constant amount C, and if so | |||
4988 | // would the addressing offset +C would be legal where the negative offset -C is | |||
4989 | // not. | |||
4990 | static bool IsSimplerBaseSCEVForTarget(const TargetTransformInfo &TTI, | |||
4991 | ScalarEvolution &SE, const SCEV *Best, | |||
4992 | const SCEV *Reg, | |||
4993 | MemAccessTy AccessType) { | |||
4994 | if (Best->getType() != Reg->getType() || | |||
4995 | (isa<SCEVAddRecExpr>(Best) && isa<SCEVAddRecExpr>(Reg) && | |||
4996 | cast<SCEVAddRecExpr>(Best)->getLoop() != | |||
4997 | cast<SCEVAddRecExpr>(Reg)->getLoop())) | |||
4998 | return false; | |||
4999 | const auto *Diff = dyn_cast<SCEVConstant>(SE.getMinusSCEV(Best, Reg)); | |||
5000 | if (!Diff) | |||
5001 | return false; | |||
5002 | ||||
5003 | return TTI.isLegalAddressingMode( | |||
5004 | AccessType.MemTy, /*BaseGV=*/nullptr, | |||
5005 | /*BaseOffset=*/Diff->getAPInt().getSExtValue(), | |||
5006 | /*HasBaseReg=*/false, /*Scale=*/0, AccessType.AddrSpace) && | |||
5007 | !TTI.isLegalAddressingMode( | |||
5008 | AccessType.MemTy, /*BaseGV=*/nullptr, | |||
5009 | /*BaseOffset=*/-Diff->getAPInt().getSExtValue(), | |||
5010 | /*HasBaseReg=*/false, /*Scale=*/0, AccessType.AddrSpace); | |||
5011 | } | |||
5012 | ||||
5013 | /// Pick a register which seems likely to be profitable, and then in any use | |||
5014 | /// which has any reference to that register, delete all formulae which do not | |||
5015 | /// reference that register. | |||
5016 | void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() { | |||
5017 | // With all other options exhausted, loop until the system is simple | |||
5018 | // enough to handle. | |||
5019 | SmallPtrSet<const SCEV *, 4> Taken; | |||
5020 | while (EstimateSearchSpaceComplexity() >= ComplexityLimit) { | |||
5021 | // Ok, we have too many of formulae on our hands to conveniently handle. | |||
5022 | // Use a rough heuristic to thin out the list. | |||
5023 | LLVM_DEBUG(dbgs() << "The search space is too complex.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "The search space is too complex.\n" ; } } while (false); | |||
5024 | ||||
5025 | // Pick the register which is used by the most LSRUses, which is likely | |||
5026 | // to be a good reuse register candidate. | |||
5027 | const SCEV *Best = nullptr; | |||
5028 | unsigned BestNum = 0; | |||
5029 | for (const SCEV *Reg : RegUses) { | |||
5030 | if (Taken.count(Reg)) | |||
5031 | continue; | |||
5032 | if (!Best) { | |||
5033 | Best = Reg; | |||
5034 | BestNum = RegUses.getUsedByIndices(Reg).count(); | |||
5035 | } else { | |||
5036 | unsigned Count = RegUses.getUsedByIndices(Reg).count(); | |||
5037 | if (Count > BestNum) { | |||
5038 | Best = Reg; | |||
5039 | BestNum = Count; | |||
5040 | } | |||
5041 | ||||
5042 | // If the scores are the same, but the Reg is simpler for the target | |||
5043 | // (for example {x,+,1} as opposed to {x+C,+,1}, where the target can | |||
5044 | // handle +C but not -C), opt for the simpler formula. | |||
5045 | if (Count == BestNum) { | |||
5046 | int LUIdx = RegUses.getUsedByIndices(Reg).find_first(); | |||
5047 | if (LUIdx >= 0 && Uses[LUIdx].Kind == LSRUse::Address && | |||
5048 | IsSimplerBaseSCEVForTarget(TTI, SE, Best, Reg, | |||
5049 | Uses[LUIdx].AccessTy)) { | |||
5050 | Best = Reg; | |||
5051 | BestNum = Count; | |||
5052 | } | |||
5053 | } | |||
5054 | } | |||
5055 | } | |||
5056 | assert(Best && "Failed to find best LSRUse candidate")(static_cast <bool> (Best && "Failed to find best LSRUse candidate" ) ? void (0) : __assert_fail ("Best && \"Failed to find best LSRUse candidate\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 5056, __extension__ __PRETTY_FUNCTION__)); | |||
5057 | ||||
5058 | LLVM_DEBUG(dbgs() << "Narrowing the search space by assuming " << *Bestdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Narrowing the search space by assuming " << *Best << " will yield profitable reuse.\n"; } } while (false) | |||
5059 | << " will yield profitable reuse.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Narrowing the search space by assuming " << *Best << " will yield profitable reuse.\n"; } } while (false); | |||
5060 | Taken.insert(Best); | |||
5061 | ||||
5062 | // In any use with formulae which references this register, delete formulae | |||
5063 | // which don't reference it. | |||
5064 | for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) { | |||
5065 | LSRUse &LU = Uses[LUIdx]; | |||
5066 | if (!LU.Regs.count(Best)) continue; | |||
5067 | ||||
5068 | bool Any = false; | |||
5069 | for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) { | |||
5070 | Formula &F = LU.Formulae[i]; | |||
5071 | if (!F.referencesReg(Best)) { | |||
5072 | LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << " Deleting "; F.print(dbgs ()); dbgs() << '\n'; } } while (false); | |||
5073 | LU.DeleteFormula(F); | |||
5074 | --e; | |||
5075 | --i; | |||
5076 | Any = true; | |||
5077 | assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?")(static_cast <bool> (e != 0 && "Use has no formulae left! Is Regs inconsistent?" ) ? void (0) : __assert_fail ("e != 0 && \"Use has no formulae left! Is Regs inconsistent?\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 5077, __extension__ __PRETTY_FUNCTION__)); | |||
5078 | continue; | |||
5079 | } | |||
5080 | } | |||
5081 | ||||
5082 | if (Any) | |||
5083 | LU.RecomputeRegs(LUIdx, RegUses); | |||
5084 | } | |||
5085 | ||||
5086 | LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "After pre-selection:\n"; print_uses (dbgs()); } } while (false); | |||
5087 | } | |||
5088 | } | |||
5089 | ||||
5090 | /// If there are an extraordinary number of formulae to choose from, use some | |||
5091 | /// rough heuristics to prune down the number of formulae. This keeps the main | |||
5092 | /// solver from taking an extraordinary amount of time in some worst-case | |||
5093 | /// scenarios. | |||
5094 | void LSRInstance::NarrowSearchSpaceUsingHeuristics() { | |||
5095 | NarrowSearchSpaceByDetectingSupersets(); | |||
5096 | NarrowSearchSpaceByCollapsingUnrolledCode(); | |||
5097 | NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(); | |||
5098 | if (FilterSameScaledReg) | |||
5099 | NarrowSearchSpaceByFilterFormulaWithSameScaledReg(); | |||
5100 | NarrowSearchSpaceByFilterPostInc(); | |||
5101 | if (LSRExpNarrow) | |||
5102 | NarrowSearchSpaceByDeletingCostlyFormulas(); | |||
5103 | else | |||
5104 | NarrowSearchSpaceByPickingWinnerRegs(); | |||
5105 | } | |||
5106 | ||||
5107 | /// This is the recursive solver. | |||
5108 | void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution, | |||
5109 | Cost &SolutionCost, | |||
5110 | SmallVectorImpl<const Formula *> &Workspace, | |||
5111 | const Cost &CurCost, | |||
5112 | const SmallPtrSet<const SCEV *, 16> &CurRegs, | |||
5113 | DenseSet<const SCEV *> &VisitedRegs) const { | |||
5114 | // Some ideas: | |||
5115 | // - prune more: | |||
5116 | // - use more aggressive filtering | |||
5117 | // - sort the formula so that the most profitable solutions are found first | |||
5118 | // - sort the uses too | |||
5119 | // - search faster: | |||
5120 | // - don't compute a cost, and then compare. compare while computing a cost | |||
5121 | // and bail early. | |||
5122 | // - track register sets with SmallBitVector | |||
5123 | ||||
5124 | const LSRUse &LU = Uses[Workspace.size()]; | |||
5125 | ||||
5126 | // If this use references any register that's already a part of the | |||
5127 | // in-progress solution, consider it a requirement that a formula must | |||
5128 | // reference that register in order to be considered. This prunes out | |||
5129 | // unprofitable searching. | |||
5130 | SmallSetVector<const SCEV *, 4> ReqRegs; | |||
5131 | for (const SCEV *S : CurRegs) | |||
5132 | if (LU.Regs.count(S)) | |||
5133 | ReqRegs.insert(S); | |||
5134 | ||||
5135 | SmallPtrSet<const SCEV *, 16> NewRegs; | |||
5136 | Cost NewCost(L, SE, TTI, AMK); | |||
5137 | for (const Formula &F : LU.Formulae) { | |||
5138 | // Ignore formulae which may not be ideal in terms of register reuse of | |||
5139 | // ReqRegs. The formula should use all required registers before | |||
5140 | // introducing new ones. | |||
5141 | // This can sometimes (notably when trying to favour postinc) lead to | |||
5142 | // sub-optimial decisions. There it is best left to the cost modelling to | |||
5143 | // get correct. | |||
5144 | if (AMK != TTI::AMK_PostIndexed || LU.Kind != LSRUse::Address) { | |||
5145 | int NumReqRegsToFind = std::min(F.getNumRegs(), ReqRegs.size()); | |||
5146 | for (const SCEV *Reg : ReqRegs) { | |||
5147 | if ((F.ScaledReg && F.ScaledReg == Reg) || | |||
5148 | is_contained(F.BaseRegs, Reg)) { | |||
5149 | --NumReqRegsToFind; | |||
5150 | if (NumReqRegsToFind == 0) | |||
5151 | break; | |||
5152 | } | |||
5153 | } | |||
5154 | if (NumReqRegsToFind != 0) { | |||
5155 | // If none of the formulae satisfied the required registers, then we could | |||
5156 | // clear ReqRegs and try again. Currently, we simply give up in this case. | |||
5157 | continue; | |||
5158 | } | |||
5159 | } | |||
5160 | ||||
5161 | // Evaluate the cost of the current formula. If it's already worse than | |||
5162 | // the current best, prune the search at that point. | |||
5163 | NewCost = CurCost; | |||
5164 | NewRegs = CurRegs; | |||
5165 | NewCost.RateFormula(F, NewRegs, VisitedRegs, LU); | |||
5166 | if (NewCost.isLess(SolutionCost)) { | |||
5167 | Workspace.push_back(&F); | |||
5168 | if (Workspace.size() != Uses.size()) { | |||
5169 | SolveRecurse(Solution, SolutionCost, Workspace, NewCost, | |||
5170 | NewRegs, VisitedRegs); | |||
5171 | if (F.getNumRegs() == 1 && Workspace.size() == 1) | |||
5172 | VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]); | |||
5173 | } else { | |||
5174 | LLVM_DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "New best at "; NewCost.print (dbgs()); dbgs() << ".\nRegs:\n"; for (const SCEV *S : NewRegs ) dbgs() << "- " << *S << "\n"; dbgs() << '\n'; } } while (false) | |||
5175 | dbgs() << ".\nRegs:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "New best at "; NewCost.print (dbgs()); dbgs() << ".\nRegs:\n"; for (const SCEV *S : NewRegs ) dbgs() << "- " << *S << "\n"; dbgs() << '\n'; } } while (false) | |||
5176 | for (const SCEV *S : NewRegs) dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "New best at "; NewCost.print (dbgs()); dbgs() << ".\nRegs:\n"; for (const SCEV *S : NewRegs ) dbgs() << "- " << *S << "\n"; dbgs() << '\n'; } } while (false) | |||
5177 | << "- " << *S << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "New best at "; NewCost.print (dbgs()); dbgs() << ".\nRegs:\n"; for (const SCEV *S : NewRegs ) dbgs() << "- " << *S << "\n"; dbgs() << '\n'; } } while (false) | |||
5178 | dbgs() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "New best at "; NewCost.print (dbgs()); dbgs() << ".\nRegs:\n"; for (const SCEV *S : NewRegs ) dbgs() << "- " << *S << "\n"; dbgs() << '\n'; } } while (false); | |||
5179 | ||||
5180 | SolutionCost = NewCost; | |||
5181 | Solution = Workspace; | |||
5182 | } | |||
5183 | Workspace.pop_back(); | |||
5184 | } | |||
5185 | } | |||
5186 | } | |||
5187 | ||||
5188 | /// Choose one formula from each use. Return the results in the given Solution | |||
5189 | /// vector. | |||
5190 | void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const { | |||
5191 | SmallVector<const Formula *, 8> Workspace; | |||
5192 | Cost SolutionCost(L, SE, TTI, AMK); | |||
5193 | SolutionCost.Lose(); | |||
5194 | Cost CurCost(L, SE, TTI, AMK); | |||
5195 | SmallPtrSet<const SCEV *, 16> CurRegs; | |||
5196 | DenseSet<const SCEV *> VisitedRegs; | |||
5197 | Workspace.reserve(Uses.size()); | |||
5198 | ||||
5199 | // SolveRecurse does all the work. | |||
5200 | SolveRecurse(Solution, SolutionCost, Workspace, CurCost, | |||
5201 | CurRegs, VisitedRegs); | |||
5202 | if (Solution.empty()) { | |||
5203 | LLVM_DEBUG(dbgs() << "\nNo Satisfactory Solution\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "\nNo Satisfactory Solution\n" ; } } while (false); | |||
5204 | return; | |||
5205 | } | |||
5206 | ||||
5207 | // Ok, we've now made all our decisions. | |||
5208 | LLVM_DEBUG(dbgs() << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "\n" "The chosen solution requires " ; SolutionCost.print(dbgs()); dbgs() << ":\n"; for (size_t i = 0, e = Uses.size(); i != e; ++i) { dbgs() << " "; Uses[i].print(dbgs()); dbgs() << "\n" " "; Solution [i]->print(dbgs()); dbgs() << '\n'; }; } } while (false ) | |||
5209 | "The chosen solution requires ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "\n" "The chosen solution requires " ; SolutionCost.print(dbgs()); dbgs() << ":\n"; for (size_t i = 0, e = Uses.size(); i != e; ++i) { dbgs() << " "; Uses[i].print(dbgs()); dbgs() << "\n" " "; Solution [i]->print(dbgs()); dbgs() << '\n'; }; } } while (false ) | |||
5210 | SolutionCost.print(dbgs()); dbgs() << ":\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "\n" "The chosen solution requires " ; SolutionCost.print(dbgs()); dbgs() << ":\n"; for (size_t i = 0, e = Uses.size(); i != e; ++i) { dbgs() << " "; Uses[i].print(dbgs()); dbgs() << "\n" " "; Solution [i]->print(dbgs()); dbgs() << '\n'; }; } } while (false ) | |||
5211 | for (size_t i = 0, e = Uses.size(); i != e; ++i) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "\n" "The chosen solution requires " ; SolutionCost.print(dbgs()); dbgs() << ":\n"; for (size_t i = 0, e = Uses.size(); i != e; ++i) { dbgs() << " "; Uses[i].print(dbgs()); dbgs() << "\n" " "; Solution [i]->print(dbgs()); dbgs() << '\n'; }; } } while (false ) | |||
5212 | dbgs() << " ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "\n" "The chosen solution requires " ; SolutionCost.print(dbgs()); dbgs() << ":\n"; for (size_t i = 0, e = Uses.size(); i != e; ++i) { dbgs() << " "; Uses[i].print(dbgs()); dbgs() << "\n" " "; Solution [i]->print(dbgs()); dbgs() << '\n'; }; } } while (false ) | |||
5213 | Uses[i].print(dbgs());do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "\n" "The chosen solution requires " ; SolutionCost.print(dbgs()); dbgs() << ":\n"; for (size_t i = 0, e = Uses.size(); i != e; ++i) { dbgs() << " "; Uses[i].print(dbgs()); dbgs() << "\n" " "; Solution [i]->print(dbgs()); dbgs() << '\n'; }; } } while (false ) | |||
5214 | dbgs() << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "\n" "The chosen solution requires " ; SolutionCost.print(dbgs()); dbgs() << ":\n"; for (size_t i = 0, e = Uses.size(); i != e; ++i) { dbgs() << " "; Uses[i].print(dbgs()); dbgs() << "\n" " "; Solution [i]->print(dbgs()); dbgs() << '\n'; }; } } while (false ) | |||
5215 | " ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "\n" "The chosen solution requires " ; SolutionCost.print(dbgs()); dbgs() << ":\n"; for (size_t i = 0, e = Uses.size(); i != e; ++i) { dbgs() << " "; Uses[i].print(dbgs()); dbgs() << "\n" " "; Solution [i]->print(dbgs()); dbgs() << '\n'; }; } } while (false ) | |||
5216 | Solution[i]->print(dbgs());do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "\n" "The chosen solution requires " ; SolutionCost.print(dbgs()); dbgs() << ":\n"; for (size_t i = 0, e = Uses.size(); i != e; ++i) { dbgs() << " "; Uses[i].print(dbgs()); dbgs() << "\n" " "; Solution [i]->print(dbgs()); dbgs() << '\n'; }; } } while (false ) | |||
5217 | dbgs() << '\n';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "\n" "The chosen solution requires " ; SolutionCost.print(dbgs()); dbgs() << ":\n"; for (size_t i = 0, e = Uses.size(); i != e; ++i) { dbgs() << " "; Uses[i].print(dbgs()); dbgs() << "\n" " "; Solution [i]->print(dbgs()); dbgs() << '\n'; }; } } while (false ) | |||
5218 | })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "\n" "The chosen solution requires " ; SolutionCost.print(dbgs()); dbgs() << ":\n"; for (size_t i = 0, e = Uses.size(); i != e; ++i) { dbgs() << " "; Uses[i].print(dbgs()); dbgs() << "\n" " "; Solution [i]->print(dbgs()); dbgs() << '\n'; }; } } while (false ); | |||
5219 | ||||
5220 | assert(Solution.size() == Uses.size() && "Malformed solution!")(static_cast <bool> (Solution.size() == Uses.size() && "Malformed solution!") ? void (0) : __assert_fail ("Solution.size() == Uses.size() && \"Malformed solution!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 5220, __extension__ __PRETTY_FUNCTION__)); | |||
5221 | ||||
5222 | if (BaselineCost.isLess(SolutionCost)) { | |||
5223 | LLVM_DEBUG(dbgs() << "The baseline solution requires ";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "The baseline solution requires " ; BaselineCost.print(dbgs()); dbgs() << "\n"; } } while (false) | |||
5224 | BaselineCost.print(dbgs()); dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "The baseline solution requires " ; BaselineCost.print(dbgs()); dbgs() << "\n"; } } while (false); | |||
5225 | if (!AllowDropSolutionIfLessProfitable) | |||
5226 | LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Baseline is more profitable than chosen solution, " "add option 'lsr-drop-solution' to drop LSR solution.\n"; } } while (false) | |||
5227 | dbgs() << "Baseline is more profitable than chosen solution, "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Baseline is more profitable than chosen solution, " "add option 'lsr-drop-solution' to drop LSR solution.\n"; } } while (false) | |||
5228 | "add option 'lsr-drop-solution' to drop LSR solution.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Baseline is more profitable than chosen solution, " "add option 'lsr-drop-solution' to drop LSR solution.\n"; } } while (false); | |||
5229 | else { | |||
5230 | LLVM_DEBUG(dbgs() << "Baseline is more profitable than chosen "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Baseline is more profitable than chosen " "solution, dropping LSR solution.\n";; } } while (false) | |||
5231 | "solution, dropping LSR solution.\n";)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType ("loop-reduce")) { dbgs() << "Baseline is more profitable than chosen " "solution, dropping LSR solution.\n";; } } while (false); | |||
5232 | Solution.clear(); | |||
5233 | } | |||
5234 | } | |||
5235 | } | |||
5236 | ||||
5237 | /// Helper for AdjustInsertPositionForExpand. Climb up the dominator tree far as | |||
5238 | /// we can go while still being dominated by the input positions. This helps | |||
5239 | /// canonicalize the insert position, which encourages sharing. | |||
5240 | BasicBlock::iterator | |||
5241 | LSRInstance::HoistInsertPosition(BasicBlock::iterator IP, | |||
5242 | const SmallVectorImpl<Instruction *> &Inputs) | |||
5243 | const { | |||
5244 | Instruction *Tentative = &*IP; | |||
5245 | while (true) { | |||
5246 | bool AllDominate = true; | |||
5247 | Instruction *BetterPos = nullptr; | |||
5248 | // Don't bother attempting to insert before a catchswitch, their basic block | |||
5249 | // cannot have other non-PHI instructions. | |||
5250 | if (isa<CatchSwitchInst>(Tentative)) | |||
5251 | return IP; | |||
5252 | ||||
5253 | for (Instruction *Inst : Inputs) { | |||
5254 | if (Inst == Tentative || !DT.dominates(Inst, Tentative)) { | |||
5255 | AllDominate = false; | |||
5256 | break; | |||
5257 | } | |||
5258 | // Attempt to find an insert position in the middle of the block, | |||
5259 | // instead of at the end, so that it can be used for other expansions. | |||
5260 | if (Tentative->getParent() == Inst->getParent() && | |||
5261 | (!BetterPos || !DT.dominates(Inst, BetterPos))) | |||
5262 | BetterPos = &*std::next(BasicBlock::iterator(Inst)); | |||
5263 | } | |||
5264 | if (!AllDominate) | |||
5265 | break; | |||
5266 | if (BetterPos) | |||
5267 | IP = BetterPos->getIterator(); | |||
5268 | else | |||
5269 | IP = Tentative->getIterator(); | |||
5270 | ||||
5271 | const Loop *IPLoop = LI.getLoopFor(IP->getParent()); | |||
5272 | unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0; | |||
5273 | ||||
5274 | BasicBlock *IDom; | |||
5275 | for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) { | |||
5276 | if (!Rung) return IP; | |||
5277 | Rung = Rung->getIDom(); | |||
5278 | if (!Rung) return IP; | |||
5279 | IDom = Rung->getBlock(); | |||
5280 | ||||
5281 | // Don't climb into a loop though. | |||
5282 | const Loop *IDomLoop = LI.getLoopFor(IDom); | |||
5283 | unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0; | |||
5284 | if (IDomDepth <= IPLoopDepth && | |||
5285 | (IDomDepth != IPLoopDepth || IDomLoop == IPLoop)) | |||
5286 | break; | |||
5287 | } | |||
5288 | ||||
5289 | Tentative = IDom->getTerminator(); | |||
5290 | } | |||
5291 | ||||
5292 | return IP; | |||
5293 | } | |||
5294 | ||||
5295 | /// Determine an input position which will be dominated by the operands and | |||
5296 | /// which will dominate the result. | |||
5297 | BasicBlock::iterator LSRInstance::AdjustInsertPositionForExpand( | |||
5298 | BasicBlock::iterator LowestIP, const LSRFixup &LF, const LSRUse &LU) const { | |||
5299 | // Collect some instructions which must be dominated by the | |||
5300 | // expanding replacement. These must be dominated by any operands that | |||
5301 | // will be required in the expansion. | |||
5302 | SmallVector<Instruction *, 4> Inputs; | |||
5303 | if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace)) | |||
5304 | Inputs.push_back(I); | |||
5305 | if (LU.Kind == LSRUse::ICmpZero) | |||
5306 | if (Instruction *I = | |||
5307 | dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1))) | |||
5308 | Inputs.push_back(I); | |||
5309 | if (LF.PostIncLoops.count(L)) { | |||
5310 | if (LF.isUseFullyOutsideLoop(L)) | |||
5311 | Inputs.push_back(L->getLoopLatch()->getTerminator()); | |||
5312 | else | |||
5313 | Inputs.push_back(IVIncInsertPos); | |||
5314 | } | |||
5315 | // The expansion must also be dominated by the increment positions of any | |||
5316 | // loops it for which it is using post-inc mode. | |||
5317 | for (const Loop *PIL : LF.PostIncLoops) { | |||
5318 | if (PIL == L) continue; | |||
5319 | ||||
5320 | // Be dominated by the loop exit. | |||
5321 | SmallVector<BasicBlock *, 4> ExitingBlocks; | |||
5322 | PIL->getExitingBlocks(ExitingBlocks); | |||
5323 | if (!ExitingBlocks.empty()) { | |||
5324 | BasicBlock *BB = ExitingBlocks[0]; | |||
5325 | for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i) | |||
5326 | BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]); | |||
5327 | Inputs.push_back(BB->getTerminator()); | |||
5328 | } | |||
5329 | } | |||
5330 | ||||
5331 | assert(!isa<PHINode>(LowestIP) && !LowestIP->isEHPad()(static_cast <bool> (!isa<PHINode>(LowestIP) && !LowestIP->isEHPad() && !isa<DbgInfoIntrinsic> (LowestIP) && "Insertion point must be a normal instruction" ) ? void (0) : __assert_fail ("!isa<PHINode>(LowestIP) && !LowestIP->isEHPad() && !isa<DbgInfoIntrinsic>(LowestIP) && \"Insertion point must be a normal instruction\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 5333, __extension__ __PRETTY_FUNCTION__)) | |||
5332 | && !isa<DbgInfoIntrinsic>(LowestIP) &&(static_cast <bool> (!isa<PHINode>(LowestIP) && !LowestIP->isEHPad() && !isa<DbgInfoIntrinsic> (LowestIP) && "Insertion point must be a normal instruction" ) ? void (0) : __assert_fail ("!isa<PHINode>(LowestIP) && !LowestIP->isEHPad() && !isa<DbgInfoIntrinsic>(LowestIP) && \"Insertion point must be a normal instruction\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 5333, __extension__ __PRETTY_FUNCTION__)) | |||
5333 | "Insertion point must be a normal instruction")(static_cast <bool> (!isa<PHINode>(LowestIP) && !LowestIP->isEHPad() && !isa<DbgInfoIntrinsic> (LowestIP) && "Insertion point must be a normal instruction" ) ? void (0) : __assert_fail ("!isa<PHINode>(LowestIP) && !LowestIP->isEHPad() && !isa<DbgInfoIntrinsic>(LowestIP) && \"Insertion point must be a normal instruction\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 5333, __extension__ __PRETTY_FUNCTION__)); | |||
5334 | ||||
5335 | // Then, climb up the immediate dominator tree as far as we can go while | |||
5336 | // still being dominated by the input positions. | |||
5337 | BasicBlock::iterator IP = HoistInsertPosition(LowestIP, Inputs); | |||
5338 | ||||
5339 | // Don't insert instructions before PHI nodes. | |||
5340 | while (isa<PHINode>(IP)) ++IP; | |||
5341 | ||||
5342 | // Ignore landingpad instructions. | |||
5343 | while (IP->isEHPad()) ++IP; | |||
5344 | ||||
5345 | // Ignore debug intrinsics. | |||
5346 | while (isa<DbgInfoIntrinsic>(IP)) ++IP; | |||
5347 | ||||
5348 | // Set IP below instructions recently inserted by SCEVExpander. This keeps the | |||
5349 | // IP consistent across expansions and allows the previously inserted | |||
5350 | // instructions to be reused by subsequent expansion. | |||
5351 | while (Rewriter.isInsertedInstruction(&*IP) && IP != LowestIP) | |||
5352 | ++IP; | |||
5353 | ||||
5354 | return IP; | |||
5355 | } | |||
5356 | ||||
5357 | /// Emit instructions for the leading candidate expression for this LSRUse (this | |||
5358 | /// is called "expanding"). | |||
5359 | Value *LSRInstance::Expand(const LSRUse &LU, const LSRFixup &LF, | |||
5360 | const Formula &F, BasicBlock::iterator IP, | |||
5361 | SmallVectorImpl<WeakTrackingVH> &DeadInsts) const { | |||
5362 | if (LU.RigidFormula) | |||
5363 | return LF.OperandValToReplace; | |||
5364 | ||||
5365 | // Determine an input position which will be dominated by the operands and | |||
5366 | // which will dominate the result. | |||
5367 | IP = AdjustInsertPositionForExpand(IP, LF, LU); | |||
5368 | Rewriter.setInsertPoint(&*IP); | |||
5369 | ||||
5370 | // Inform the Rewriter if we have a post-increment use, so that it can | |||
5371 | // perform an advantageous expansion. | |||
5372 | Rewriter.setPostInc(LF.PostIncLoops); | |||
5373 | ||||
5374 | // This is the type that the user actually needs. | |||
5375 | Type *OpTy = LF.OperandValToReplace->getType(); | |||
5376 | // This will be the type that we'll initially expand to. | |||
5377 | Type *Ty = F.getType(); | |||
5378 | if (!Ty) | |||
5379 | // No type known; just expand directly to the ultimate type. | |||
5380 | Ty = OpTy; | |||
5381 | else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy)) | |||
5382 | // Expand directly to the ultimate type if it's the right size. | |||
5383 | Ty = OpTy; | |||
5384 | // This is the type to do integer arithmetic in. | |||
5385 | Type *IntTy = SE.getEffectiveSCEVType(Ty); | |||
5386 | ||||
5387 | // Build up a list of operands to add together to form the full base. | |||
5388 | SmallVector<const SCEV *, 8> Ops; | |||
5389 | ||||
5390 | // Expand the BaseRegs portion. | |||
5391 | for (const SCEV *Reg : F.BaseRegs) { | |||
5392 | assert(!Reg->isZero() && "Zero allocated in a base register!")(static_cast <bool> (!Reg->isZero() && "Zero allocated in a base register!" ) ? void (0) : __assert_fail ("!Reg->isZero() && \"Zero allocated in a base register!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 5392, __extension__ __PRETTY_FUNCTION__)); | |||
5393 | ||||
5394 | // If we're expanding for a post-inc user, make the post-inc adjustment. | |||
5395 | Reg = denormalizeForPostIncUse(Reg, LF.PostIncLoops, SE); | |||
5396 | Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr))); | |||
5397 | } | |||
5398 | ||||
5399 | // Expand the ScaledReg portion. | |||
5400 | Value *ICmpScaledV = nullptr; | |||
5401 | if (F.Scale != 0) { | |||
5402 | const SCEV *ScaledS = F.ScaledReg; | |||
5403 | ||||
5404 | // If we're expanding for a post-inc user, make the post-inc adjustment. | |||
5405 | PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops); | |||
5406 | ScaledS = denormalizeForPostIncUse(ScaledS, Loops, SE); | |||
5407 | ||||
5408 | if (LU.Kind == LSRUse::ICmpZero) { | |||
5409 | // Expand ScaleReg as if it was part of the base regs. | |||
5410 | if (F.Scale == 1) | |||
5411 | Ops.push_back( | |||
5412 | SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr))); | |||
5413 | else { | |||
5414 | // An interesting way of "folding" with an icmp is to use a negated | |||
5415 | // scale, which we'll implement by inserting it into the other operand | |||
5416 | // of the icmp. | |||
5417 | assert(F.Scale == -1 &&(static_cast <bool> (F.Scale == -1 && "The only scale supported by ICmpZero uses is -1!" ) ? void (0) : __assert_fail ("F.Scale == -1 && \"The only scale supported by ICmpZero uses is -1!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 5418, __extension__ __PRETTY_FUNCTION__)) | |||
5418 | "The only scale supported by ICmpZero uses is -1!")(static_cast <bool> (F.Scale == -1 && "The only scale supported by ICmpZero uses is -1!" ) ? void (0) : __assert_fail ("F.Scale == -1 && \"The only scale supported by ICmpZero uses is -1!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 5418, __extension__ __PRETTY_FUNCTION__)); | |||
5419 | ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr); | |||
5420 | } | |||
5421 | } else { | |||
5422 | // Otherwise just expand the scaled register and an explicit scale, | |||
5423 | // which is expected to be matched as part of the address. | |||
5424 | ||||
5425 | // Flush the operand list to suppress SCEVExpander hoisting address modes. | |||
5426 | // Unless the addressing mode will not be folded. | |||
5427 | if (!Ops.empty() && LU.Kind == LSRUse::Address && | |||
5428 | isAMCompletelyFolded(TTI, LU, F)) { | |||
5429 | Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), nullptr); | |||
5430 | Ops.clear(); | |||
5431 | Ops.push_back(SE.getUnknown(FullV)); | |||
5432 | } | |||
5433 | ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr)); | |||
5434 | if (F.Scale != 1) | |||
5435 | ScaledS = | |||
5436 | SE.getMulExpr(ScaledS, SE.getConstant(ScaledS->getType(), F.Scale)); | |||
5437 | Ops.push_back(ScaledS); | |||
5438 | } | |||
5439 | } | |||
5440 | ||||
5441 | // Expand the GV portion. | |||
5442 | if (F.BaseGV) { | |||
5443 | // Flush the operand list to suppress SCEVExpander hoisting. | |||
5444 | if (!Ops.empty()) { | |||
5445 | Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), IntTy); | |||
5446 | Ops.clear(); | |||
5447 | Ops.push_back(SE.getUnknown(FullV)); | |||
5448 | } | |||
5449 | Ops.push_back(SE.getUnknown(F.BaseGV)); | |||
5450 | } | |||
5451 | ||||
5452 | // Flush the operand list to suppress SCEVExpander hoisting of both folded and | |||
5453 | // unfolded offsets. LSR assumes they both live next to their uses. | |||
5454 | if (!Ops.empty()) { | |||
5455 | Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty); | |||
5456 | Ops.clear(); | |||
5457 | Ops.push_back(SE.getUnknown(FullV)); | |||
5458 | } | |||
5459 | ||||
5460 | // Expand the immediate portion. | |||
5461 | int64_t Offset = (uint64_t)F.BaseOffset + LF.Offset; | |||
5462 | if (Offset != 0) { | |||
5463 | if (LU.Kind == LSRUse::ICmpZero) { | |||
5464 | // The other interesting way of "folding" with an ICmpZero is to use a | |||
5465 | // negated immediate. | |||
5466 | if (!ICmpScaledV) | |||
5467 | ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset); | |||
5468 | else { | |||
5469 | Ops.push_back(SE.getUnknown(ICmpScaledV)); | |||
5470 | ICmpScaledV = ConstantInt::get(IntTy, Offset); | |||
5471 | } | |||
5472 | } else { | |||
5473 | // Just add the immediate values. These again are expected to be matched | |||
5474 | // as part of the address. | |||
5475 | Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset))); | |||
5476 | } | |||
5477 | } | |||
5478 | ||||
5479 | // Expand the unfolded offset portion. | |||
5480 | int64_t UnfoldedOffset = F.UnfoldedOffset; | |||
5481 | if (UnfoldedOffset != 0) { | |||
5482 | // Just add the immediate values. | |||
5483 | Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, | |||
5484 | UnfoldedOffset))); | |||
5485 | } | |||
5486 | ||||
5487 | // Emit instructions summing all the operands. | |||
5488 | const SCEV *FullS = Ops.empty() ? | |||
5489 | SE.getConstant(IntTy, 0) : | |||
5490 | SE.getAddExpr(Ops); | |||
5491 | Value *FullV = Rewriter.expandCodeFor(FullS, Ty); | |||
5492 | ||||
5493 | // We're done expanding now, so reset the rewriter. | |||
5494 | Rewriter.clearPostInc(); | |||
5495 | ||||
5496 | // An ICmpZero Formula represents an ICmp which we're handling as a | |||
5497 | // comparison against zero. Now that we've expanded an expression for that | |||
5498 | // form, update the ICmp's other operand. | |||
5499 | if (LU.Kind == LSRUse::ICmpZero) { | |||
5500 | ICmpInst *CI = cast<ICmpInst>(LF.UserInst); | |||
5501 | if (auto *OperandIsInstr = dyn_cast<Instruction>(CI->getOperand(1))) | |||
5502 | DeadInsts.emplace_back(OperandIsInstr); | |||
5503 | assert(!F.BaseGV && "ICmp does not support folding a global value and "(static_cast <bool> (!F.BaseGV && "ICmp does not support folding a global value and " "a scale at the same time!") ? void (0) : __assert_fail ("!F.BaseGV && \"ICmp does not support folding a global value and \" \"a scale at the same time!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 5504, __extension__ __PRETTY_FUNCTION__)) | |||
5504 | "a scale at the same time!")(static_cast <bool> (!F.BaseGV && "ICmp does not support folding a global value and " "a scale at the same time!") ? void (0) : __assert_fail ("!F.BaseGV && \"ICmp does not support folding a global value and \" \"a scale at the same time!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 5504, __extension__ __PRETTY_FUNCTION__)); | |||
5505 | if (F.Scale == -1) { | |||
5506 | if (ICmpScaledV->getType() != OpTy) { | |||
5507 | Instruction *Cast = | |||
5508 | CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false, | |||
5509 | OpTy, false), | |||
5510 | ICmpScaledV, OpTy, "tmp", CI); | |||
5511 | ICmpScaledV = Cast; | |||
5512 | } | |||
5513 | CI->setOperand(1, ICmpScaledV); | |||
5514 | } else { | |||
5515 | // A scale of 1 means that the scale has been expanded as part of the | |||
5516 | // base regs. | |||
5517 | assert((F.Scale == 0 || F.Scale == 1) &&(static_cast <bool> ((F.Scale == 0 || F.Scale == 1) && "ICmp does not support folding a global value and " "a scale at the same time!" ) ? void (0) : __assert_fail ("(F.Scale == 0 || F.Scale == 1) && \"ICmp does not support folding a global value and \" \"a scale at the same time!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 5519, __extension__ __PRETTY_FUNCTION__)) | |||
5518 | "ICmp does not support folding a global value and "(static_cast <bool> ((F.Scale == 0 || F.Scale == 1) && "ICmp does not support folding a global value and " "a scale at the same time!" ) ? void (0) : __assert_fail ("(F.Scale == 0 || F.Scale == 1) && \"ICmp does not support folding a global value and \" \"a scale at the same time!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 5519, __extension__ __PRETTY_FUNCTION__)) | |||
5519 | "a scale at the same time!")(static_cast <bool> ((F.Scale == 0 || F.Scale == 1) && "ICmp does not support folding a global value and " "a scale at the same time!" ) ? void (0) : __assert_fail ("(F.Scale == 0 || F.Scale == 1) && \"ICmp does not support folding a global value and \" \"a scale at the same time!\"" , "llvm/lib/Transforms/Scalar/LoopStrengthReduce.cpp", 5519, __extension__ __PRETTY_FUNCTION__)); | |||
5520 | Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy), | |||
5521 | -(uint64_t)Offset); | |||
5522 | if (C->getType() != OpTy) | |||
5523 | C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false, | |||
5524 | OpTy, false), | |||
5525 | C, OpTy); | |||
5526 | ||||
5527 | CI->setOperand(1, C); | |||
5528 | } | |||
5529 | } | |||
5530 | ||||
5531 | return FullV; | |||
5532 | } | |||
5533 | ||||
5534 | /// Helper for Rewrite. PHI nodes are special because the use of their operands | |||
5535 | /// effectively happens in their predecessor blocks, so the expression may need | |||
5536 | /// to be expanded in multiple places. | |||
5537 | void LSRInstance::RewriteForPHI( | |||
5538 | PHINode *PN, const LSRUse &LU, const LSRFixup &LF, const Formula &F, | |||
5539 | SmallVectorImpl<WeakTrackingVH> &DeadInsts) const { | |||
5540 | DenseMap<BasicBlock *, Value *> Inserted; | |||
5541 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) | |||
| ||||
5542 | if (PN->getIncomingValue(i) == LF.OperandValToReplace) { | |||
5543 | bool needUpdateFixups = false; | |||
5544 | BasicBlock *BB = PN->getIncomingBlock(i); | |||
5545 | ||||
5546 | // If this is a critical edge, split the edge so that we do not insert | |||
5547 | // the code on all predecessor/successor paths. We do this unless this | |||
5548 | // is the canonical backedge for this loop, which complicates post-inc | |||
5549 | // users. | |||
5550 | if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 && | |||
5551 | !isa<IndirectBrInst>(BB->getTerminator()) && | |||
5552 | !isa<CatchSwitchInst>(BB->getTerminator())) { | |||
5553 | BasicBlock *Parent = PN->getParent(); | |||
5554 | Loop *PNLoop = LI.getLoopFor(Parent); | |||
5555 | if (!PNLoop || Parent != PNLoop->getHeader()) { | |||
5556 | // Split the critical edge. | |||
5557 | BasicBlock *NewBB = nullptr; | |||
5558 | if (!Parent->isLandingPad()) { | |||
5559 | NewBB = | |||
5560 | SplitCriticalEdge(BB, Parent, | |||
5561 | CriticalEdgeSplittingOptions(&DT, &LI, MSSAU) | |||
5562 | .setMergeIdenticalEdges() | |||
5563 | .setKeepOneInputPHIs()); | |||
5564 | } else { | |||
5565 | SmallVector<BasicBlock*, 2> NewBBs; | |||
5566 | SplitLandingPadPredecessors(Parent, BB, "", "", NewBBs, &DT, &LI); | |||
5567 | NewBB = NewBBs[0]; | |||
5568 | } | |||
5569 | // If NewBB==NULL, then SplitCriticalEdge refused to split because all | |||
5570 | // phi predecessors are identical. The simple thing to do is skip | |||
5571 | // splitting in this case rather than complicate the API. | |||
5572 | if (NewBB) { | |||
5573 | // If PN is outside of the loop and BB is in the loop, we want to | |||
5574 | // move the block to be immediately before the PHI block, not | |||
5575 | // immediately after BB. | |||
5576 | if (L->contains(BB) && !L->contains(PN)) | |||
5577 | NewBB->moveBefore(PN->getParent()); | |||
5578 | ||||
5579 | // Splitting the edge can reduce the number of PHI entries we have. | |||
5580 | e = PN->getNumIncomingValues(); | |||
5581 | BB = NewBB; | |||
5582 | i = PN->getBasicBlockIndex(BB); | |||
5583 | ||||
5584 | needUpdateFixups = true; | |||
5585 | } | |||
5586 | } | |||
5587 | } | |||
5588 | ||||
5589 | std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair = | |||
5590 | Inserted.insert(std::make_pair(BB, static_cast<Value *>(nullptr))); | |||
5591 | if (!Pair.second) | |||
5592 | PN->setIncomingValue(i, Pair.first->second); | |||
5593 | else { | |||
5594 | Value *FullV = | |||
5595 | Expand(LU, LF, F, BB->getTerminator()->getIterator(), DeadInsts); | |||
5596 | ||||
5597 | // If this is reuse-by-noop-cast, insert the noop cast. | |||
5598 | Type *OpTy = LF.OperandValToReplace->getType(); | |||
| ||||
5599 | if (FullV->getType() != OpTy) | |||
5600 | FullV = | |||
5601 | CastInst::Create(CastInst::getCastOpcode(FullV, false, | |||
5602 | OpTy, false), | |||
5603 | FullV, LF.OperandValToReplace->getType(), | |||
5604 | "tmp", BB->getTerminator()); | |||
5605 | ||||
5606 | PN->setIncomingValue(i, FullV); | |||
5607 | Pair.first->second = FullV; | |||
5608 | } | |||
5609 | ||||
5610 | // If LSR splits critical edge and phi node has other pending | |||
5611 | // fixup operands, we need to update those pending fixups. Otherwise | |||
5612 | // formulae will not be implemented completely and some instructions | |||
5613 | // will not be eliminated. | |||
5614 | if (needUpdateFixups) { | |||
5615 | for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) | |||
5616 | for (LSRFixup &Fixup : Uses[LUIdx].Fixups) | |||
5617 | // If fixup is supposed to rewrite some operand in the phi | |||
5618 | // that was just updated, it may be already moved to | |||
5619 | // another phi node. Such fixup requires update. | |||
5620 | if (Fixup.UserInst == PN) { | |||
5621 | // Check if the operand we try to replace still exists in the | |||
5622 | // original phi. | |||
5623 | bool foundInOriginalPHI = false; | |||
5624 | for (const auto &val : PN->incoming_values()) | |||
5625 | if (val == Fixup.OperandValToReplace) { | |||
5626 | foundInOriginalPHI = true; | |||
5627 | break; | |||
5628 | } | |||
5629 | ||||
5630 | // If fixup operand found in original PHI - nothing to do. | |||
5631 | if (foundInOriginalPHI) | |||
5632 | continue; | |||
5633 | ||||
5634 | // Otherwise it might be moved to another PHI and requires update. | |||
5635 | // If fixup operand not found in any of the incoming blocks that | |||
5636 | // means we have already rewritten it - nothing to do. | |||
5637 | for (const auto &Block : PN->blocks()) | |||
5638 | for (BasicBlock::iterator I = Block->begin(); isa<PHINode>(I); | |||
5639 | ++I) { | |||
5640 | PHINode *NewPN = cast<PHINode>(I); | |||
5641 | for (const auto &val : NewPN->incoming_values()) | |||
5642 | if (val == Fixup.OperandValToReplace) | |||
5643 | Fixup.UserInst = NewPN; | |||
5644 | } | |||
5645 | } | |||
5646 | } | |||
5647 | } | |||
5648 | } | |||
5649 | ||||
5650 | /// Emit instructions for the leading candidate expression for this LSRUse (this | |||
5651 | /// is called "expanding"), and update the UserInst to reference the newly | |||
5652 | /// expanded value. | |||
5653 | void LSRInstance::Rewrite(const LSRUse &LU, const LSRFixup &LF, | |||
5654 | const Formula &F, | |||
5655 | SmallVectorImpl<WeakTrackingVH> &DeadInsts) const { | |||
5656 | // First, find an insertion point that dominates UserInst. For PHI nodes, | |||
5657 | // find the nearest block which dominates all the relevant uses. | |||
5658 | if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) { | |||
5659 | RewriteForPHI(PN, LU, LF, F, DeadInsts); | |||
5660 | } else { | |||
5661 | Value *FullV = Expand(LU, LF, F, LF.UserInst->getIterator(), DeadInsts); | |||
5662 | ||||
5663 | // If this is reuse-by-noop-cast, insert the noop cast. | |||
5664 | Type *OpTy = LF.OperandValToReplace->getType(); | |||
5665 | if (FullV->getType() != OpTy) { | |||
5666 | Instruction *Cast = | |||
5667 | CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false), | |||
5668 | FullV, OpTy, "tmp", LF.UserInst); | |||