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