blob: 773777ac804f179302fc395bca6bc16a42e58d84 [file] [log] [blame]
Dan Gohman0a40ad92009-04-16 03:18:22 +00001//===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Nate Begemanb18121e2004-10-18 21:08:22 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Nate Begemanb18121e2004-10-18 21:08:22 +00008//===----------------------------------------------------------------------===//
9//
Dan Gohman97f70ad2009-05-19 20:37:36 +000010// This transformation analyzes and transforms the induction variables (and
11// computations derived from them) into forms suitable for efficient execution
12// on the target.
13//
Nate Begemanb18121e2004-10-18 21:08:22 +000014// This pass performs a strength reduction on array references inside loops that
Dan Gohman97f70ad2009-05-19 20:37:36 +000015// have as one or more of their components the loop induction variable, it
16// rewrites expressions to take advantage of scaled-index addressing modes
17// available on the target, and it performs a variety of other optimizations
18// related to loop induction variables.
Nate Begemanb18121e2004-10-18 21:08:22 +000019//
Dan Gohman45774ce2010-02-12 10:34:29 +000020// Terminology note: this code has a lot of handling for "post-increment" or
21// "post-inc" users. This is not talking about post-increment addressing modes;
22// it is instead talking about code like this:
23//
24// %i = phi [ 0, %entry ], [ %i.next, %latch ]
25// ...
26// %i.next = add %i, 1
27// %c = icmp eq %i.next, %n
28//
29// The SCEV for %i is {0,+,1}<%L>. The SCEV for %i.next is {1,+,1}<%L>, however
30// it's useful to think about these as the same register, with some uses using
Sanjoy Das7041fb12015-03-27 06:01:56 +000031// the value of the register before the add and some using it after. In this
Dan Gohman45774ce2010-02-12 10:34:29 +000032// example, the icmp is a post-increment user, since it uses %i.next, which is
33// the value of the induction variable after the increment. The other common
34// case of post-increment users is users outside the loop.
35//
36// TODO: More sophistication in the way Formulae are generated and filtered.
37//
38// TODO: Handle multiple loops at a time.
39//
Chandler Carruth26c59fa2013-01-07 14:41:08 +000040// TODO: Should the addressing mode BaseGV be changed to a ConstantExpr instead
41// of a GlobalValue?
Dan Gohman45774ce2010-02-12 10:34:29 +000042//
43// TODO: When truncation is free, truncate ICmp users' operands to make it a
44// smaller encoding (on x86 at least).
45//
46// TODO: When a negated register is used by an add (such as in a list of
47// multiple base registers, or as the increment expression in an addrec),
48// we may not actually need both reg and (-1 * reg) in registers; the
49// negation can be implemented by using a sub instead of an add. The
50// lack of support for taking this into consideration when making
51// register pressure decisions is partly worked around by the "Special"
52// use kind.
53//
Nate Begemanb18121e2004-10-18 21:08:22 +000054//===----------------------------------------------------------------------===//
55
Chandler Carruthed0881b2012-12-03 16:50:05 +000056#include "llvm/Transforms/Scalar.h"
57#include "llvm/ADT/DenseSet.h"
Benjamin Kramer62fb0cf2014-03-15 17:17:48 +000058#include "llvm/ADT/Hashing.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000059#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000060#include "llvm/ADT/SetVector.h"
61#include "llvm/ADT/SmallBitVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000062#include "llvm/Analysis/IVUsers.h"
Devang Patelb0743b52007-03-06 21:14:09 +000063#include "llvm/Analysis/LoopPass.h"
Nate Begemane68bcd12005-07-30 00:15:07 +000064#include "llvm/Analysis/ScalarEvolutionExpander.h"
Chandler Carruth26c59fa2013-01-07 14:41:08 +000065#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000066#include "llvm/IR/Constants.h"
67#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000068#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000069#include "llvm/IR/Instructions.h"
70#include "llvm/IR/IntrinsicInst.h"
Mehdi Aminia28d91d2015-03-10 02:37:25 +000071#include "llvm/IR/Module.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000072#include "llvm/IR/ValueHandle.h"
Andrew Trick58124392011-09-27 00:44:14 +000073#include "llvm/Support/CommandLine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000074#include "llvm/Support/Debug.h"
Daniel Dunbar6115b392009-07-26 09:48:23 +000075#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000076#include "llvm/Transforms/Utils/BasicBlockUtils.h"
77#include "llvm/Transforms/Utils/Local.h"
Jeff Cohenc5009912005-07-30 18:22:27 +000078#include <algorithm>
Nate Begemanb18121e2004-10-18 21:08:22 +000079using namespace llvm;
80
Chandler Carruth964daaa2014-04-22 02:55:47 +000081#define DEBUG_TYPE "loop-reduce"
82
Andrew Trick19f80c12012-04-18 04:00:10 +000083/// MaxIVUsers is an arbitrary threshold that provides an early opportunitiy for
84/// bail out. This threshold is far beyond the number of users that LSR can
85/// conceivably solve, so it should not affect generated code, but catches the
86/// worst cases before LSR burns too much compile time and stack space.
87static const unsigned MaxIVUsers = 200;
88
Andrew Trickecbe22b2011-10-11 02:30:45 +000089// Temporary flag to cleanup congruent phis after LSR phi expansion.
90// It's currently disabled until we can determine whether it's truly useful or
91// not. The flag should be removed after the v3.0 release.
Andrew Trick06f6c052012-01-07 07:08:17 +000092// This is now needed for ivchains.
Benjamin Kramer7ba71be2011-11-26 23:01:57 +000093static cl::opt<bool> EnablePhiElim(
Andrew Trick06f6c052012-01-07 07:08:17 +000094 "enable-lsr-phielim", cl::Hidden, cl::init(true),
95 cl::desc("Enable LSR phi elimination"));
Andrew Trick58124392011-09-27 00:44:14 +000096
Andrew Trick248d4102012-01-09 21:18:52 +000097#ifndef NDEBUG
98// Stress test IV chain generation.
99static cl::opt<bool> StressIVChain(
100 "stress-ivchain", cl::Hidden, cl::init(false),
101 cl::desc("Stress test LSR IV chains"));
102#else
103static bool StressIVChain = false;
104#endif
105
Dan Gohman45774ce2010-02-12 10:34:29 +0000106namespace {
Nate Begemanb18121e2004-10-18 21:08:22 +0000107
Dan Gohman45774ce2010-02-12 10:34:29 +0000108/// RegSortData - This class holds data which is used to order reuse candidates.
109class RegSortData {
110public:
111 /// UsedByIndices - This represents the set of LSRUse indices which reference
112 /// a particular register.
113 SmallBitVector UsedByIndices;
114
Dan Gohman45774ce2010-02-12 10:34:29 +0000115 void print(raw_ostream &OS) const;
116 void dump() const;
117};
118
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000119}
Dan Gohman45774ce2010-02-12 10:34:29 +0000120
121void RegSortData::print(raw_ostream &OS) const {
122 OS << "[NumUses=" << UsedByIndices.count() << ']';
123}
124
Manman Ren49d684e2012-09-12 05:06:18 +0000125#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman45774ce2010-02-12 10:34:29 +0000126void RegSortData::dump() const {
127 print(errs()); errs() << '\n';
128}
Manman Renc3366cc2012-09-06 19:55:56 +0000129#endif
Dan Gohman2a12ae72009-02-20 04:17:46 +0000130
Chris Lattner79a42ac2006-12-19 21:40:18 +0000131namespace {
Dale Johannesene3a02be2007-03-20 00:47:50 +0000132
Dan Gohman45774ce2010-02-12 10:34:29 +0000133/// RegUseTracker - Map register candidates to information about how they are
134/// used.
135class RegUseTracker {
136 typedef DenseMap<const SCEV *, RegSortData> RegUsesTy;
Dale Johannesene3a02be2007-03-20 00:47:50 +0000137
Dan Gohman248c41d2010-05-18 22:33:00 +0000138 RegUsesTy RegUsesMap;
Dan Gohman45774ce2010-02-12 10:34:29 +0000139 SmallVector<const SCEV *, 16> RegSequence;
Evan Cheng3df447d2006-03-16 21:53:05 +0000140
Dan Gohman45774ce2010-02-12 10:34:29 +0000141public:
142 void CountRegister(const SCEV *Reg, size_t LUIdx);
Dan Gohman4cf99b52010-05-18 23:42:37 +0000143 void DropRegister(const SCEV *Reg, size_t LUIdx);
Dan Gohmana7b68d62010-10-07 23:33:43 +0000144 void SwapAndDropUse(size_t LUIdx, size_t LastLUIdx);
Dan Gohman51ad99d2010-01-21 02:09:26 +0000145
Dan Gohman45774ce2010-02-12 10:34:29 +0000146 bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
Dan Gohman51ad99d2010-01-21 02:09:26 +0000147
Dan Gohman45774ce2010-02-12 10:34:29 +0000148 const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
Dan Gohman51ad99d2010-01-21 02:09:26 +0000149
Dan Gohman45774ce2010-02-12 10:34:29 +0000150 void clear();
Dan Gohman51ad99d2010-01-21 02:09:26 +0000151
Dan Gohman45774ce2010-02-12 10:34:29 +0000152 typedef SmallVectorImpl<const SCEV *>::iterator iterator;
153 typedef SmallVectorImpl<const SCEV *>::const_iterator const_iterator;
154 iterator begin() { return RegSequence.begin(); }
155 iterator end() { return RegSequence.end(); }
156 const_iterator begin() const { return RegSequence.begin(); }
157 const_iterator end() const { return RegSequence.end(); }
158};
Dan Gohman51ad99d2010-01-21 02:09:26 +0000159
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000160}
Dan Gohman51ad99d2010-01-21 02:09:26 +0000161
Dan Gohman45774ce2010-02-12 10:34:29 +0000162void
163RegUseTracker::CountRegister(const SCEV *Reg, size_t LUIdx) {
164 std::pair<RegUsesTy::iterator, bool> Pair =
Dan Gohman248c41d2010-05-18 22:33:00 +0000165 RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
Dan Gohman45774ce2010-02-12 10:34:29 +0000166 RegSortData &RSD = Pair.first->second;
167 if (Pair.second)
168 RegSequence.push_back(Reg);
169 RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
170 RSD.UsedByIndices.set(LUIdx);
Dan Gohman51ad99d2010-01-21 02:09:26 +0000171}
172
Dan Gohman4cf99b52010-05-18 23:42:37 +0000173void
174RegUseTracker::DropRegister(const SCEV *Reg, size_t LUIdx) {
175 RegUsesTy::iterator It = RegUsesMap.find(Reg);
176 assert(It != RegUsesMap.end());
177 RegSortData &RSD = It->second;
178 assert(RSD.UsedByIndices.size() > LUIdx);
179 RSD.UsedByIndices.reset(LUIdx);
180}
181
Dan Gohman20fab452010-05-19 23:43:12 +0000182void
Dan Gohmana7b68d62010-10-07 23:33:43 +0000183RegUseTracker::SwapAndDropUse(size_t LUIdx, size_t LastLUIdx) {
184 assert(LUIdx <= LastLUIdx);
185
186 // Update RegUses. The data structure is not optimized for this purpose;
187 // we must iterate through it and update each of the bit vectors.
Craig Topper10949ae2015-05-23 08:45:10 +0000188 for (auto &Pair : RegUsesMap) {
189 SmallBitVector &UsedByIndices = Pair.second.UsedByIndices;
Dan Gohmana7b68d62010-10-07 23:33:43 +0000190 if (LUIdx < UsedByIndices.size())
191 UsedByIndices[LUIdx] =
192 LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : 0;
193 UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx));
194 }
Dan Gohman20fab452010-05-19 23:43:12 +0000195}
196
Dan Gohman45774ce2010-02-12 10:34:29 +0000197bool
198RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
Dan Gohman4f13bbf2010-08-29 15:18:49 +0000199 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
200 if (I == RegUsesMap.end())
201 return false;
202 const SmallBitVector &UsedByIndices = I->second.UsedByIndices;
Dan Gohman45774ce2010-02-12 10:34:29 +0000203 int i = UsedByIndices.find_first();
204 if (i == -1) return false;
205 if ((size_t)i != LUIdx) return true;
206 return UsedByIndices.find_next(i) != -1;
207}
Dan Gohman51ad99d2010-01-21 02:09:26 +0000208
Dan Gohman45774ce2010-02-12 10:34:29 +0000209const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
Dan Gohman248c41d2010-05-18 22:33:00 +0000210 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
211 assert(I != RegUsesMap.end() && "Unknown register!");
Dan Gohman45774ce2010-02-12 10:34:29 +0000212 return I->second.UsedByIndices;
213}
Dan Gohman51ad99d2010-01-21 02:09:26 +0000214
Dan Gohman45774ce2010-02-12 10:34:29 +0000215void RegUseTracker::clear() {
Dan Gohman248c41d2010-05-18 22:33:00 +0000216 RegUsesMap.clear();
Dan Gohman45774ce2010-02-12 10:34:29 +0000217 RegSequence.clear();
218}
Dan Gohman51ad99d2010-01-21 02:09:26 +0000219
Dan Gohman45774ce2010-02-12 10:34:29 +0000220namespace {
221
222/// Formula - This class holds information that describes a formula for
223/// computing satisfying a use. It may include broken-out immediates and scaled
224/// registers.
225struct Formula {
Chandler Carruth6e479322013-01-07 15:04:40 +0000226 /// Global base address used for complex addressing.
227 GlobalValue *BaseGV;
228
229 /// Base offset for complex addressing.
230 int64_t BaseOffset;
231
232 /// Whether any complex addressing has a base register.
233 bool HasBaseReg;
234
235 /// The scale of any complex addressing.
236 int64_t Scale;
Dan Gohman45774ce2010-02-12 10:34:29 +0000237
238 /// BaseRegs - The list of "base" registers for this use. When this is
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000239 /// non-empty. The canonical representation of a formula is
240 /// 1. BaseRegs.size > 1 implies ScaledReg != NULL and
241 /// 2. ScaledReg != NULL implies Scale != 1 || !BaseRegs.empty().
242 /// #1 enforces that the scaled register is always used when at least two
243 /// registers are needed by the formula: e.g., reg1 + reg2 is reg1 + 1 * reg2.
244 /// #2 enforces that 1 * reg is reg.
245 /// This invariant can be temporarly broken while building a formula.
246 /// However, every formula inserted into the LSRInstance must be in canonical
247 /// form.
Preston Gurd25c3b6a2013-02-01 20:41:27 +0000248 SmallVector<const SCEV *, 4> BaseRegs;
Dan Gohman45774ce2010-02-12 10:34:29 +0000249
250 /// ScaledReg - The 'scaled' register for this use. This should be non-null
Chandler Carruth6e479322013-01-07 15:04:40 +0000251 /// when Scale is not zero.
Dan Gohman45774ce2010-02-12 10:34:29 +0000252 const SCEV *ScaledReg;
253
Dan Gohman6136e942011-05-03 00:46:49 +0000254 /// UnfoldedOffset - An additional constant offset which added near the
255 /// use. This requires a temporary register, but the offset itself can
256 /// live in an add immediate field rather than a register.
257 int64_t UnfoldedOffset;
258
Chandler Carruth6e479322013-01-07 15:04:40 +0000259 Formula()
Craig Topperf40110f2014-04-25 05:29:35 +0000260 : BaseGV(nullptr), BaseOffset(0), HasBaseReg(false), Scale(0),
261 ScaledReg(nullptr), UnfoldedOffset(0) {}
Dan Gohman45774ce2010-02-12 10:34:29 +0000262
Dan Gohman20d9ce22010-11-17 21:41:58 +0000263 void InitialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE);
Dan Gohman45774ce2010-02-12 10:34:29 +0000264
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000265 bool isCanonical() const;
266
267 void Canonicalize();
268
269 bool Unscale();
270
Adam Nemetdeab6f92014-04-29 18:25:28 +0000271 size_t getNumRegs() const;
Chris Lattner229907c2011-07-18 04:54:35 +0000272 Type *getType() const;
Dan Gohman45774ce2010-02-12 10:34:29 +0000273
Dan Gohman80a96082010-05-20 15:17:54 +0000274 void DeleteBaseReg(const SCEV *&S);
275
Dan Gohman45774ce2010-02-12 10:34:29 +0000276 bool referencesReg(const SCEV *S) const;
277 bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
278 const RegUseTracker &RegUses) const;
279
280 void print(raw_ostream &OS) const;
281 void dump() const;
282};
283
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000284}
Dan Gohman45774ce2010-02-12 10:34:29 +0000285
Dan Gohman8b0a4192010-03-01 17:49:51 +0000286/// DoInitialMatch - Recursion helper for InitialMatch.
Dan Gohman45774ce2010-02-12 10:34:29 +0000287static void DoInitialMatch(const SCEV *S, Loop *L,
288 SmallVectorImpl<const SCEV *> &Good,
289 SmallVectorImpl<const SCEV *> &Bad,
Dan Gohman20d9ce22010-11-17 21:41:58 +0000290 ScalarEvolution &SE) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000291 // Collect expressions which properly dominate the loop header.
Dan Gohman20d9ce22010-11-17 21:41:58 +0000292 if (SE.properlyDominates(S, L->getHeader())) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000293 Good.push_back(S);
294 return;
Dan Gohman51ad99d2010-01-21 02:09:26 +0000295 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000296
297 // Look at add operands.
298 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Craig Topper77b99412015-05-23 08:01:41 +0000299 for (const SCEV *S : Add->operands())
300 DoInitialMatch(S, L, Good, Bad, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +0000301 return;
302 }
303
304 // Look at addrec operands.
305 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
306 if (!AR->getStart()->isZero()) {
Dan Gohman20d9ce22010-11-17 21:41:58 +0000307 DoInitialMatch(AR->getStart(), L, Good, Bad, SE);
Dan Gohman1d2ded72010-05-03 22:09:21 +0000308 DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
Dan Gohman45774ce2010-02-12 10:34:29 +0000309 AR->getStepRecurrence(SE),
Andrew Trick8b55b732011-03-14 16:50:06 +0000310 // FIXME: AR->getNoWrapFlags()
311 AR->getLoop(), SCEV::FlagAnyWrap),
Dan Gohman20d9ce22010-11-17 21:41:58 +0000312 L, Good, Bad, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +0000313 return;
314 }
315
316 // Handle a multiplication by -1 (negation) if it didn't fold.
317 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
318 if (Mul->getOperand(0)->isAllOnesValue()) {
319 SmallVector<const SCEV *, 4> Ops(Mul->op_begin()+1, Mul->op_end());
320 const SCEV *NewMul = SE.getMulExpr(Ops);
321
322 SmallVector<const SCEV *, 4> MyGood;
323 SmallVector<const SCEV *, 4> MyBad;
Dan Gohman20d9ce22010-11-17 21:41:58 +0000324 DoInitialMatch(NewMul, L, MyGood, MyBad, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +0000325 const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
326 SE.getEffectiveSCEVType(NewMul->getType())));
Craig Topper042a3922015-05-25 20:01:18 +0000327 for (const SCEV *S : MyGood)
328 Good.push_back(SE.getMulExpr(NegOne, S));
329 for (const SCEV *S : MyBad)
330 Bad.push_back(SE.getMulExpr(NegOne, S));
Dan Gohman45774ce2010-02-12 10:34:29 +0000331 return;
332 }
333
334 // Ok, we can't do anything interesting. Just stuff the whole thing into a
335 // register and hope for the best.
336 Bad.push_back(S);
337}
338
339/// InitialMatch - Incorporate loop-variant parts of S into this Formula,
340/// attempting to keep all loop-invariant and loop-computable values in a
341/// single base register.
Dan Gohman20d9ce22010-11-17 21:41:58 +0000342void Formula::InitialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000343 SmallVector<const SCEV *, 4> Good;
344 SmallVector<const SCEV *, 4> Bad;
Dan Gohman20d9ce22010-11-17 21:41:58 +0000345 DoInitialMatch(S, L, Good, Bad, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +0000346 if (!Good.empty()) {
Dan Gohman9b5d0bb72010-04-08 23:36:27 +0000347 const SCEV *Sum = SE.getAddExpr(Good);
348 if (!Sum->isZero())
349 BaseRegs.push_back(Sum);
Chandler Carruth6e479322013-01-07 15:04:40 +0000350 HasBaseReg = true;
Dan Gohman45774ce2010-02-12 10:34:29 +0000351 }
352 if (!Bad.empty()) {
Dan Gohman9b5d0bb72010-04-08 23:36:27 +0000353 const SCEV *Sum = SE.getAddExpr(Bad);
354 if (!Sum->isZero())
355 BaseRegs.push_back(Sum);
Chandler Carruth6e479322013-01-07 15:04:40 +0000356 HasBaseReg = true;
Dan Gohman45774ce2010-02-12 10:34:29 +0000357 }
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000358 Canonicalize();
359}
360
361/// \brief Check whether or not this formula statisfies the canonical
362/// representation.
363/// \see Formula::BaseRegs.
364bool Formula::isCanonical() const {
365 if (ScaledReg)
366 return Scale != 1 || !BaseRegs.empty();
367 return BaseRegs.size() <= 1;
368}
369
370/// \brief Helper method to morph a formula into its canonical representation.
371/// \see Formula::BaseRegs.
372/// Every formula having more than one base register, must use the ScaledReg
373/// field. Otherwise, we would have to do special cases everywhere in LSR
374/// to treat reg1 + reg2 + ... the same way as reg1 + 1*reg2 + ...
375/// On the other hand, 1*reg should be canonicalized into reg.
376void Formula::Canonicalize() {
377 if (isCanonical())
378 return;
379 // So far we did not need this case. This is easy to implement but it is
380 // useless to maintain dead code. Beside it could hurt compile time.
381 assert(!BaseRegs.empty() && "1*reg => reg, should not be needed.");
382 // Keep the invariant sum in BaseRegs and one of the variant sum in ScaledReg.
383 ScaledReg = BaseRegs.back();
384 BaseRegs.pop_back();
385 Scale = 1;
386 size_t BaseRegsSize = BaseRegs.size();
387 size_t Try = 0;
388 // If ScaledReg is an invariant, try to find a variant expression.
389 while (Try < BaseRegsSize && !isa<SCEVAddRecExpr>(ScaledReg))
390 std::swap(ScaledReg, BaseRegs[Try++]);
391}
392
393/// \brief Get rid of the scale in the formula.
394/// In other words, this method morphes reg1 + 1*reg2 into reg1 + reg2.
395/// \return true if it was possible to get rid of the scale, false otherwise.
396/// \note After this operation the formula may not be in the canonical form.
397bool Formula::Unscale() {
398 if (Scale != 1)
399 return false;
400 Scale = 0;
401 BaseRegs.push_back(ScaledReg);
402 ScaledReg = nullptr;
403 return true;
Dan Gohman45774ce2010-02-12 10:34:29 +0000404}
405
406/// getNumRegs - Return the total number of register operands used by this
407/// formula. This does not include register uses implied by non-constant
408/// addrec strides.
Adam Nemetdeab6f92014-04-29 18:25:28 +0000409size_t Formula::getNumRegs() const {
Dan Gohman45774ce2010-02-12 10:34:29 +0000410 return !!ScaledReg + BaseRegs.size();
411}
412
413/// getType - Return the type of this formula, if it has one, or null
414/// otherwise. This type is meaningless except for the bit size.
Chris Lattner229907c2011-07-18 04:54:35 +0000415Type *Formula::getType() const {
Dan Gohman45774ce2010-02-12 10:34:29 +0000416 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
417 ScaledReg ? ScaledReg->getType() :
Chandler Carruth6e479322013-01-07 15:04:40 +0000418 BaseGV ? BaseGV->getType() :
Craig Topperf40110f2014-04-25 05:29:35 +0000419 nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000420}
421
Dan Gohman80a96082010-05-20 15:17:54 +0000422/// DeleteBaseReg - Delete the given base reg from the BaseRegs list.
423void Formula::DeleteBaseReg(const SCEV *&S) {
424 if (&S != &BaseRegs.back())
425 std::swap(S, BaseRegs.back());
426 BaseRegs.pop_back();
427}
428
Dan Gohman45774ce2010-02-12 10:34:29 +0000429/// referencesReg - Test if this formula references the given register.
430bool Formula::referencesReg(const SCEV *S) const {
431 return S == ScaledReg ||
432 std::find(BaseRegs.begin(), BaseRegs.end(), S) != BaseRegs.end();
433}
434
435/// hasRegsUsedByUsesOtherThan - Test whether this formula uses registers
436/// which are used by uses other than the use with the given index.
437bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
438 const RegUseTracker &RegUses) const {
439 if (ScaledReg)
440 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
441 return true;
Craig Topper042a3922015-05-25 20:01:18 +0000442 for (const SCEV *BaseReg : BaseRegs)
443 if (RegUses.isRegUsedByUsesOtherThan(BaseReg, LUIdx))
Dan Gohman45774ce2010-02-12 10:34:29 +0000444 return true;
445 return false;
446}
447
448void Formula::print(raw_ostream &OS) const {
449 bool First = true;
Chandler Carruth6e479322013-01-07 15:04:40 +0000450 if (BaseGV) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000451 if (!First) OS << " + "; else First = false;
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000452 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +0000453 }
Chandler Carruth6e479322013-01-07 15:04:40 +0000454 if (BaseOffset != 0) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000455 if (!First) OS << " + "; else First = false;
Chandler Carruth6e479322013-01-07 15:04:40 +0000456 OS << BaseOffset;
Dan Gohman45774ce2010-02-12 10:34:29 +0000457 }
Craig Topper042a3922015-05-25 20:01:18 +0000458 for (const SCEV *BaseReg : BaseRegs) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000459 if (!First) OS << " + "; else First = false;
Craig Topper042a3922015-05-25 20:01:18 +0000460 OS << "reg(" << *BaseReg << ')';
Dan Gohman45774ce2010-02-12 10:34:29 +0000461 }
Chandler Carruth6e479322013-01-07 15:04:40 +0000462 if (HasBaseReg && BaseRegs.empty()) {
Dan Gohman06ab08f2010-05-18 22:35:55 +0000463 if (!First) OS << " + "; else First = false;
464 OS << "**error: HasBaseReg**";
Chandler Carruth6e479322013-01-07 15:04:40 +0000465 } else if (!HasBaseReg && !BaseRegs.empty()) {
Dan Gohman06ab08f2010-05-18 22:35:55 +0000466 if (!First) OS << " + "; else First = false;
467 OS << "**error: !HasBaseReg**";
468 }
Chandler Carruth6e479322013-01-07 15:04:40 +0000469 if (Scale != 0) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000470 if (!First) OS << " + "; else First = false;
Chandler Carruth6e479322013-01-07 15:04:40 +0000471 OS << Scale << "*reg(";
Dan Gohman45774ce2010-02-12 10:34:29 +0000472 if (ScaledReg)
473 OS << *ScaledReg;
474 else
475 OS << "<unknown>";
476 OS << ')';
477 }
Dan Gohman6136e942011-05-03 00:46:49 +0000478 if (UnfoldedOffset != 0) {
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +0000479 if (!First) OS << " + ";
Dan Gohman6136e942011-05-03 00:46:49 +0000480 OS << "imm(" << UnfoldedOffset << ')';
481 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000482}
483
Manman Ren49d684e2012-09-12 05:06:18 +0000484#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman45774ce2010-02-12 10:34:29 +0000485void Formula::dump() const {
486 print(errs()); errs() << '\n';
487}
Manman Renc3366cc2012-09-06 19:55:56 +0000488#endif
Dan Gohman45774ce2010-02-12 10:34:29 +0000489
Dan Gohman85af2562010-02-19 19:32:49 +0000490/// isAddRecSExtable - Return true if the given addrec can be sign-extended
491/// without changing its value.
492static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
Chris Lattner229907c2011-07-18 04:54:35 +0000493 Type *WideTy =
Dan Gohmanab5fb7f2010-05-20 19:44:23 +0000494 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1);
Dan Gohman85af2562010-02-19 19:32:49 +0000495 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
496}
497
498/// isAddSExtable - Return true if the given add can be sign-extended
499/// without changing its value.
500static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
Chris Lattner229907c2011-07-18 04:54:35 +0000501 Type *WideTy =
Dan Gohmanab5fb7f2010-05-20 19:44:23 +0000502 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1);
Dan Gohman85af2562010-02-19 19:32:49 +0000503 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
504}
505
Dan Gohmanab542222010-06-24 16:45:11 +0000506/// isMulSExtable - Return true if the given mul can be sign-extended
Dan Gohman85af2562010-02-19 19:32:49 +0000507/// without changing its value.
Dan Gohmanab542222010-06-24 16:45:11 +0000508static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {
Chris Lattner229907c2011-07-18 04:54:35 +0000509 Type *WideTy =
Dan Gohmanab542222010-06-24 16:45:11 +0000510 IntegerType::get(SE.getContext(),
511 SE.getTypeSizeInBits(M->getType()) * M->getNumOperands());
512 return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy));
Dan Gohman85af2562010-02-19 19:32:49 +0000513}
514
Dan Gohman4eebb942010-02-19 19:35:48 +0000515/// getExactSDiv - Return an expression for LHS /s RHS, if it can be determined
516/// and if the remainder is known to be zero, or null otherwise. If
517/// IgnoreSignificantBits is true, expressions like (X * Y) /s Y are simplified
518/// to Y, ignoring that the multiplication may overflow, which is useful when
519/// the result will be used in a context where the most significant bits are
520/// ignored.
521static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
522 ScalarEvolution &SE,
523 bool IgnoreSignificantBits = false) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000524 // Handle the trivial case, which works for any SCEV type.
525 if (LHS == RHS)
Dan Gohman1d2ded72010-05-03 22:09:21 +0000526 return SE.getConstant(LHS->getType(), 1);
Dan Gohman45774ce2010-02-12 10:34:29 +0000527
Dan Gohman47ddf762010-06-24 16:51:25 +0000528 // Handle a few RHS special cases.
529 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
530 if (RC) {
531 const APInt &RA = RC->getValue()->getValue();
532 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do
533 // some folding.
534 if (RA.isAllOnesValue())
535 return SE.getMulExpr(LHS, RC);
536 // Handle x /s 1 as x.
537 if (RA == 1)
538 return LHS;
539 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000540
541 // Check for a division of a constant by a constant.
542 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000543 if (!RC)
Craig Topperf40110f2014-04-25 05:29:35 +0000544 return nullptr;
Dan Gohman47ddf762010-06-24 16:51:25 +0000545 const APInt &LA = C->getValue()->getValue();
546 const APInt &RA = RC->getValue()->getValue();
547 if (LA.srem(RA) != 0)
Craig Topperf40110f2014-04-25 05:29:35 +0000548 return nullptr;
Dan Gohman47ddf762010-06-24 16:51:25 +0000549 return SE.getConstant(LA.sdiv(RA));
Dan Gohman45774ce2010-02-12 10:34:29 +0000550 }
551
Dan Gohman85af2562010-02-19 19:32:49 +0000552 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
Dan Gohman45774ce2010-02-12 10:34:29 +0000553 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman85af2562010-02-19 19:32:49 +0000554 if (IgnoreSignificantBits || isAddRecSExtable(AR, SE)) {
Dan Gohman4eebb942010-02-19 19:35:48 +0000555 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
556 IgnoreSignificantBits);
Craig Topperf40110f2014-04-25 05:29:35 +0000557 if (!Step) return nullptr;
Dan Gohman129a8162010-08-19 01:02:31 +0000558 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
559 IgnoreSignificantBits);
Craig Topperf40110f2014-04-25 05:29:35 +0000560 if (!Start) return nullptr;
Andrew Trick8b55b732011-03-14 16:50:06 +0000561 // FlagNW is independent of the start value, step direction, and is
562 // preserved with smaller magnitude steps.
563 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
564 return SE.getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagAnyWrap);
Dan Gohman85af2562010-02-19 19:32:49 +0000565 }
Craig Topperf40110f2014-04-25 05:29:35 +0000566 return nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000567 }
568
Dan Gohman85af2562010-02-19 19:32:49 +0000569 // Distribute the sdiv over add operands, if the add doesn't overflow.
Dan Gohman45774ce2010-02-12 10:34:29 +0000570 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohman85af2562010-02-19 19:32:49 +0000571 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
572 SmallVector<const SCEV *, 8> Ops;
Craig Topper042a3922015-05-25 20:01:18 +0000573 for (const SCEV *S : Add->operands()) {
574 const SCEV *Op = getExactSDiv(S, RHS, SE, IgnoreSignificantBits);
Craig Topperf40110f2014-04-25 05:29:35 +0000575 if (!Op) return nullptr;
Dan Gohman85af2562010-02-19 19:32:49 +0000576 Ops.push_back(Op);
577 }
578 return SE.getAddExpr(Ops);
Dan Gohman45774ce2010-02-12 10:34:29 +0000579 }
Craig Topperf40110f2014-04-25 05:29:35 +0000580 return nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000581 }
582
583 // Check for a multiply operand that we can pull RHS out of.
Dan Gohman963b1c12010-06-24 16:57:52 +0000584 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman85af2562010-02-19 19:32:49 +0000585 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000586 SmallVector<const SCEV *, 4> Ops;
587 bool Found = false;
Craig Topper042a3922015-05-25 20:01:18 +0000588 for (const SCEV *S : Mul->operands()) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000589 if (!Found)
Dan Gohman6b733fc2010-05-20 16:23:28 +0000590 if (const SCEV *Q = getExactSDiv(S, RHS, SE,
Dan Gohman4eebb942010-02-19 19:35:48 +0000591 IgnoreSignificantBits)) {
Dan Gohman6b733fc2010-05-20 16:23:28 +0000592 S = Q;
Dan Gohman45774ce2010-02-12 10:34:29 +0000593 Found = true;
Dan Gohman45774ce2010-02-12 10:34:29 +0000594 }
Dan Gohman6b733fc2010-05-20 16:23:28 +0000595 Ops.push_back(S);
Dan Gohman45774ce2010-02-12 10:34:29 +0000596 }
Craig Topperf40110f2014-04-25 05:29:35 +0000597 return Found ? SE.getMulExpr(Ops) : nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000598 }
Craig Topperf40110f2014-04-25 05:29:35 +0000599 return nullptr;
Dan Gohman963b1c12010-06-24 16:57:52 +0000600 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000601
602 // Otherwise we don't know.
Craig Topperf40110f2014-04-25 05:29:35 +0000603 return nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000604}
605
606/// ExtractImmediate - If S involves the addition of a constant integer value,
607/// return that integer value, and mutate S to point to a new SCEV with that
608/// value excluded.
609static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
610 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
611 if (C->getValue()->getValue().getMinSignedBits() <= 64) {
Dan Gohman1d2ded72010-05-03 22:09:21 +0000612 S = SE.getConstant(C->getType(), 0);
Dan Gohman45774ce2010-02-12 10:34:29 +0000613 return C->getValue()->getSExtValue();
614 }
615 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
616 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
617 int64_t Result = ExtractImmediate(NewOps.front(), SE);
Dan Gohman081ffcd2010-08-13 21:17:19 +0000618 if (Result != 0)
619 S = SE.getAddExpr(NewOps);
Dan Gohman45774ce2010-02-12 10:34:29 +0000620 return Result;
621 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
622 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
623 int64_t Result = ExtractImmediate(NewOps.front(), SE);
Dan Gohman081ffcd2010-08-13 21:17:19 +0000624 if (Result != 0)
Andrew Trick8b55b732011-03-14 16:50:06 +0000625 S = SE.getAddRecExpr(NewOps, AR->getLoop(),
626 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
627 SCEV::FlagAnyWrap);
Dan Gohman45774ce2010-02-12 10:34:29 +0000628 return Result;
629 }
630 return 0;
631}
632
633/// ExtractSymbol - If S involves the addition of a GlobalValue address,
634/// return that symbol, and mutate S to point to a new SCEV with that
635/// value excluded.
636static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
637 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
638 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
Dan Gohman1d2ded72010-05-03 22:09:21 +0000639 S = SE.getConstant(GV->getType(), 0);
Dan Gohman45774ce2010-02-12 10:34:29 +0000640 return GV;
641 }
642 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
643 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
644 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
Dan Gohman081ffcd2010-08-13 21:17:19 +0000645 if (Result)
646 S = SE.getAddExpr(NewOps);
Dan Gohman45774ce2010-02-12 10:34:29 +0000647 return Result;
648 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
649 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
650 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
Dan Gohman081ffcd2010-08-13 21:17:19 +0000651 if (Result)
Andrew Trick8b55b732011-03-14 16:50:06 +0000652 S = SE.getAddRecExpr(NewOps, AR->getLoop(),
653 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
654 SCEV::FlagAnyWrap);
Dan Gohman45774ce2010-02-12 10:34:29 +0000655 return Result;
656 }
Craig Topperf40110f2014-04-25 05:29:35 +0000657 return nullptr;
Nate Begemanb18121e2004-10-18 21:08:22 +0000658}
659
Dan Gohmand0b1fbd2009-02-18 00:08:39 +0000660/// isAddressUse - Returns true if the specified instruction is using the
Dale Johannesen9efd2ce2008-12-05 21:47:27 +0000661/// specified value as an address.
662static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
663 bool isAddress = isa<LoadInst>(Inst);
664 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
665 if (SI->getOperand(1) == OperandVal)
666 isAddress = true;
667 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
668 // Addressing modes can also be folded into prefetches and a variety
669 // of intrinsics.
670 switch (II->getIntrinsicID()) {
671 default: break;
672 case Intrinsic::prefetch:
Dale Johannesen9efd2ce2008-12-05 21:47:27 +0000673 case Intrinsic::x86_sse_storeu_ps:
674 case Intrinsic::x86_sse2_storeu_pd:
675 case Intrinsic::x86_sse2_storeu_dq:
676 case Intrinsic::x86_sse2_storel_dq:
Gabor Greif8ae30952010-06-30 09:15:28 +0000677 if (II->getArgOperand(0) == OperandVal)
Dale Johannesen9efd2ce2008-12-05 21:47:27 +0000678 isAddress = true;
679 break;
680 }
681 }
682 return isAddress;
683}
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000684
Dan Gohman917ffe42009-03-09 21:01:17 +0000685/// getAccessType - Return the type of the memory being accessed.
Chris Lattner229907c2011-07-18 04:54:35 +0000686static Type *getAccessType(const Instruction *Inst) {
687 Type *AccessTy = Inst->getType();
Dan Gohman917ffe42009-03-09 21:01:17 +0000688 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
Dan Gohman14d13392009-05-18 16:45:28 +0000689 AccessTy = SI->getOperand(0)->getType();
Dan Gohman917ffe42009-03-09 21:01:17 +0000690 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
691 // Addressing modes can also be folded into prefetches and a variety
692 // of intrinsics.
693 switch (II->getIntrinsicID()) {
694 default: break;
695 case Intrinsic::x86_sse_storeu_ps:
696 case Intrinsic::x86_sse2_storeu_pd:
697 case Intrinsic::x86_sse2_storeu_dq:
698 case Intrinsic::x86_sse2_storel_dq:
Gabor Greif8ae30952010-06-30 09:15:28 +0000699 AccessTy = II->getArgOperand(0)->getType();
Dan Gohman917ffe42009-03-09 21:01:17 +0000700 break;
701 }
702 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000703
704 // All pointers have the same requirements, so canonicalize them to an
705 // arbitrary pointer type to minimize variation.
Chris Lattner229907c2011-07-18 04:54:35 +0000706 if (PointerType *PTy = dyn_cast<PointerType>(AccessTy))
Dan Gohman45774ce2010-02-12 10:34:29 +0000707 AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
708 PTy->getAddressSpace());
709
Dan Gohman14d13392009-05-18 16:45:28 +0000710 return AccessTy;
Dan Gohman917ffe42009-03-09 21:01:17 +0000711}
712
Andrew Trick5df90962011-12-06 03:13:31 +0000713/// isExistingPhi - Return true if this AddRec is already a phi in its loop.
714static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
715 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
716 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
717 if (SE.isSCEVable(PN->getType()) &&
718 (SE.getEffectiveSCEVType(PN->getType()) ==
719 SE.getEffectiveSCEVType(AR->getType())) &&
720 SE.getSCEV(PN) == AR)
721 return true;
722 }
723 return false;
724}
725
Andrew Trickd5d2db92012-01-10 01:45:08 +0000726/// Check if expanding this expression is likely to incur significant cost. This
727/// is tricky because SCEV doesn't track which expressions are actually computed
728/// by the current IR.
729///
730/// We currently allow expansion of IV increments that involve adds,
731/// multiplication by constants, and AddRecs from existing phis.
732///
733/// TODO: Allow UDivExpr if we can find an existing IV increment that is an
734/// obvious multiple of the UDivExpr.
735static bool isHighCostExpansion(const SCEV *S,
Craig Topper71b7b682014-08-21 05:55:13 +0000736 SmallPtrSetImpl<const SCEV*> &Processed,
Andrew Trickd5d2db92012-01-10 01:45:08 +0000737 ScalarEvolution &SE) {
738 // Zero/One operand expressions
739 switch (S->getSCEVType()) {
740 case scUnknown:
741 case scConstant:
742 return false;
743 case scTruncate:
744 return isHighCostExpansion(cast<SCEVTruncateExpr>(S)->getOperand(),
745 Processed, SE);
746 case scZeroExtend:
747 return isHighCostExpansion(cast<SCEVZeroExtendExpr>(S)->getOperand(),
748 Processed, SE);
749 case scSignExtend:
750 return isHighCostExpansion(cast<SCEVSignExtendExpr>(S)->getOperand(),
751 Processed, SE);
752 }
753
David Blaikie70573dc2014-11-19 07:49:26 +0000754 if (!Processed.insert(S).second)
Andrew Trickd5d2db92012-01-10 01:45:08 +0000755 return false;
756
757 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Craig Topper042a3922015-05-25 20:01:18 +0000758 for (const SCEV *S : Add->operands()) {
759 if (isHighCostExpansion(S, Processed, SE))
Andrew Trickd5d2db92012-01-10 01:45:08 +0000760 return true;
761 }
762 return false;
763 }
764
765 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
766 if (Mul->getNumOperands() == 2) {
767 // Multiplication by a constant is ok
768 if (isa<SCEVConstant>(Mul->getOperand(0)))
769 return isHighCostExpansion(Mul->getOperand(1), Processed, SE);
770
771 // If we have the value of one operand, check if an existing
772 // multiplication already generates this expression.
773 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) {
774 Value *UVal = U->getValue();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000775 for (User *UR : UVal->users()) {
Andrew Trick14779cc2012-03-26 20:28:37 +0000776 // If U is a constant, it may be used by a ConstantExpr.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000777 Instruction *UI = dyn_cast<Instruction>(UR);
778 if (UI && UI->getOpcode() == Instruction::Mul &&
779 SE.isSCEVable(UI->getType())) {
780 return SE.getSCEV(UI) == Mul;
Andrew Trickd5d2db92012-01-10 01:45:08 +0000781 }
782 }
783 }
784 }
785 }
786
787 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
788 if (isExistingPhi(AR, SE))
789 return false;
790 }
791
792 // Fow now, consider any other type of expression (div/mul/min/max) high cost.
793 return true;
794}
795
Dan Gohman45774ce2010-02-12 10:34:29 +0000796/// DeleteTriviallyDeadInstructions - If any of the instructions is the
797/// specified set are trivially dead, delete them and see if this makes any of
798/// their operands subsequently dead.
799static bool
800DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
801 bool Changed = false;
802
803 while (!DeadInsts.empty()) {
Richard Smithad9c8e82012-08-21 20:35:14 +0000804 Value *V = DeadInsts.pop_back_val();
805 Instruction *I = dyn_cast_or_null<Instruction>(V);
Dan Gohman45774ce2010-02-12 10:34:29 +0000806
Craig Topperf40110f2014-04-25 05:29:35 +0000807 if (!I || !isInstructionTriviallyDead(I))
Dan Gohman45774ce2010-02-12 10:34:29 +0000808 continue;
809
Craig Topper042a3922015-05-25 20:01:18 +0000810 for (Use &O : I->operands())
811 if (Instruction *U = dyn_cast<Instruction>(O)) {
812 O = nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000813 if (U->use_empty())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000814 DeadInsts.emplace_back(U);
Dan Gohman45774ce2010-02-12 10:34:29 +0000815 }
816
817 I->eraseFromParent();
818 Changed = true;
819 }
820
821 return Changed;
822}
823
Dan Gohman045f8192010-01-22 00:46:49 +0000824namespace {
Quentin Colombet8aa7abe2013-05-31 17:20:29 +0000825class LSRUse;
826}
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000827
828/// \brief Check if the addressing mode defined by \p F is completely
829/// folded in \p LU at isel time.
830/// This includes address-mode folding and special icmp tricks.
831/// This function returns true if \p LU can accommodate what \p F
832/// defines and up to 1 base + 1 scaled + offset.
833/// In other words, if \p F has several base registers, this function may
834/// still return true. Therefore, users still need to account for
835/// additional base registers and/or unfolded offsets to derive an
836/// accurate cost model.
837static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
838 const LSRUse &LU, const Formula &F);
Quentin Colombetbf490d42013-05-31 21:29:03 +0000839// Get the cost of the scaling factor used in F for LU.
840static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
841 const LSRUse &LU, const Formula &F);
Quentin Colombet8aa7abe2013-05-31 17:20:29 +0000842
843namespace {
Jim Grosbach60f48542009-11-17 17:53:56 +0000844
Dan Gohman45774ce2010-02-12 10:34:29 +0000845/// Cost - This class is used to measure and compare candidate formulae.
846class Cost {
847 /// TODO: Some of these could be merged. Also, a lexical ordering
848 /// isn't always optimal.
849 unsigned NumRegs;
850 unsigned AddRecCost;
851 unsigned NumIVMuls;
852 unsigned NumBaseAdds;
853 unsigned ImmCost;
854 unsigned SetupCost;
Quentin Colombetbf490d42013-05-31 21:29:03 +0000855 unsigned ScaleCost;
Nate Begemane68bcd12005-07-30 00:15:07 +0000856
Dan Gohman45774ce2010-02-12 10:34:29 +0000857public:
858 Cost()
859 : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
Quentin Colombetbf490d42013-05-31 21:29:03 +0000860 SetupCost(0), ScaleCost(0) {}
Jim Grosbach60f48542009-11-17 17:53:56 +0000861
Dan Gohman45774ce2010-02-12 10:34:29 +0000862 bool operator<(const Cost &Other) const;
Dan Gohman045f8192010-01-22 00:46:49 +0000863
Tim Northoverbc6659c2014-01-22 13:27:00 +0000864 void Lose();
Dan Gohman045f8192010-01-22 00:46:49 +0000865
Andrew Trick784729d2011-09-26 23:11:04 +0000866#ifndef NDEBUG
867 // Once any of the metrics loses, they must all remain losers.
868 bool isValid() {
869 return ((NumRegs | AddRecCost | NumIVMuls | NumBaseAdds
Quentin Colombetbf490d42013-05-31 21:29:03 +0000870 | ImmCost | SetupCost | ScaleCost) != ~0u)
Andrew Trick784729d2011-09-26 23:11:04 +0000871 || ((NumRegs & AddRecCost & NumIVMuls & NumBaseAdds
Quentin Colombetbf490d42013-05-31 21:29:03 +0000872 & ImmCost & SetupCost & ScaleCost) == ~0u);
Andrew Trick784729d2011-09-26 23:11:04 +0000873 }
874#endif
875
876 bool isLoser() {
877 assert(isValid() && "invalid cost");
878 return NumRegs == ~0u;
879 }
880
Quentin Colombet8aa7abe2013-05-31 17:20:29 +0000881 void RateFormula(const TargetTransformInfo &TTI,
882 const Formula &F,
Craig Topper71b7b682014-08-21 05:55:13 +0000883 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman45774ce2010-02-12 10:34:29 +0000884 const DenseSet<const SCEV *> &VisitedRegs,
885 const Loop *L,
886 const SmallVectorImpl<int64_t> &Offsets,
Andrew Trick5df90962011-12-06 03:13:31 +0000887 ScalarEvolution &SE, DominatorTree &DT,
Quentin Colombet8aa7abe2013-05-31 17:20:29 +0000888 const LSRUse &LU,
Craig Topper71b7b682014-08-21 05:55:13 +0000889 SmallPtrSetImpl<const SCEV *> *LoserRegs = nullptr);
Dan Gohman045f8192010-01-22 00:46:49 +0000890
Dan Gohman45774ce2010-02-12 10:34:29 +0000891 void print(raw_ostream &OS) const;
892 void dump() const;
Dan Gohman045f8192010-01-22 00:46:49 +0000893
Dan Gohman45774ce2010-02-12 10:34:29 +0000894private:
895 void RateRegister(const SCEV *Reg,
Craig Topper71b7b682014-08-21 05:55:13 +0000896 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman45774ce2010-02-12 10:34:29 +0000897 const Loop *L,
898 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman5b18f032010-02-13 02:06:02 +0000899 void RatePrimaryRegister(const SCEV *Reg,
Craig Topper71b7b682014-08-21 05:55:13 +0000900 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman5b18f032010-02-13 02:06:02 +0000901 const Loop *L,
Andrew Trick5df90962011-12-06 03:13:31 +0000902 ScalarEvolution &SE, DominatorTree &DT,
Craig Topper71b7b682014-08-21 05:55:13 +0000903 SmallPtrSetImpl<const SCEV *> *LoserRegs);
Dan Gohman45774ce2010-02-12 10:34:29 +0000904};
905
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000906}
Dan Gohman45774ce2010-02-12 10:34:29 +0000907
908/// RateRegister - Tally up interesting quantities from the given register.
909void Cost::RateRegister(const SCEV *Reg,
Craig Topper71b7b682014-08-21 05:55:13 +0000910 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman45774ce2010-02-12 10:34:29 +0000911 const Loop *L,
912 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman5b18f032010-02-13 02:06:02 +0000913 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
Andrew Trickbc6de902011-09-29 01:33:38 +0000914 // If this is an addrec for another loop, don't second-guess its addrec phi
915 // nodes. LSR isn't currently smart enough to reason about more than one
Andrew Trickd97b83e2012-03-22 22:42:45 +0000916 // loop at a time. LSR has already run on inner loops, will not run on outer
917 // loops, and cannot be expected to change sibling loops.
918 if (AR->getLoop() != L) {
919 // If the AddRec exists, consider it's register free and leave it alone.
Andrew Trick5df90962011-12-06 03:13:31 +0000920 if (isExistingPhi(AR, SE))
921 return;
922
Andrew Trickd97b83e2012-03-22 22:42:45 +0000923 // Otherwise, do not consider this formula at all.
Tim Northoverbc6659c2014-01-22 13:27:00 +0000924 Lose();
Andrew Trickd97b83e2012-03-22 22:42:45 +0000925 return;
Dan Gohman45774ce2010-02-12 10:34:29 +0000926 }
Andrew Trickd97b83e2012-03-22 22:42:45 +0000927 AddRecCost += 1; /// TODO: This should be a function of the stride.
Dan Gohman45774ce2010-02-12 10:34:29 +0000928
Dan Gohman5b18f032010-02-13 02:06:02 +0000929 // Add the step value register, if it needs one.
930 // TODO: The non-affine case isn't precisely modeled here.
Andrew Trick8868fae2011-09-26 23:35:25 +0000931 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) {
932 if (!Regs.count(AR->getOperand(1))) {
Dan Gohman5b18f032010-02-13 02:06:02 +0000933 RateRegister(AR->getOperand(1), Regs, L, SE, DT);
Andrew Trick8868fae2011-09-26 23:35:25 +0000934 if (isLoser())
935 return;
936 }
937 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000938 }
Dan Gohman5b18f032010-02-13 02:06:02 +0000939 ++NumRegs;
940
941 // Rough heuristic; favor registers which don't require extra setup
942 // instructions in the preheader.
943 if (!isa<SCEVUnknown>(Reg) &&
944 !isa<SCEVConstant>(Reg) &&
945 !(isa<SCEVAddRecExpr>(Reg) &&
946 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
947 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
948 ++SetupCost;
Dan Gohman34f37e02010-10-07 23:41:58 +0000949
950 NumIVMuls += isa<SCEVMulExpr>(Reg) &&
Dan Gohmanafd6db92010-11-17 21:23:15 +0000951 SE.hasComputableLoopEvolution(Reg, L);
Dan Gohman5b18f032010-02-13 02:06:02 +0000952}
953
954/// RatePrimaryRegister - Record this register in the set. If we haven't seen it
Andrew Trick5df90962011-12-06 03:13:31 +0000955/// before, rate it. Optional LoserRegs provides a way to declare any formula
956/// that refers to one of those regs an instant loser.
Dan Gohman5b18f032010-02-13 02:06:02 +0000957void Cost::RatePrimaryRegister(const SCEV *Reg,
Craig Topper71b7b682014-08-21 05:55:13 +0000958 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman0849ed52010-02-16 19:42:34 +0000959 const Loop *L,
Andrew Trick5df90962011-12-06 03:13:31 +0000960 ScalarEvolution &SE, DominatorTree &DT,
Craig Topper71b7b682014-08-21 05:55:13 +0000961 SmallPtrSetImpl<const SCEV *> *LoserRegs) {
Andrew Trick5df90962011-12-06 03:13:31 +0000962 if (LoserRegs && LoserRegs->count(Reg)) {
Tim Northoverbc6659c2014-01-22 13:27:00 +0000963 Lose();
Andrew Trick5df90962011-12-06 03:13:31 +0000964 return;
965 }
David Blaikie70573dc2014-11-19 07:49:26 +0000966 if (Regs.insert(Reg).second) {
Dan Gohman5b18f032010-02-13 02:06:02 +0000967 RateRegister(Reg, Regs, L, SE, DT);
Andrew Tricka1c01ba2013-03-19 04:14:57 +0000968 if (LoserRegs && isLoser())
Andrew Trick5df90962011-12-06 03:13:31 +0000969 LoserRegs->insert(Reg);
970 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000971}
972
Quentin Colombet8aa7abe2013-05-31 17:20:29 +0000973void Cost::RateFormula(const TargetTransformInfo &TTI,
974 const Formula &F,
Craig Topper71b7b682014-08-21 05:55:13 +0000975 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman45774ce2010-02-12 10:34:29 +0000976 const DenseSet<const SCEV *> &VisitedRegs,
977 const Loop *L,
978 const SmallVectorImpl<int64_t> &Offsets,
Andrew Trick5df90962011-12-06 03:13:31 +0000979 ScalarEvolution &SE, DominatorTree &DT,
Quentin Colombet8aa7abe2013-05-31 17:20:29 +0000980 const LSRUse &LU,
Craig Topper71b7b682014-08-21 05:55:13 +0000981 SmallPtrSetImpl<const SCEV *> *LoserRegs) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000982 assert(F.isCanonical() && "Cost is accurate only for canonical formula");
Dan Gohman45774ce2010-02-12 10:34:29 +0000983 // Tally up the registers.
984 if (const SCEV *ScaledReg = F.ScaledReg) {
985 if (VisitedRegs.count(ScaledReg)) {
Tim Northoverbc6659c2014-01-22 13:27:00 +0000986 Lose();
Dan Gohman45774ce2010-02-12 10:34:29 +0000987 return;
988 }
Andrew Trick5df90962011-12-06 03:13:31 +0000989 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT, LoserRegs);
Andrew Trick784729d2011-09-26 23:11:04 +0000990 if (isLoser())
991 return;
Dan Gohman45774ce2010-02-12 10:34:29 +0000992 }
Craig Topper042a3922015-05-25 20:01:18 +0000993 for (const SCEV *BaseReg : F.BaseRegs) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000994 if (VisitedRegs.count(BaseReg)) {
Tim Northoverbc6659c2014-01-22 13:27:00 +0000995 Lose();
Dan Gohman45774ce2010-02-12 10:34:29 +0000996 return;
997 }
Andrew Trick5df90962011-12-06 03:13:31 +0000998 RatePrimaryRegister(BaseReg, Regs, L, SE, DT, LoserRegs);
Andrew Trick784729d2011-09-26 23:11:04 +0000999 if (isLoser())
1000 return;
Dan Gohman45774ce2010-02-12 10:34:29 +00001001 }
1002
Dan Gohman6136e942011-05-03 00:46:49 +00001003 // Determine how many (unfolded) adds we'll need inside the loop.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001004 size_t NumBaseParts = F.getNumRegs();
Dan Gohman6136e942011-05-03 00:46:49 +00001005 if (NumBaseParts > 1)
Quentin Colombet8aa7abe2013-05-31 17:20:29 +00001006 // Do not count the base and a possible second register if the target
1007 // allows to fold 2 registers.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001008 NumBaseAdds +=
1009 NumBaseParts - (1 + (F.Scale && isAMCompletelyFolded(TTI, LU, F)));
1010 NumBaseAdds += (F.UnfoldedOffset != 0);
Dan Gohman45774ce2010-02-12 10:34:29 +00001011
Quentin Colombetbf490d42013-05-31 21:29:03 +00001012 // Accumulate non-free scaling amounts.
1013 ScaleCost += getScalingFactorCost(TTI, LU, F);
1014
Dan Gohman45774ce2010-02-12 10:34:29 +00001015 // Tally up the non-zero immediates.
Craig Topper042a3922015-05-25 20:01:18 +00001016 for (int64_t O : Offsets) {
1017 int64_t Offset = (uint64_t)O + F.BaseOffset;
Chandler Carruth6e479322013-01-07 15:04:40 +00001018 if (F.BaseGV)
Dan Gohman45774ce2010-02-12 10:34:29 +00001019 ImmCost += 64; // Handle symbolic values conservatively.
1020 // TODO: This should probably be the pointer size.
1021 else if (Offset != 0)
1022 ImmCost += APInt(64, Offset, true).getMinSignedBits();
1023 }
Andrew Trick784729d2011-09-26 23:11:04 +00001024 assert(isValid() && "invalid cost");
Dan Gohman45774ce2010-02-12 10:34:29 +00001025}
1026
Tim Northoverbc6659c2014-01-22 13:27:00 +00001027/// Lose - Set this cost to a losing value.
1028void Cost::Lose() {
Dan Gohman45774ce2010-02-12 10:34:29 +00001029 NumRegs = ~0u;
1030 AddRecCost = ~0u;
1031 NumIVMuls = ~0u;
1032 NumBaseAdds = ~0u;
1033 ImmCost = ~0u;
1034 SetupCost = ~0u;
Quentin Colombetbf490d42013-05-31 21:29:03 +00001035 ScaleCost = ~0u;
Dan Gohman45774ce2010-02-12 10:34:29 +00001036}
1037
1038/// operator< - Choose the lower cost.
1039bool Cost::operator<(const Cost &Other) const {
Benjamin Kramerb2f034b2014-03-03 19:58:30 +00001040 return std::tie(NumRegs, AddRecCost, NumIVMuls, NumBaseAdds, ScaleCost,
1041 ImmCost, SetupCost) <
1042 std::tie(Other.NumRegs, Other.AddRecCost, Other.NumIVMuls,
1043 Other.NumBaseAdds, Other.ScaleCost, Other.ImmCost,
1044 Other.SetupCost);
Dan Gohman45774ce2010-02-12 10:34:29 +00001045}
1046
1047void Cost::print(raw_ostream &OS) const {
1048 OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
1049 if (AddRecCost != 0)
1050 OS << ", with addrec cost " << AddRecCost;
1051 if (NumIVMuls != 0)
1052 OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
1053 if (NumBaseAdds != 0)
1054 OS << ", plus " << NumBaseAdds << " base add"
1055 << (NumBaseAdds == 1 ? "" : "s");
Quentin Colombetbf490d42013-05-31 21:29:03 +00001056 if (ScaleCost != 0)
1057 OS << ", plus " << ScaleCost << " scale cost";
Dan Gohman45774ce2010-02-12 10:34:29 +00001058 if (ImmCost != 0)
1059 OS << ", plus " << ImmCost << " imm cost";
1060 if (SetupCost != 0)
1061 OS << ", plus " << SetupCost << " setup cost";
1062}
1063
Manman Ren49d684e2012-09-12 05:06:18 +00001064#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman45774ce2010-02-12 10:34:29 +00001065void Cost::dump() const {
1066 print(errs()); errs() << '\n';
1067}
Manman Renc3366cc2012-09-06 19:55:56 +00001068#endif
Dan Gohman45774ce2010-02-12 10:34:29 +00001069
1070namespace {
1071
1072/// LSRFixup - An operand value in an instruction which is to be replaced
1073/// with some equivalent, possibly strength-reduced, replacement.
1074struct LSRFixup {
1075 /// UserInst - The instruction which will be updated.
1076 Instruction *UserInst;
1077
1078 /// OperandValToReplace - The operand of the instruction which will
1079 /// be replaced. The operand may be used more than once; every instance
1080 /// will be replaced.
1081 Value *OperandValToReplace;
1082
Dan Gohmand006ab92010-04-07 22:27:08 +00001083 /// PostIncLoops - If this user is to use the post-incremented value of an
Dan Gohman45774ce2010-02-12 10:34:29 +00001084 /// induction variable, this variable is non-null and holds the loop
1085 /// associated with the induction variable.
Dan Gohmand006ab92010-04-07 22:27:08 +00001086 PostIncLoopSet PostIncLoops;
Dan Gohman45774ce2010-02-12 10:34:29 +00001087
1088 /// LUIdx - The index of the LSRUse describing the expression which
1089 /// this fixup needs, minus an offset (below).
1090 size_t LUIdx;
1091
1092 /// Offset - A constant offset to be added to the LSRUse expression.
1093 /// This allows multiple fixups to share the same LSRUse with different
1094 /// offsets, for example in an unrolled loop.
1095 int64_t Offset;
1096
Dan Gohmand006ab92010-04-07 22:27:08 +00001097 bool isUseFullyOutsideLoop(const Loop *L) const;
1098
Dan Gohman45774ce2010-02-12 10:34:29 +00001099 LSRFixup();
1100
1101 void print(raw_ostream &OS) const;
1102 void dump() const;
1103};
1104
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001105}
Dan Gohman45774ce2010-02-12 10:34:29 +00001106
1107LSRFixup::LSRFixup()
Craig Topperf40110f2014-04-25 05:29:35 +00001108 : UserInst(nullptr), OperandValToReplace(nullptr), LUIdx(~size_t(0)),
1109 Offset(0) {}
Dan Gohman45774ce2010-02-12 10:34:29 +00001110
Dan Gohmand006ab92010-04-07 22:27:08 +00001111/// isUseFullyOutsideLoop - Test whether this fixup always uses its
1112/// value outside of the given loop.
1113bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
1114 // PHI nodes use their value in their incoming blocks.
1115 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
1116 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1117 if (PN->getIncomingValue(i) == OperandValToReplace &&
1118 L->contains(PN->getIncomingBlock(i)))
1119 return false;
1120 return true;
1121 }
1122
1123 return !L->contains(UserInst);
1124}
1125
Dan Gohman45774ce2010-02-12 10:34:29 +00001126void LSRFixup::print(raw_ostream &OS) const {
1127 OS << "UserInst=";
1128 // Store is common and interesting enough to be worth special-casing.
1129 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
1130 OS << "store ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001131 Store->getOperand(0)->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001132 } else if (UserInst->getType()->isVoidTy())
1133 OS << UserInst->getOpcodeName();
1134 else
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001135 UserInst->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001136
1137 OS << ", OperandValToReplace=";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001138 OperandValToReplace->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001139
Craig Topper042a3922015-05-25 20:01:18 +00001140 for (const Loop *PIL : PostIncLoops) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001141 OS << ", PostIncLoop=";
Craig Topper042a3922015-05-25 20:01:18 +00001142 PIL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001143 }
1144
1145 if (LUIdx != ~size_t(0))
1146 OS << ", LUIdx=" << LUIdx;
1147
1148 if (Offset != 0)
1149 OS << ", Offset=" << Offset;
1150}
1151
Manman Ren49d684e2012-09-12 05:06:18 +00001152#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman45774ce2010-02-12 10:34:29 +00001153void LSRFixup::dump() const {
1154 print(errs()); errs() << '\n';
1155}
Manman Renc3366cc2012-09-06 19:55:56 +00001156#endif
Dan Gohman45774ce2010-02-12 10:34:29 +00001157
1158namespace {
1159
1160/// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
1161/// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
1162struct UniquifierDenseMapInfo {
Preston Gurd25c3b6a2013-02-01 20:41:27 +00001163 static SmallVector<const SCEV *, 4> getEmptyKey() {
1164 SmallVector<const SCEV *, 4> V;
Dan Gohman45774ce2010-02-12 10:34:29 +00001165 V.push_back(reinterpret_cast<const SCEV *>(-1));
1166 return V;
1167 }
1168
Preston Gurd25c3b6a2013-02-01 20:41:27 +00001169 static SmallVector<const SCEV *, 4> getTombstoneKey() {
1170 SmallVector<const SCEV *, 4> V;
Dan Gohman45774ce2010-02-12 10:34:29 +00001171 V.push_back(reinterpret_cast<const SCEV *>(-2));
1172 return V;
1173 }
1174
Preston Gurd25c3b6a2013-02-01 20:41:27 +00001175 static unsigned getHashValue(const SmallVector<const SCEV *, 4> &V) {
Benjamin Kramer62fb0cf2014-03-15 17:17:48 +00001176 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
Dan Gohman45774ce2010-02-12 10:34:29 +00001177 }
1178
Preston Gurd25c3b6a2013-02-01 20:41:27 +00001179 static bool isEqual(const SmallVector<const SCEV *, 4> &LHS,
1180 const SmallVector<const SCEV *, 4> &RHS) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001181 return LHS == RHS;
1182 }
1183};
1184
1185/// LSRUse - This class holds the state that LSR keeps for each use in
1186/// IVUsers, as well as uses invented by LSR itself. It includes information
1187/// about what kinds of things can be folded into the user, information about
1188/// the user itself, and information about how the use may be satisfied.
1189/// TODO: Represent multiple users of the same expression in common?
1190class LSRUse {
Preston Gurd25c3b6a2013-02-01 20:41:27 +00001191 DenseSet<SmallVector<const SCEV *, 4>, UniquifierDenseMapInfo> Uniquifier;
Dan Gohman45774ce2010-02-12 10:34:29 +00001192
1193public:
1194 /// KindType - An enum for a kind of use, indicating what types of
1195 /// scaled and immediate operands it might support.
1196 enum KindType {
1197 Basic, ///< A normal use, with no folding.
1198 Special, ///< A special case of basic, allowing -1 scales.
Nadav Rotem4dc976f2012-10-19 21:28:43 +00001199 Address, ///< An address use; folding according to TargetLowering
Dan Gohman45774ce2010-02-12 10:34:29 +00001200 ICmpZero ///< An equality icmp with both operands folded into one.
1201 // TODO: Add a generic icmp too?
Dan Gohman045f8192010-01-22 00:46:49 +00001202 };
Dan Gohman45774ce2010-02-12 10:34:29 +00001203
Benjamin Kramer62fb0cf2014-03-15 17:17:48 +00001204 typedef PointerIntPair<const SCEV *, 2, KindType> SCEVUseKindPair;
1205
Dan Gohman45774ce2010-02-12 10:34:29 +00001206 KindType Kind;
Chris Lattner229907c2011-07-18 04:54:35 +00001207 Type *AccessTy;
Dan Gohman45774ce2010-02-12 10:34:29 +00001208
1209 SmallVector<int64_t, 8> Offsets;
1210 int64_t MinOffset;
1211 int64_t MaxOffset;
1212
1213 /// AllFixupsOutsideLoop - This records whether all of the fixups using this
1214 /// LSRUse are outside of the loop, in which case some special-case heuristics
1215 /// may be used.
1216 bool AllFixupsOutsideLoop;
1217
Andrew Trick57243da2013-10-25 21:35:56 +00001218 /// RigidFormula is set to true to guarantee that this use will be associated
1219 /// with a single formula--the one that initially matched. Some SCEV
1220 /// expressions cannot be expanded. This allows LSR to consider the registers
1221 /// used by those expressions without the need to expand them later after
1222 /// changing the formula.
1223 bool RigidFormula;
1224
Dan Gohman14152082010-07-15 20:24:58 +00001225 /// WidestFixupType - This records the widest use type for any fixup using
1226 /// this LSRUse. FindUseWithSimilarFormula can't consider uses with different
1227 /// max fixup widths to be equivalent, because the narrower one may be relying
1228 /// on the implicit truncation to truncate away bogus bits.
Chris Lattner229907c2011-07-18 04:54:35 +00001229 Type *WidestFixupType;
Dan Gohman14152082010-07-15 20:24:58 +00001230
Dan Gohman45774ce2010-02-12 10:34:29 +00001231 /// Formulae - A list of ways to build a value that can satisfy this user.
1232 /// After the list is populated, one of these is selected heuristically and
1233 /// used to formulate a replacement for OperandValToReplace in UserInst.
1234 SmallVector<Formula, 12> Formulae;
1235
1236 /// Regs - The set of register candidates used by all formulae in this LSRUse.
1237 SmallPtrSet<const SCEV *, 4> Regs;
1238
Chris Lattner229907c2011-07-18 04:54:35 +00001239 LSRUse(KindType K, Type *T) : Kind(K), AccessTy(T),
Dan Gohman45774ce2010-02-12 10:34:29 +00001240 MinOffset(INT64_MAX),
1241 MaxOffset(INT64_MIN),
Dan Gohman14152082010-07-15 20:24:58 +00001242 AllFixupsOutsideLoop(true),
Andrew Trick57243da2013-10-25 21:35:56 +00001243 RigidFormula(false),
Craig Topperf40110f2014-04-25 05:29:35 +00001244 WidestFixupType(nullptr) {}
Dan Gohman45774ce2010-02-12 10:34:29 +00001245
Dan Gohman20fab452010-05-19 23:43:12 +00001246 bool HasFormulaWithSameRegs(const Formula &F) const;
Dan Gohman8c16b382010-02-22 04:11:59 +00001247 bool InsertFormula(const Formula &F);
Dan Gohmanf1c7b1b2010-05-18 22:39:15 +00001248 void DeleteFormula(Formula &F);
Dan Gohman4cf99b52010-05-18 23:42:37 +00001249 void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
Dan Gohman45774ce2010-02-12 10:34:29 +00001250
Dan Gohman45774ce2010-02-12 10:34:29 +00001251 void print(raw_ostream &OS) const;
1252 void dump() const;
1253};
1254
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001255}
Dan Gohman297fb8b2010-06-19 21:21:39 +00001256
Dan Gohman20fab452010-05-19 23:43:12 +00001257/// HasFormula - Test whether this use as a formula which has the same
1258/// registers as the given formula.
1259bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
Preston Gurd25c3b6a2013-02-01 20:41:27 +00001260 SmallVector<const SCEV *, 4> Key = F.BaseRegs;
Dan Gohman20fab452010-05-19 23:43:12 +00001261 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1262 // Unstable sort by host order ok, because this is only used for uniquifying.
1263 std::sort(Key.begin(), Key.end());
1264 return Uniquifier.count(Key);
1265}
1266
Dan Gohman45774ce2010-02-12 10:34:29 +00001267/// InsertFormula - If the given formula has not yet been inserted, add it to
1268/// the list, and return true. Return false otherwise.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001269/// The formula must be in canonical form.
Dan Gohman8c16b382010-02-22 04:11:59 +00001270bool LSRUse::InsertFormula(const Formula &F) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001271 assert(F.isCanonical() && "Invalid canonical representation");
1272
Andrew Trick57243da2013-10-25 21:35:56 +00001273 if (!Formulae.empty() && RigidFormula)
1274 return false;
1275
Preston Gurd25c3b6a2013-02-01 20:41:27 +00001276 SmallVector<const SCEV *, 4> Key = F.BaseRegs;
Dan Gohman45774ce2010-02-12 10:34:29 +00001277 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1278 // Unstable sort by host order ok, because this is only used for uniquifying.
1279 std::sort(Key.begin(), Key.end());
1280
1281 if (!Uniquifier.insert(Key).second)
1282 return false;
1283
1284 // Using a register to hold the value of 0 is not profitable.
1285 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
1286 "Zero allocated in a scaled register!");
1287#ifndef NDEBUG
Craig Topper042a3922015-05-25 20:01:18 +00001288 for (const SCEV *BaseReg : F.BaseRegs)
1289 assert(!BaseReg->isZero() && "Zero allocated in a base register!");
Dan Gohman45774ce2010-02-12 10:34:29 +00001290#endif
1291
1292 // Add the formula to the list.
1293 Formulae.push_back(F);
1294
1295 // Record registers now being used by this use.
Dan Gohman45774ce2010-02-12 10:34:29 +00001296 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001297 if (F.ScaledReg)
1298 Regs.insert(F.ScaledReg);
Dan Gohman45774ce2010-02-12 10:34:29 +00001299
1300 return true;
Dan Gohman045f8192010-01-22 00:46:49 +00001301}
1302
Dan Gohmanf1c7b1b2010-05-18 22:39:15 +00001303/// DeleteFormula - Remove the given formula from this use's list.
1304void LSRUse::DeleteFormula(Formula &F) {
Dan Gohman80a96082010-05-20 15:17:54 +00001305 if (&F != &Formulae.back())
1306 std::swap(F, Formulae.back());
Dan Gohmanf1c7b1b2010-05-18 22:39:15 +00001307 Formulae.pop_back();
1308}
1309
Dan Gohman4cf99b52010-05-18 23:42:37 +00001310/// RecomputeRegs - Recompute the Regs field, and update RegUses.
1311void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
1312 // Now that we've filtered out some formulae, recompute the Regs set.
Benjamin Kramer1c2beed2015-02-19 17:19:43 +00001313 SmallPtrSet<const SCEV *, 4> OldRegs = std::move(Regs);
Dan Gohman4cf99b52010-05-18 23:42:37 +00001314 Regs.clear();
Benjamin Kramer1c2beed2015-02-19 17:19:43 +00001315 for (const Formula &F : Formulae) {
Dan Gohman4cf99b52010-05-18 23:42:37 +00001316 if (F.ScaledReg) Regs.insert(F.ScaledReg);
1317 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1318 }
1319
1320 // Update the RegTracker.
Craig Topper46276792014-08-24 23:23:06 +00001321 for (const SCEV *S : OldRegs)
1322 if (!Regs.count(S))
1323 RegUses.DropRegister(S, LUIdx);
Dan Gohman4cf99b52010-05-18 23:42:37 +00001324}
1325
Dan Gohman45774ce2010-02-12 10:34:29 +00001326void LSRUse::print(raw_ostream &OS) const {
1327 OS << "LSR Use: Kind=";
1328 switch (Kind) {
1329 case Basic: OS << "Basic"; break;
1330 case Special: OS << "Special"; break;
1331 case ICmpZero: OS << "ICmpZero"; break;
1332 case Address:
1333 OS << "Address of ";
Duncan Sands19d0b472010-02-16 11:11:14 +00001334 if (AccessTy->isPointerTy())
Dan Gohman45774ce2010-02-12 10:34:29 +00001335 OS << "pointer"; // the full pointer type could be really verbose
1336 else
1337 OS << *AccessTy;
Evan Cheng133694d2007-10-25 09:11:16 +00001338 }
1339
Dan Gohman45774ce2010-02-12 10:34:29 +00001340 OS << ", Offsets={";
Craig Topper042a3922015-05-25 20:01:18 +00001341 bool NeedComma = false;
1342 for (int64_t O : Offsets) {
1343 if (NeedComma) OS << ',';
1344 OS << O;
1345 NeedComma = true;
Dan Gohman045f8192010-01-22 00:46:49 +00001346 }
Dan Gohman45774ce2010-02-12 10:34:29 +00001347 OS << '}';
Dan Gohman045f8192010-01-22 00:46:49 +00001348
Dan Gohman45774ce2010-02-12 10:34:29 +00001349 if (AllFixupsOutsideLoop)
1350 OS << ", all-fixups-outside-loop";
Dan Gohman14152082010-07-15 20:24:58 +00001351
1352 if (WidestFixupType)
1353 OS << ", widest fixup type: " << *WidestFixupType;
Dan Gohman045f8192010-01-22 00:46:49 +00001354}
1355
Manman Ren49d684e2012-09-12 05:06:18 +00001356#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman45774ce2010-02-12 10:34:29 +00001357void LSRUse::dump() const {
1358 print(errs()); errs() << '\n';
1359}
Manman Renc3366cc2012-09-06 19:55:56 +00001360#endif
Dan Gohman045f8192010-01-22 00:46:49 +00001361
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001362static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1363 LSRUse::KindType Kind, Type *AccessTy,
1364 GlobalValue *BaseGV, int64_t BaseOffset,
1365 bool HasBaseReg, int64_t Scale) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001366 switch (Kind) {
1367 case LSRUse::Address:
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001368 return TTI.isLegalAddressingMode(AccessTy, BaseGV, BaseOffset, HasBaseReg, Scale);
Dan Gohman45774ce2010-02-12 10:34:29 +00001369
Dan Gohman45774ce2010-02-12 10:34:29 +00001370 case LSRUse::ICmpZero:
1371 // There's not even a target hook for querying whether it would be legal to
1372 // fold a GV into an ICmp.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001373 if (BaseGV)
Dan Gohman45774ce2010-02-12 10:34:29 +00001374 return false;
1375
1376 // ICmp only has two operands; don't allow more than two non-trivial parts.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001377 if (Scale != 0 && HasBaseReg && BaseOffset != 0)
Dan Gohman45774ce2010-02-12 10:34:29 +00001378 return false;
1379
1380 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1381 // putting the scaled register in the other operand of the icmp.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001382 if (Scale != 0 && Scale != -1)
Dan Gohman45774ce2010-02-12 10:34:29 +00001383 return false;
1384
1385 // If we have low-level target information, ask the target if it can fold an
1386 // integer immediate on an icmp.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001387 if (BaseOffset != 0) {
Jakob Stoklund Olesenf2390e82012-04-05 03:10:56 +00001388 // We have one of:
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001389 // ICmpZero BaseReg + BaseOffset => ICmp BaseReg, -BaseOffset
1390 // ICmpZero -1*ScaleReg + BaseOffset => ICmp ScaleReg, BaseOffset
Jakob Stoklund Olesenf2390e82012-04-05 03:10:56 +00001391 // Offs is the ICmp immediate.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001392 if (Scale == 0)
1393 // The cast does the right thing with INT64_MIN.
1394 BaseOffset = -(uint64_t)BaseOffset;
1395 return TTI.isLegalICmpImmediate(BaseOffset);
Dan Gohman045f8192010-01-22 00:46:49 +00001396 }
Dan Gohman45774ce2010-02-12 10:34:29 +00001397
Jakob Stoklund Olesenf2390e82012-04-05 03:10:56 +00001398 // ICmpZero BaseReg + -1*ScaleReg => ICmp BaseReg, ScaleReg
Dan Gohman45774ce2010-02-12 10:34:29 +00001399 return true;
1400
1401 case LSRUse::Basic:
1402 // Only handle single-register values.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001403 return !BaseGV && Scale == 0 && BaseOffset == 0;
Dan Gohman45774ce2010-02-12 10:34:29 +00001404
1405 case LSRUse::Special:
Andrew Trickaca8fb32012-06-15 20:07:26 +00001406 // Special case Basic to handle -1 scales.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001407 return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset == 0;
Dan Gohman045f8192010-01-22 00:46:49 +00001408 }
1409
David Blaikie46a9f012012-01-20 21:51:11 +00001410 llvm_unreachable("Invalid LSRUse Kind!");
Dan Gohman045f8192010-01-22 00:46:49 +00001411}
1412
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001413static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1414 int64_t MinOffset, int64_t MaxOffset,
1415 LSRUse::KindType Kind, Type *AccessTy,
1416 GlobalValue *BaseGV, int64_t BaseOffset,
1417 bool HasBaseReg, int64_t Scale) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001418 // Check for overflow.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001419 if (((int64_t)((uint64_t)BaseOffset + MinOffset) > BaseOffset) !=
Dan Gohman45774ce2010-02-12 10:34:29 +00001420 (MinOffset > 0))
1421 return false;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001422 MinOffset = (uint64_t)BaseOffset + MinOffset;
1423 if (((int64_t)((uint64_t)BaseOffset + MaxOffset) > BaseOffset) !=
1424 (MaxOffset > 0))
1425 return false;
1426 MaxOffset = (uint64_t)BaseOffset + MaxOffset;
1427
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001428 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MinOffset,
1429 HasBaseReg, Scale) &&
1430 isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MaxOffset,
1431 HasBaseReg, Scale);
1432}
1433
1434static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1435 int64_t MinOffset, int64_t MaxOffset,
1436 LSRUse::KindType Kind, Type *AccessTy,
1437 const Formula &F) {
1438 // For the purpose of isAMCompletelyFolded either having a canonical formula
1439 // or a scale not equal to zero is correct.
1440 // Problems may arise from non canonical formulae having a scale == 0.
1441 // Strictly speaking it would best to just rely on canonical formulae.
1442 // However, when we generate the scaled formulae, we first check that the
1443 // scaling factor is profitable before computing the actual ScaledReg for
1444 // compile time sake.
1445 assert((F.isCanonical() || F.Scale != 0));
1446 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1447 F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale);
1448}
1449
1450/// isLegalUse - Test whether we know how to expand the current formula.
1451static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
1452 int64_t MaxOffset, LSRUse::KindType Kind, Type *AccessTy,
1453 GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg,
1454 int64_t Scale) {
1455 // We know how to expand completely foldable formulae.
1456 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
1457 BaseOffset, HasBaseReg, Scale) ||
1458 // Or formulae that use a base register produced by a sum of base
1459 // registers.
1460 (Scale == 1 &&
1461 isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1462 BaseGV, BaseOffset, true, 0));
Dan Gohman045f8192010-01-22 00:46:49 +00001463}
1464
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001465static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
1466 int64_t MaxOffset, LSRUse::KindType Kind, Type *AccessTy,
1467 const Formula &F) {
Chandler Carruth6e479322013-01-07 15:04:40 +00001468 return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV,
1469 F.BaseOffset, F.HasBaseReg, F.Scale);
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001470}
1471
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001472static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1473 const LSRUse &LU, const Formula &F) {
1474 return isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
1475 LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg,
1476 F.Scale);
1477}
Quentin Colombet8aa7abe2013-05-31 17:20:29 +00001478
Quentin Colombetbf490d42013-05-31 21:29:03 +00001479static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
1480 const LSRUse &LU, const Formula &F) {
1481 if (!F.Scale)
1482 return 0;
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001483
1484 // If the use is not completely folded in that instruction, we will have to
1485 // pay an extra cost only for scale != 1.
1486 if (!isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
1487 LU.AccessTy, F))
1488 return F.Scale != 1;
Quentin Colombetbf490d42013-05-31 21:29:03 +00001489
1490 switch (LU.Kind) {
1491 case LSRUse::Address: {
Quentin Colombet145eb972013-06-19 19:59:41 +00001492 // Check the scaling factor cost with both the min and max offsets.
1493 int ScaleCostMinOffset =
1494 TTI.getScalingFactorCost(LU.AccessTy, F.BaseGV,
1495 F.BaseOffset + LU.MinOffset,
1496 F.HasBaseReg, F.Scale);
1497 int ScaleCostMaxOffset =
1498 TTI.getScalingFactorCost(LU.AccessTy, F.BaseGV,
1499 F.BaseOffset + LU.MaxOffset,
1500 F.HasBaseReg, F.Scale);
1501
1502 assert(ScaleCostMinOffset >= 0 && ScaleCostMaxOffset >= 0 &&
1503 "Legal addressing mode has an illegal cost!");
1504 return std::max(ScaleCostMinOffset, ScaleCostMaxOffset);
Quentin Colombetbf490d42013-05-31 21:29:03 +00001505 }
1506 case LSRUse::ICmpZero:
Quentin Colombetbf490d42013-05-31 21:29:03 +00001507 case LSRUse::Basic:
1508 case LSRUse::Special:
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001509 // The use is completely folded, i.e., everything is folded into the
1510 // instruction.
Quentin Colombetbf490d42013-05-31 21:29:03 +00001511 return 0;
1512 }
1513
1514 llvm_unreachable("Invalid LSRUse Kind!");
1515}
1516
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001517static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
Chris Lattner229907c2011-07-18 04:54:35 +00001518 LSRUse::KindType Kind, Type *AccessTy,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001519 GlobalValue *BaseGV, int64_t BaseOffset,
1520 bool HasBaseReg) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001521 // Fast-path: zero is always foldable.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001522 if (BaseOffset == 0 && !BaseGV) return true;
Dan Gohman045f8192010-01-22 00:46:49 +00001523
Dan Gohman45774ce2010-02-12 10:34:29 +00001524 // Conservatively, create an address with an immediate and a
1525 // base and a scale.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001526 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
Dan Gohman045f8192010-01-22 00:46:49 +00001527
Dan Gohman20fab452010-05-19 23:43:12 +00001528 // Canonicalize a scale of 1 to a base register if the formula doesn't
1529 // already have a base register.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001530 if (!HasBaseReg && Scale == 1) {
1531 Scale = 0;
1532 HasBaseReg = true;
Dan Gohman20fab452010-05-19 23:43:12 +00001533 }
1534
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001535 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset,
1536 HasBaseReg, Scale);
Dan Gohman045f8192010-01-22 00:46:49 +00001537}
1538
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001539static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
1540 ScalarEvolution &SE, int64_t MinOffset,
1541 int64_t MaxOffset, LSRUse::KindType Kind,
1542 Type *AccessTy, const SCEV *S, bool HasBaseReg) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001543 // Fast-path: zero is always foldable.
1544 if (S->isZero()) return true;
1545
1546 // Conservatively, create an address with an immediate and a
1547 // base and a scale.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001548 int64_t BaseOffset = ExtractImmediate(S, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +00001549 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1550
1551 // If there's anything else involved, it's not foldable.
1552 if (!S->isZero()) return false;
1553
1554 // Fast-path: zero is always foldable.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001555 if (BaseOffset == 0 && !BaseGV) return true;
Dan Gohman45774ce2010-02-12 10:34:29 +00001556
1557 // Conservatively, create an address with an immediate and a
1558 // base and a scale.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001559 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
Dan Gohman45774ce2010-02-12 10:34:29 +00001560
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001561 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
1562 BaseOffset, HasBaseReg, Scale);
Dan Gohman045f8192010-01-22 00:46:49 +00001563}
1564
Dan Gohman297fb8b2010-06-19 21:21:39 +00001565namespace {
1566
Andrew Trick29fe5f02012-01-09 19:50:34 +00001567/// IVInc - An individual increment in a Chain of IV increments.
1568/// Relate an IV user to an expression that computes the IV it uses from the IV
1569/// used by the previous link in the Chain.
1570///
1571/// For the head of a chain, IncExpr holds the absolute SCEV expression for the
1572/// original IVOperand. The head of the chain's IVOperand is only valid during
1573/// chain collection, before LSR replaces IV users. During chain generation,
1574/// IncExpr can be used to find the new IVOperand that computes the same
1575/// expression.
1576struct IVInc {
1577 Instruction *UserInst;
1578 Value* IVOperand;
1579 const SCEV *IncExpr;
1580
1581 IVInc(Instruction *U, Value *O, const SCEV *E):
1582 UserInst(U), IVOperand(O), IncExpr(E) {}
1583};
1584
1585// IVChain - The list of IV increments in program order.
1586// We typically add the head of a chain without finding subsequent links.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001587struct IVChain {
1588 SmallVector<IVInc,1> Incs;
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00001589 const SCEV *ExprBase;
1590
Craig Topperf40110f2014-04-25 05:29:35 +00001591 IVChain() : ExprBase(nullptr) {}
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00001592
1593 IVChain(const IVInc &Head, const SCEV *Base)
1594 : Incs(1, Head), ExprBase(Base) {}
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001595
1596 typedef SmallVectorImpl<IVInc>::const_iterator const_iterator;
1597
1598 // begin - return the first increment in the chain.
1599 const_iterator begin() const {
1600 assert(!Incs.empty());
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001601 return std::next(Incs.begin());
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001602 }
1603 const_iterator end() const {
1604 return Incs.end();
1605 }
1606
1607 // hasIncs - Returns true if this chain contains any increments.
1608 bool hasIncs() const { return Incs.size() >= 2; }
1609
1610 // add - Add an IVInc to the end of this chain.
1611 void add(const IVInc &X) { Incs.push_back(X); }
1612
1613 // tailUserInst - Returns the last UserInst in the chain.
1614 Instruction *tailUserInst() const { return Incs.back().UserInst; }
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00001615
1616 // isProfitableIncrement - Returns true if IncExpr can be profitably added to
1617 // this chain.
1618 bool isProfitableIncrement(const SCEV *OperExpr,
1619 const SCEV *IncExpr,
1620 ScalarEvolution&);
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001621};
Andrew Trick29fe5f02012-01-09 19:50:34 +00001622
1623/// ChainUsers - Helper for CollectChains to track multiple IV increment uses.
1624/// Distinguish between FarUsers that definitely cross IV increments and
1625/// NearUsers that may be used between IV increments.
1626struct ChainUsers {
1627 SmallPtrSet<Instruction*, 4> FarUsers;
1628 SmallPtrSet<Instruction*, 4> NearUsers;
1629};
1630
Dan Gohman45774ce2010-02-12 10:34:29 +00001631/// LSRInstance - This class holds state for the main loop strength reduction
1632/// logic.
1633class LSRInstance {
1634 IVUsers &IU;
1635 ScalarEvolution &SE;
1636 DominatorTree &DT;
Dan Gohman607e02b2010-04-09 22:07:05 +00001637 LoopInfo &LI;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001638 const TargetTransformInfo &TTI;
Dan Gohman45774ce2010-02-12 10:34:29 +00001639 Loop *const L;
1640 bool Changed;
1641
1642 /// IVIncInsertPos - This is the insert position that the current loop's
1643 /// induction variable increment should be placed. In simple loops, this is
1644 /// the latch block's terminator. But in more complicated cases, this is a
1645 /// position which will dominate all the in-loop post-increment users.
1646 Instruction *IVIncInsertPos;
1647
1648 /// Factors - Interesting factors between use strides.
1649 SmallSetVector<int64_t, 8> Factors;
1650
1651 /// Types - Interesting use types, to facilitate truncation reuse.
Chris Lattner229907c2011-07-18 04:54:35 +00001652 SmallSetVector<Type *, 4> Types;
Dan Gohman45774ce2010-02-12 10:34:29 +00001653
1654 /// Fixups - The list of operands which are to be replaced.
1655 SmallVector<LSRFixup, 16> Fixups;
1656
1657 /// Uses - The list of interesting uses.
1658 SmallVector<LSRUse, 16> Uses;
1659
1660 /// RegUses - Track which uses use which register candidates.
1661 RegUseTracker RegUses;
1662
Andrew Trick29fe5f02012-01-09 19:50:34 +00001663 // Limit the number of chains to avoid quadratic behavior. We don't expect to
1664 // have more than a few IV increment chains in a loop. Missing a Chain falls
1665 // back to normal LSR behavior for those uses.
1666 static const unsigned MaxChains = 8;
1667
1668 /// IVChainVec - IV users can form a chain of IV increments.
1669 SmallVector<IVChain, MaxChains> IVChainVec;
1670
Andrew Trick248d4102012-01-09 21:18:52 +00001671 /// IVIncSet - IV users that belong to profitable IVChains.
1672 SmallPtrSet<Use*, MaxChains> IVIncSet;
1673
Dan Gohman45774ce2010-02-12 10:34:29 +00001674 void OptimizeShadowIV();
1675 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1676 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
Dan Gohman4c4043c2010-05-20 20:05:31 +00001677 void OptimizeLoopTermCond();
Dan Gohman45774ce2010-02-12 10:34:29 +00001678
Andrew Trick29fe5f02012-01-09 19:50:34 +00001679 void ChainInstruction(Instruction *UserInst, Instruction *IVOper,
1680 SmallVectorImpl<ChainUsers> &ChainUsersVec);
Andrew Trick248d4102012-01-09 21:18:52 +00001681 void FinalizeChain(IVChain &Chain);
Andrew Trick29fe5f02012-01-09 19:50:34 +00001682 void CollectChains();
Andrew Trick248d4102012-01-09 21:18:52 +00001683 void GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
1684 SmallVectorImpl<WeakVH> &DeadInsts);
Andrew Trick29fe5f02012-01-09 19:50:34 +00001685
Dan Gohman45774ce2010-02-12 10:34:29 +00001686 void CollectInterestingTypesAndFactors();
1687 void CollectFixupsAndInitialFormulae();
1688
1689 LSRFixup &getNewFixup() {
1690 Fixups.push_back(LSRFixup());
1691 return Fixups.back();
1692 }
1693
1694 // Support for sharing of LSRUses between LSRFixups.
Benjamin Kramer62fb0cf2014-03-15 17:17:48 +00001695 typedef DenseMap<LSRUse::SCEVUseKindPair, size_t> UseMapTy;
Dan Gohman45774ce2010-02-12 10:34:29 +00001696 UseMapTy UseMap;
1697
Dan Gohman110ed642010-09-01 01:45:53 +00001698 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
Chris Lattner229907c2011-07-18 04:54:35 +00001699 LSRUse::KindType Kind, Type *AccessTy);
Dan Gohman45774ce2010-02-12 10:34:29 +00001700
1701 std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
1702 LSRUse::KindType Kind,
Chris Lattner229907c2011-07-18 04:54:35 +00001703 Type *AccessTy);
Dan Gohman45774ce2010-02-12 10:34:29 +00001704
Dan Gohmana7b68d62010-10-07 23:33:43 +00001705 void DeleteUse(LSRUse &LU, size_t LUIdx);
Dan Gohman80a96082010-05-20 15:17:54 +00001706
Dan Gohman110ed642010-09-01 01:45:53 +00001707 LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
Dan Gohman20fab452010-05-19 23:43:12 +00001708
Dan Gohman8c16b382010-02-22 04:11:59 +00001709 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
Dan Gohman45774ce2010-02-12 10:34:29 +00001710 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1711 void CountRegisters(const Formula &F, size_t LUIdx);
1712 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1713
1714 void CollectLoopInvariantFixupsAndFormulae();
1715
1716 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1717 unsigned Depth = 0);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001718
1719 void GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
1720 const Formula &Base, unsigned Depth,
1721 size_t Idx, bool IsScaledReg = false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001722 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001723 void GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
1724 const Formula &Base, size_t Idx,
1725 bool IsScaledReg = false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001726 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001727 void GenerateConstantOffsetsImpl(LSRUse &LU, unsigned LUIdx,
1728 const Formula &Base,
1729 const SmallVectorImpl<int64_t> &Worklist,
1730 size_t Idx, bool IsScaledReg = false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001731 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1732 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1733 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1734 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1735 void GenerateCrossUseConstantOffsets();
1736 void GenerateAllReuseFormulae();
1737
1738 void FilterOutUndesirableDedicatedRegisters();
Dan Gohmana4eca052010-05-18 22:51:59 +00001739
1740 size_t EstimateSearchSpaceComplexity() const;
Dan Gohmane9e08732010-08-29 16:09:42 +00001741 void NarrowSearchSpaceByDetectingSupersets();
1742 void NarrowSearchSpaceByCollapsingUnrolledCode();
Dan Gohman002ff892010-08-29 16:39:22 +00001743 void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
Dan Gohmane9e08732010-08-29 16:09:42 +00001744 void NarrowSearchSpaceByPickingWinnerRegs();
Dan Gohman45774ce2010-02-12 10:34:29 +00001745 void NarrowSearchSpaceUsingHeuristics();
1746
1747 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1748 Cost &SolutionCost,
1749 SmallVectorImpl<const Formula *> &Workspace,
1750 const Cost &CurCost,
1751 const SmallPtrSet<const SCEV *, 16> &CurRegs,
1752 DenseSet<const SCEV *> &VisitedRegs) const;
1753 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1754
Dan Gohman607e02b2010-04-09 22:07:05 +00001755 BasicBlock::iterator
1756 HoistInsertPosition(BasicBlock::iterator IP,
1757 const SmallVectorImpl<Instruction *> &Inputs) const;
Andrew Trickc908b432012-01-20 07:41:13 +00001758 BasicBlock::iterator
1759 AdjustInsertPositionForExpand(BasicBlock::iterator IP,
1760 const LSRFixup &LF,
1761 const LSRUse &LU,
1762 SCEVExpander &Rewriter) const;
Dan Gohmand2df6432010-04-09 02:00:38 +00001763
Dan Gohman45774ce2010-02-12 10:34:29 +00001764 Value *Expand(const LSRFixup &LF,
1765 const Formula &F,
Dan Gohman8c16b382010-02-22 04:11:59 +00001766 BasicBlock::iterator IP,
Dan Gohman45774ce2010-02-12 10:34:29 +00001767 SCEVExpander &Rewriter,
Dan Gohman8c16b382010-02-22 04:11:59 +00001768 SmallVectorImpl<WeakVH> &DeadInsts) const;
Dan Gohman6deab962010-02-16 20:25:07 +00001769 void RewriteForPHI(PHINode *PN, const LSRFixup &LF,
1770 const Formula &F,
Dan Gohman6deab962010-02-16 20:25:07 +00001771 SCEVExpander &Rewriter,
1772 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman6deab962010-02-16 20:25:07 +00001773 Pass *P) const;
Dan Gohman45774ce2010-02-12 10:34:29 +00001774 void Rewrite(const LSRFixup &LF,
1775 const Formula &F,
Dan Gohman45774ce2010-02-12 10:34:29 +00001776 SCEVExpander &Rewriter,
1777 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman45774ce2010-02-12 10:34:29 +00001778 Pass *P) const;
1779 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
1780 Pass *P);
1781
Andrew Trickdc18e382011-12-13 00:55:33 +00001782public:
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001783 LSRInstance(Loop *L, Pass *P);
Dan Gohman45774ce2010-02-12 10:34:29 +00001784
1785 bool getChanged() const { return Changed; }
1786
1787 void print_factors_and_types(raw_ostream &OS) const;
1788 void print_fixups(raw_ostream &OS) const;
1789 void print_uses(raw_ostream &OS) const;
1790 void print(raw_ostream &OS) const;
1791 void dump() const;
1792};
1793
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001794}
Dan Gohman45774ce2010-02-12 10:34:29 +00001795
1796/// OptimizeShadowIV - If IV is used in a int-to-float cast
Dan Gohman8b0a4192010-03-01 17:49:51 +00001797/// inside the loop then try to eliminate the cast operation.
Dan Gohman45774ce2010-02-12 10:34:29 +00001798void LSRInstance::OptimizeShadowIV() {
1799 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1800 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1801 return;
1802
1803 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1804 UI != E; /* empty */) {
1805 IVUsers::const_iterator CandidateUI = UI;
1806 ++UI;
1807 Instruction *ShadowUse = CandidateUI->getUser();
Craig Topperf40110f2014-04-25 05:29:35 +00001808 Type *DestTy = nullptr;
Andrew Trick858e9f02011-07-21 01:05:01 +00001809 bool IsSigned = false;
Dan Gohman45774ce2010-02-12 10:34:29 +00001810
1811 /* If shadow use is a int->float cast then insert a second IV
1812 to eliminate this cast.
1813
1814 for (unsigned i = 0; i < n; ++i)
1815 foo((double)i);
1816
1817 is transformed into
1818
1819 double d = 0.0;
1820 for (unsigned i = 0; i < n; ++i, ++d)
1821 foo(d);
1822 */
Andrew Trick858e9f02011-07-21 01:05:01 +00001823 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) {
1824 IsSigned = false;
Dan Gohman45774ce2010-02-12 10:34:29 +00001825 DestTy = UCast->getDestTy();
Andrew Trick858e9f02011-07-21 01:05:01 +00001826 }
1827 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) {
1828 IsSigned = true;
Dan Gohman45774ce2010-02-12 10:34:29 +00001829 DestTy = SCast->getDestTy();
Andrew Trick858e9f02011-07-21 01:05:01 +00001830 }
Dan Gohman45774ce2010-02-12 10:34:29 +00001831 if (!DestTy) continue;
1832
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001833 // If target does not support DestTy natively then do not apply
1834 // this transformation.
1835 if (!TTI.isTypeLegal(DestTy)) continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00001836
1837 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1838 if (!PH) continue;
1839 if (PH->getNumIncomingValues() != 2) continue;
1840
Chris Lattner229907c2011-07-18 04:54:35 +00001841 Type *SrcTy = PH->getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00001842 int Mantissa = DestTy->getFPMantissaWidth();
1843 if (Mantissa == -1) continue;
1844 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1845 continue;
1846
1847 unsigned Entry, Latch;
1848 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1849 Entry = 0;
1850 Latch = 1;
Dan Gohman045f8192010-01-22 00:46:49 +00001851 } else {
Dan Gohman45774ce2010-02-12 10:34:29 +00001852 Entry = 1;
1853 Latch = 0;
Dan Gohman045f8192010-01-22 00:46:49 +00001854 }
Dan Gohman045f8192010-01-22 00:46:49 +00001855
Dan Gohman45774ce2010-02-12 10:34:29 +00001856 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
1857 if (!Init) continue;
Andrew Trick858e9f02011-07-21 01:05:01 +00001858 Constant *NewInit = ConstantFP::get(DestTy, IsSigned ?
Andrew Trickbd243d02011-07-21 01:45:54 +00001859 (double)Init->getSExtValue() :
1860 (double)Init->getZExtValue());
Dan Gohman045f8192010-01-22 00:46:49 +00001861
Dan Gohman45774ce2010-02-12 10:34:29 +00001862 BinaryOperator *Incr =
1863 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
1864 if (!Incr) continue;
1865 if (Incr->getOpcode() != Instruction::Add
1866 && Incr->getOpcode() != Instruction::Sub)
Dan Gohman045f8192010-01-22 00:46:49 +00001867 continue;
Dan Gohman045f8192010-01-22 00:46:49 +00001868
Dan Gohman45774ce2010-02-12 10:34:29 +00001869 /* Initialize new IV, double d = 0.0 in above example. */
Craig Topperf40110f2014-04-25 05:29:35 +00001870 ConstantInt *C = nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +00001871 if (Incr->getOperand(0) == PH)
1872 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
1873 else if (Incr->getOperand(1) == PH)
1874 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
Dan Gohman045f8192010-01-22 00:46:49 +00001875 else
Dan Gohman045f8192010-01-22 00:46:49 +00001876 continue;
1877
Dan Gohman45774ce2010-02-12 10:34:29 +00001878 if (!C) continue;
Dan Gohman045f8192010-01-22 00:46:49 +00001879
Dan Gohman45774ce2010-02-12 10:34:29 +00001880 // Ignore negative constants, as the code below doesn't handle them
1881 // correctly. TODO: Remove this restriction.
1882 if (!C->getValue().isStrictlyPositive()) continue;
Dan Gohman045f8192010-01-22 00:46:49 +00001883
Dan Gohman45774ce2010-02-12 10:34:29 +00001884 /* Add new PHINode. */
Jay Foad52131342011-03-30 11:28:46 +00001885 PHINode *NewPH = PHINode::Create(DestTy, 2, "IV.S.", PH);
Dan Gohman045f8192010-01-22 00:46:49 +00001886
Dan Gohman45774ce2010-02-12 10:34:29 +00001887 /* create new increment. '++d' in above example. */
1888 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1889 BinaryOperator *NewIncr =
1890 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1891 Instruction::FAdd : Instruction::FSub,
1892 NewPH, CFP, "IV.S.next.", Incr);
Dan Gohman045f8192010-01-22 00:46:49 +00001893
Dan Gohman45774ce2010-02-12 10:34:29 +00001894 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1895 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
Dan Gohman045f8192010-01-22 00:46:49 +00001896
Dan Gohman45774ce2010-02-12 10:34:29 +00001897 /* Remove cast operation */
1898 ShadowUse->replaceAllUsesWith(NewPH);
1899 ShadowUse->eraseFromParent();
Dan Gohman4c4043c2010-05-20 20:05:31 +00001900 Changed = true;
Dan Gohman45774ce2010-02-12 10:34:29 +00001901 break;
Dan Gohman045f8192010-01-22 00:46:49 +00001902 }
1903}
1904
1905/// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1906/// set the IV user and stride information and return true, otherwise return
1907/// false.
Dan Gohmanab5fb7f2010-05-20 19:44:23 +00001908bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) {
Craig Topper042a3922015-05-25 20:01:18 +00001909 for (IVStrideUse &U : IU)
1910 if (U.getUser() == Cond) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001911 // NOTE: we could handle setcc instructions with multiple uses here, but
1912 // InstCombine does it as well for simple uses, it's not clear that it
1913 // occurs enough in real life to handle.
Craig Topper042a3922015-05-25 20:01:18 +00001914 CondUse = &U;
Dan Gohman45774ce2010-02-12 10:34:29 +00001915 return true;
1916 }
Dan Gohman045f8192010-01-22 00:46:49 +00001917 return false;
Evan Cheng133694d2007-10-25 09:11:16 +00001918}
1919
Dan Gohman045f8192010-01-22 00:46:49 +00001920/// OptimizeMax - Rewrite the loop's terminating condition if it uses
1921/// a max computation.
1922///
1923/// This is a narrow solution to a specific, but acute, problem. For loops
1924/// like this:
1925///
1926/// i = 0;
1927/// do {
1928/// p[i] = 0.0;
1929/// } while (++i < n);
1930///
1931/// the trip count isn't just 'n', because 'n' might not be positive. And
1932/// unfortunately this can come up even for loops where the user didn't use
1933/// a C do-while loop. For example, seemingly well-behaved top-test loops
1934/// will commonly be lowered like this:
1935//
1936/// if (n > 0) {
1937/// i = 0;
1938/// do {
1939/// p[i] = 0.0;
1940/// } while (++i < n);
1941/// }
1942///
1943/// and then it's possible for subsequent optimization to obscure the if
1944/// test in such a way that indvars can't find it.
1945///
1946/// When indvars can't find the if test in loops like this, it creates a
1947/// max expression, which allows it to give the loop a canonical
1948/// induction variable:
1949///
1950/// i = 0;
1951/// max = n < 1 ? 1 : n;
1952/// do {
1953/// p[i] = 0.0;
1954/// } while (++i != max);
1955///
1956/// Canonical induction variables are necessary because the loop passes
1957/// are designed around them. The most obvious example of this is the
1958/// LoopInfo analysis, which doesn't remember trip count values. It
1959/// expects to be able to rediscover the trip count each time it is
Dan Gohman45774ce2010-02-12 10:34:29 +00001960/// needed, and it does this using a simple analysis that only succeeds if
Dan Gohman045f8192010-01-22 00:46:49 +00001961/// the loop has a canonical induction variable.
1962///
1963/// However, when it comes time to generate code, the maximum operation
1964/// can be quite costly, especially if it's inside of an outer loop.
1965///
1966/// This function solves this problem by detecting this type of loop and
1967/// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
1968/// the instructions for the maximum computation.
1969///
Dan Gohman45774ce2010-02-12 10:34:29 +00001970ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
Dan Gohman045f8192010-01-22 00:46:49 +00001971 // Check that the loop matches the pattern we're looking for.
1972 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
1973 Cond->getPredicate() != CmpInst::ICMP_NE)
1974 return Cond;
Dan Gohman51ad99d2010-01-21 02:09:26 +00001975
Dan Gohman045f8192010-01-22 00:46:49 +00001976 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
1977 if (!Sel || !Sel->hasOneUse()) return Cond;
Dan Gohman51ad99d2010-01-21 02:09:26 +00001978
Dan Gohman45774ce2010-02-12 10:34:29 +00001979 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
Dan Gohman045f8192010-01-22 00:46:49 +00001980 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1981 return Cond;
Dan Gohman1d2ded72010-05-03 22:09:21 +00001982 const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001983
Dan Gohman045f8192010-01-22 00:46:49 +00001984 // Add one to the backedge-taken count to get the trip count.
Dan Gohman9b7632d2010-08-16 15:39:27 +00001985 const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount);
Dan Gohman534ba372010-04-24 03:13:44 +00001986 if (IterationCount != SE.getSCEV(Sel)) return Cond;
Dan Gohman045f8192010-01-22 00:46:49 +00001987
Dan Gohman534ba372010-04-24 03:13:44 +00001988 // Check for a max calculation that matches the pattern. There's no check
1989 // for ICMP_ULE here because the comparison would be with zero, which
1990 // isn't interesting.
1991 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
Craig Topperf40110f2014-04-25 05:29:35 +00001992 const SCEVNAryExpr *Max = nullptr;
Dan Gohman534ba372010-04-24 03:13:44 +00001993 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
1994 Pred = ICmpInst::ICMP_SLE;
1995 Max = S;
1996 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
1997 Pred = ICmpInst::ICMP_SLT;
1998 Max = S;
1999 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
2000 Pred = ICmpInst::ICMP_ULT;
2001 Max = U;
2002 } else {
2003 // No match; bail.
Dan Gohman045f8192010-01-22 00:46:49 +00002004 return Cond;
Dan Gohman534ba372010-04-24 03:13:44 +00002005 }
Dan Gohman045f8192010-01-22 00:46:49 +00002006
2007 // To handle a max with more than two operands, this optimization would
2008 // require additional checking and setup.
2009 if (Max->getNumOperands() != 2)
2010 return Cond;
2011
2012 const SCEV *MaxLHS = Max->getOperand(0);
2013 const SCEV *MaxRHS = Max->getOperand(1);
Dan Gohman534ba372010-04-24 03:13:44 +00002014
2015 // ScalarEvolution canonicalizes constants to the left. For < and >, look
2016 // for a comparison with 1. For <= and >=, a comparison with zero.
2017 if (!MaxLHS ||
2018 (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
2019 return Cond;
2020
Dan Gohman045f8192010-01-22 00:46:49 +00002021 // Check the relevant induction variable for conformance to
2022 // the pattern.
Dan Gohman45774ce2010-02-12 10:34:29 +00002023 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
Dan Gohman045f8192010-01-22 00:46:49 +00002024 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2025 if (!AR || !AR->isAffine() ||
2026 AR->getStart() != One ||
Dan Gohman45774ce2010-02-12 10:34:29 +00002027 AR->getStepRecurrence(SE) != One)
Dan Gohman045f8192010-01-22 00:46:49 +00002028 return Cond;
2029
2030 assert(AR->getLoop() == L &&
2031 "Loop condition operand is an addrec in a different loop!");
2032
2033 // Check the right operand of the select, and remember it, as it will
2034 // be used in the new comparison instruction.
Craig Topperf40110f2014-04-25 05:29:35 +00002035 Value *NewRHS = nullptr;
Dan Gohman534ba372010-04-24 03:13:44 +00002036 if (ICmpInst::isTrueWhenEqual(Pred)) {
2037 // Look for n+1, and grab n.
2038 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
Jakub Staszakf6df1e32013-03-24 09:25:47 +00002039 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2040 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
2041 NewRHS = BO->getOperand(0);
Dan Gohman534ba372010-04-24 03:13:44 +00002042 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
Jakub Staszakf6df1e32013-03-24 09:25:47 +00002043 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2044 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
2045 NewRHS = BO->getOperand(0);
Dan Gohman534ba372010-04-24 03:13:44 +00002046 if (!NewRHS)
2047 return Cond;
2048 } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
Dan Gohman045f8192010-01-22 00:46:49 +00002049 NewRHS = Sel->getOperand(1);
Dan Gohman45774ce2010-02-12 10:34:29 +00002050 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
Dan Gohman045f8192010-01-22 00:46:49 +00002051 NewRHS = Sel->getOperand(2);
Dan Gohman1081f1a2010-06-22 23:07:13 +00002052 else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
2053 NewRHS = SU->getValue();
Dan Gohman534ba372010-04-24 03:13:44 +00002054 else
Dan Gohman1081f1a2010-06-22 23:07:13 +00002055 // Max doesn't match expected pattern.
2056 return Cond;
Dan Gohman045f8192010-01-22 00:46:49 +00002057
2058 // Determine the new comparison opcode. It may be signed or unsigned,
2059 // and the original comparison may be either equality or inequality.
Dan Gohman045f8192010-01-22 00:46:49 +00002060 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
2061 Pred = CmpInst::getInversePredicate(Pred);
2062
2063 // Ok, everything looks ok to change the condition into an SLT or SGE and
2064 // delete the max calculation.
2065 ICmpInst *NewCond =
2066 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
2067
2068 // Delete the max calculation instructions.
2069 Cond->replaceAllUsesWith(NewCond);
2070 CondUse->setUser(NewCond);
2071 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
2072 Cond->eraseFromParent();
2073 Sel->eraseFromParent();
2074 if (Cmp->use_empty())
2075 Cmp->eraseFromParent();
2076 return NewCond;
Dan Gohman68e77352008-09-15 21:22:06 +00002077}
2078
Jim Grosbach60f48542009-11-17 17:53:56 +00002079/// OptimizeLoopTermCond - Change loop terminating condition to use the
Evan Cheng85a9f432009-11-12 07:35:05 +00002080/// postinc iv when possible.
Dan Gohman4c4043c2010-05-20 20:05:31 +00002081void
Dan Gohman45774ce2010-02-12 10:34:29 +00002082LSRInstance::OptimizeLoopTermCond() {
2083 SmallPtrSet<Instruction *, 4> PostIncs;
2084
Evan Cheng85a9f432009-11-12 07:35:05 +00002085 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Chengba4e5da72009-11-17 18:10:11 +00002086 SmallVector<BasicBlock*, 8> ExitingBlocks;
2087 L->getExitingBlocks(ExitingBlocks);
Jim Grosbach60f48542009-11-17 17:53:56 +00002088
Craig Topper042a3922015-05-25 20:01:18 +00002089 for (BasicBlock *ExitingBlock : ExitingBlocks) {
Evan Cheng85a9f432009-11-12 07:35:05 +00002090
Dan Gohman45774ce2010-02-12 10:34:29 +00002091 // Get the terminating condition for the loop if possible. If we
Evan Chengba4e5da72009-11-17 18:10:11 +00002092 // can, we want to change it to use a post-incremented version of its
2093 // induction variable, to allow coalescing the live ranges for the IV into
2094 // one register value.
Evan Cheng85a9f432009-11-12 07:35:05 +00002095
Evan Chengba4e5da72009-11-17 18:10:11 +00002096 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2097 if (!TermBr)
2098 continue;
2099 // FIXME: Overly conservative, termination condition could be an 'or' etc..
2100 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
2101 continue;
Evan Cheng85a9f432009-11-12 07:35:05 +00002102
Evan Chengba4e5da72009-11-17 18:10:11 +00002103 // Search IVUsesByStride to find Cond's IVUse if there is one.
Craig Topperf40110f2014-04-25 05:29:35 +00002104 IVStrideUse *CondUse = nullptr;
Evan Chengba4e5da72009-11-17 18:10:11 +00002105 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Dan Gohman45774ce2010-02-12 10:34:29 +00002106 if (!FindIVUserForCond(Cond, CondUse))
Evan Chengba4e5da72009-11-17 18:10:11 +00002107 continue;
2108
Evan Chengba4e5da72009-11-17 18:10:11 +00002109 // If the trip count is computed in terms of a max (due to ScalarEvolution
2110 // being unable to find a sufficient guard, for example), change the loop
2111 // comparison to use SLT or ULT instead of NE.
Dan Gohman45774ce2010-02-12 10:34:29 +00002112 // One consequence of doing this now is that it disrupts the count-down
2113 // optimization. That's not always a bad thing though, because in such
2114 // cases it may still be worthwhile to avoid a max.
2115 Cond = OptimizeMax(Cond, CondUse);
Evan Chengba4e5da72009-11-17 18:10:11 +00002116
Dan Gohman45774ce2010-02-12 10:34:29 +00002117 // If this exiting block dominates the latch block, it may also use
2118 // the post-inc value if it won't be shared with other uses.
2119 // Check for dominance.
2120 if (!DT.dominates(ExitingBlock, LatchBlock))
Dan Gohman045f8192010-01-22 00:46:49 +00002121 continue;
Evan Chengba4e5da72009-11-17 18:10:11 +00002122
Dan Gohman45774ce2010-02-12 10:34:29 +00002123 // Conservatively avoid trying to use the post-inc value in non-latch
2124 // exits if there may be pre-inc users in intervening blocks.
Dan Gohman2d0f96d2010-02-14 03:21:49 +00002125 if (LatchBlock != ExitingBlock)
Dan Gohman45774ce2010-02-12 10:34:29 +00002126 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
2127 // Test if the use is reachable from the exiting block. This dominator
2128 // query is a conservative approximation of reachability.
2129 if (&*UI != CondUse &&
2130 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
2131 // Conservatively assume there may be reuse if the quotient of their
2132 // strides could be a legal scale.
Dan Gohmane637ff52010-04-19 21:48:58 +00002133 const SCEV *A = IU.getStride(*CondUse, L);
2134 const SCEV *B = IU.getStride(*UI, L);
Dan Gohmand006ab92010-04-07 22:27:08 +00002135 if (!A || !B) continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00002136 if (SE.getTypeSizeInBits(A->getType()) !=
2137 SE.getTypeSizeInBits(B->getType())) {
2138 if (SE.getTypeSizeInBits(A->getType()) >
2139 SE.getTypeSizeInBits(B->getType()))
2140 B = SE.getSignExtendExpr(B, A->getType());
2141 else
2142 A = SE.getSignExtendExpr(A, B->getType());
2143 }
2144 if (const SCEVConstant *D =
Dan Gohman4eebb942010-02-19 19:35:48 +00002145 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
Dan Gohman86110fa2010-05-20 22:25:20 +00002146 const ConstantInt *C = D->getValue();
Dan Gohman45774ce2010-02-12 10:34:29 +00002147 // Stride of one or negative one can have reuse with non-addresses.
Dan Gohman86110fa2010-05-20 22:25:20 +00002148 if (C->isOne() || C->isAllOnesValue())
Dan Gohman45774ce2010-02-12 10:34:29 +00002149 goto decline_post_inc;
2150 // Avoid weird situations.
Dan Gohman86110fa2010-05-20 22:25:20 +00002151 if (C->getValue().getMinSignedBits() >= 64 ||
2152 C->getValue().isMinSignedValue())
Dan Gohman45774ce2010-02-12 10:34:29 +00002153 goto decline_post_inc;
2154 // Check for possible scaled-address reuse.
Chris Lattner229907c2011-07-18 04:54:35 +00002155 Type *AccessTy = getAccessType(UI->getUser());
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002156 int64_t Scale = C->getSExtValue();
Craig Topperf40110f2014-04-25 05:29:35 +00002157 if (TTI.isLegalAddressingMode(AccessTy, /*BaseGV=*/ nullptr,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002158 /*BaseOffset=*/ 0,
2159 /*HasBaseReg=*/ false, Scale))
Dan Gohman45774ce2010-02-12 10:34:29 +00002160 goto decline_post_inc;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002161 Scale = -Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00002162 if (TTI.isLegalAddressingMode(AccessTy, /*BaseGV=*/ nullptr,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002163 /*BaseOffset=*/ 0,
2164 /*HasBaseReg=*/ false, Scale))
Dan Gohman45774ce2010-02-12 10:34:29 +00002165 goto decline_post_inc;
2166 }
2167 }
2168
David Greene2330f782009-12-23 22:58:38 +00002169 DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
Dan Gohman45774ce2010-02-12 10:34:29 +00002170 << *Cond << '\n');
Evan Chengba4e5da72009-11-17 18:10:11 +00002171
2172 // It's possible for the setcc instruction to be anywhere in the loop, and
2173 // possible for it to have multiple users. If it is not immediately before
2174 // the exiting block branch, move it.
Dan Gohman45774ce2010-02-12 10:34:29 +00002175 if (&*++BasicBlock::iterator(Cond) != TermBr) {
2176 if (Cond->hasOneUse()) {
Evan Chengba4e5da72009-11-17 18:10:11 +00002177 Cond->moveBefore(TermBr);
2178 } else {
Dan Gohman45774ce2010-02-12 10:34:29 +00002179 // Clone the terminating condition and insert into the loopend.
2180 ICmpInst *OldCond = Cond;
Evan Chengba4e5da72009-11-17 18:10:11 +00002181 Cond = cast<ICmpInst>(Cond->clone());
2182 Cond->setName(L->getHeader()->getName() + ".termcond");
2183 ExitingBlock->getInstList().insert(TermBr, Cond);
2184
2185 // Clone the IVUse, as the old use still exists!
Andrew Trickfc4ccb22011-06-21 15:43:52 +00002186 CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
Dan Gohman45774ce2010-02-12 10:34:29 +00002187 TermBr->replaceUsesOfWith(OldCond, Cond);
Evan Chengba4e5da72009-11-17 18:10:11 +00002188 }
Evan Cheng85a9f432009-11-12 07:35:05 +00002189 }
2190
Evan Chengba4e5da72009-11-17 18:10:11 +00002191 // If we get to here, we know that we can transform the setcc instruction to
2192 // use the post-incremented version of the IV, allowing us to coalesce the
2193 // live ranges for the IV correctly.
Dan Gohmand006ab92010-04-07 22:27:08 +00002194 CondUse->transformToPostInc(L);
Evan Chengba4e5da72009-11-17 18:10:11 +00002195 Changed = true;
2196
Dan Gohman45774ce2010-02-12 10:34:29 +00002197 PostIncs.insert(Cond);
2198 decline_post_inc:;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002199 }
Dan Gohman45774ce2010-02-12 10:34:29 +00002200
2201 // Determine an insertion point for the loop induction variable increment. It
2202 // must dominate all the post-inc comparisons we just set up, and it must
2203 // dominate the loop latch edge.
2204 IVIncInsertPos = L->getLoopLatch()->getTerminator();
Craig Topper46276792014-08-24 23:23:06 +00002205 for (Instruction *Inst : PostIncs) {
Dan Gohman45774ce2010-02-12 10:34:29 +00002206 BasicBlock *BB =
2207 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
Craig Topper46276792014-08-24 23:23:06 +00002208 Inst->getParent());
2209 if (BB == Inst->getParent())
2210 IVIncInsertPos = Inst;
Dan Gohman45774ce2010-02-12 10:34:29 +00002211 else if (BB != IVIncInsertPos->getParent())
2212 IVIncInsertPos = BB->getTerminator();
2213 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00002214}
2215
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002216/// reconcileNewOffset - Determine if the given use can accommodate a fixup
Dan Gohmana4ca28a2010-05-20 20:52:00 +00002217/// at the given offset and other details. If so, update the use and
2218/// return true.
Dan Gohman45774ce2010-02-12 10:34:29 +00002219bool
Dan Gohman110ed642010-09-01 01:45:53 +00002220LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
Chris Lattner229907c2011-07-18 04:54:35 +00002221 LSRUse::KindType Kind, Type *AccessTy) {
Dan Gohman110ed642010-09-01 01:45:53 +00002222 int64_t NewMinOffset = LU.MinOffset;
2223 int64_t NewMaxOffset = LU.MaxOffset;
Chris Lattner229907c2011-07-18 04:54:35 +00002224 Type *NewAccessTy = AccessTy;
Dan Gohman045f8192010-01-22 00:46:49 +00002225
Dan Gohman45774ce2010-02-12 10:34:29 +00002226 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
2227 // something conservative, however this can pessimize in the case that one of
2228 // the uses will have all its uses outside the loop, for example.
2229 if (LU.Kind != Kind)
Dan Gohman045f8192010-01-22 00:46:49 +00002230 return false;
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00002231
Dan Gohman45774ce2010-02-12 10:34:29 +00002232 // Check for a mismatched access type, and fall back conservatively as needed.
Dan Gohman32655902010-06-19 21:30:18 +00002233 // TODO: Be less conservative when the type is similar and can use the same
2234 // addressing modes.
Dan Gohman45774ce2010-02-12 10:34:29 +00002235 if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
Dan Gohman110ed642010-09-01 01:45:53 +00002236 NewAccessTy = Type::getVoidTy(AccessTy->getContext());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002237
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00002238 // Conservatively assume HasBaseReg is true for now.
2239 if (NewOffset < LU.MinOffset) {
2240 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
2241 LU.MaxOffset - NewOffset, HasBaseReg))
2242 return false;
2243 NewMinOffset = NewOffset;
2244 } else if (NewOffset > LU.MaxOffset) {
2245 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
2246 NewOffset - LU.MinOffset, HasBaseReg))
2247 return false;
2248 NewMaxOffset = NewOffset;
2249 }
2250
Dan Gohman45774ce2010-02-12 10:34:29 +00002251 // Update the use.
Dan Gohman110ed642010-09-01 01:45:53 +00002252 LU.MinOffset = NewMinOffset;
2253 LU.MaxOffset = NewMaxOffset;
2254 LU.AccessTy = NewAccessTy;
2255 if (NewOffset != LU.Offsets.back())
2256 LU.Offsets.push_back(NewOffset);
Dan Gohman29916e02010-01-21 22:42:49 +00002257 return true;
2258}
2259
Dan Gohman45774ce2010-02-12 10:34:29 +00002260/// getUse - Return an LSRUse index and an offset value for a fixup which
2261/// needs the given expression, with the given kind and optional access type.
Dan Gohman8b0a4192010-03-01 17:49:51 +00002262/// Either reuse an existing use or create a new one, as needed.
Dan Gohman45774ce2010-02-12 10:34:29 +00002263std::pair<size_t, int64_t>
2264LSRInstance::getUse(const SCEV *&Expr,
Chris Lattner229907c2011-07-18 04:54:35 +00002265 LSRUse::KindType Kind, Type *AccessTy) {
Dan Gohman45774ce2010-02-12 10:34:29 +00002266 const SCEV *Copy = Expr;
2267 int64_t Offset = ExtractImmediate(Expr, SE);
Evan Cheng85a9f432009-11-12 07:35:05 +00002268
Dan Gohman45774ce2010-02-12 10:34:29 +00002269 // Basic uses can't accept any offset, for example.
Craig Topperf40110f2014-04-25 05:29:35 +00002270 if (!isAlwaysFoldable(TTI, Kind, AccessTy, /*BaseGV=*/ nullptr,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002271 Offset, /*HasBaseReg=*/ true)) {
Dan Gohman45774ce2010-02-12 10:34:29 +00002272 Expr = Copy;
2273 Offset = 0;
2274 }
2275
2276 std::pair<UseMapTy::iterator, bool> P =
Benjamin Kramer62fb0cf2014-03-15 17:17:48 +00002277 UseMap.insert(std::make_pair(LSRUse::SCEVUseKindPair(Expr, Kind), 0));
Dan Gohman45774ce2010-02-12 10:34:29 +00002278 if (!P.second) {
2279 // A use already existed with this base.
2280 size_t LUIdx = P.first->second;
2281 LSRUse &LU = Uses[LUIdx];
Dan Gohman110ed642010-09-01 01:45:53 +00002282 if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))
Dan Gohman45774ce2010-02-12 10:34:29 +00002283 // Reuse this use.
2284 return std::make_pair(LUIdx, Offset);
2285 }
2286
2287 // Create a new use.
2288 size_t LUIdx = Uses.size();
2289 P.first->second = LUIdx;
2290 Uses.push_back(LSRUse(Kind, AccessTy));
2291 LSRUse &LU = Uses[LUIdx];
2292
Dan Gohman110ed642010-09-01 01:45:53 +00002293 // We don't need to track redundant offsets, but we don't need to go out
2294 // of our way here to avoid them.
2295 if (LU.Offsets.empty() || Offset != LU.Offsets.back())
2296 LU.Offsets.push_back(Offset);
2297
Dan Gohman45774ce2010-02-12 10:34:29 +00002298 LU.MinOffset = Offset;
2299 LU.MaxOffset = Offset;
2300 return std::make_pair(LUIdx, Offset);
2301}
2302
Dan Gohman80a96082010-05-20 15:17:54 +00002303/// DeleteUse - Delete the given use from the Uses list.
Dan Gohmana7b68d62010-10-07 23:33:43 +00002304void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) {
Dan Gohman110ed642010-09-01 01:45:53 +00002305 if (&LU != &Uses.back())
Dan Gohman80a96082010-05-20 15:17:54 +00002306 std::swap(LU, Uses.back());
2307 Uses.pop_back();
Dan Gohmana7b68d62010-10-07 23:33:43 +00002308
2309 // Update RegUses.
2310 RegUses.SwapAndDropUse(LUIdx, Uses.size());
Dan Gohman80a96082010-05-20 15:17:54 +00002311}
2312
Dan Gohman20fab452010-05-19 23:43:12 +00002313/// FindUseWithFormula - Look for a use distinct from OrigLU which is has
2314/// a formula that has the same registers as the given formula.
2315LSRUse *
2316LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
Dan Gohman110ed642010-09-01 01:45:53 +00002317 const LSRUse &OrigLU) {
2318 // Search all uses for the formula. This could be more clever.
Dan Gohman20fab452010-05-19 23:43:12 +00002319 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2320 LSRUse &LU = Uses[LUIdx];
Dan Gohmanb6a520d2010-08-29 15:27:08 +00002321 // Check whether this use is close enough to OrigLU, to see whether it's
2322 // worthwhile looking through its formulae.
2323 // Ignore ICmpZero uses because they may contain formulae generated by
2324 // GenerateICmpZeroScales, in which case adding fixup offsets may
2325 // be invalid.
Dan Gohman20fab452010-05-19 23:43:12 +00002326 if (&LU != &OrigLU &&
2327 LU.Kind != LSRUse::ICmpZero &&
2328 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
Dan Gohman14152082010-07-15 20:24:58 +00002329 LU.WidestFixupType == OrigLU.WidestFixupType &&
Dan Gohman20fab452010-05-19 23:43:12 +00002330 LU.HasFormulaWithSameRegs(OrigF)) {
Dan Gohmanb6a520d2010-08-29 15:27:08 +00002331 // Scan through this use's formulae.
Craig Topper042a3922015-05-25 20:01:18 +00002332 for (const Formula &F : LU.Formulae) {
Dan Gohmanb6a520d2010-08-29 15:27:08 +00002333 // Check to see if this formula has the same registers and symbols
2334 // as OrigF.
Dan Gohman20fab452010-05-19 23:43:12 +00002335 if (F.BaseRegs == OrigF.BaseRegs &&
2336 F.ScaledReg == OrigF.ScaledReg &&
Chandler Carruth6e479322013-01-07 15:04:40 +00002337 F.BaseGV == OrigF.BaseGV &&
2338 F.Scale == OrigF.Scale &&
Dan Gohman6136e942011-05-03 00:46:49 +00002339 F.UnfoldedOffset == OrigF.UnfoldedOffset) {
Chandler Carruth6e479322013-01-07 15:04:40 +00002340 if (F.BaseOffset == 0)
Dan Gohman20fab452010-05-19 23:43:12 +00002341 return &LU;
Dan Gohmanb6a520d2010-08-29 15:27:08 +00002342 // This is the formula where all the registers and symbols matched;
2343 // there aren't going to be any others. Since we declined it, we
Benjamin Kramerbde91762012-06-02 10:20:22 +00002344 // can skip the rest of the formulae and proceed to the next LSRUse.
Dan Gohman20fab452010-05-19 23:43:12 +00002345 break;
2346 }
2347 }
2348 }
2349 }
2350
Dan Gohmanb6a520d2010-08-29 15:27:08 +00002351 // Nothing looked good.
Craig Topperf40110f2014-04-25 05:29:35 +00002352 return nullptr;
Dan Gohman20fab452010-05-19 23:43:12 +00002353}
2354
Dan Gohman45774ce2010-02-12 10:34:29 +00002355void LSRInstance::CollectInterestingTypesAndFactors() {
2356 SmallSetVector<const SCEV *, 4> Strides;
2357
Dan Gohman2446f572010-02-19 00:05:23 +00002358 // Collect interesting types and strides.
Dan Gohmand006ab92010-04-07 22:27:08 +00002359 SmallVector<const SCEV *, 4> Worklist;
Craig Topper042a3922015-05-25 20:01:18 +00002360 for (const IVStrideUse &U : IU) {
2361 const SCEV *Expr = IU.getExpr(U);
Dan Gohman45774ce2010-02-12 10:34:29 +00002362
2363 // Collect interesting types.
Dan Gohmand006ab92010-04-07 22:27:08 +00002364 Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
Dan Gohman45774ce2010-02-12 10:34:29 +00002365
Dan Gohmand006ab92010-04-07 22:27:08 +00002366 // Add strides for mentioned loops.
2367 Worklist.push_back(Expr);
2368 do {
2369 const SCEV *S = Worklist.pop_back_val();
2370 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
Andrew Trickd97b83e2012-03-22 22:42:45 +00002371 if (AR->getLoop() == L)
Andrew Tricke8b4f402011-12-10 00:25:00 +00002372 Strides.insert(AR->getStepRecurrence(SE));
Dan Gohmand006ab92010-04-07 22:27:08 +00002373 Worklist.push_back(AR->getStart());
2374 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00002375 Worklist.append(Add->op_begin(), Add->op_end());
Dan Gohmand006ab92010-04-07 22:27:08 +00002376 }
2377 } while (!Worklist.empty());
Dan Gohman2446f572010-02-19 00:05:23 +00002378 }
2379
2380 // Compute interesting factors from the set of interesting strides.
2381 for (SmallSetVector<const SCEV *, 4>::const_iterator
2382 I = Strides.begin(), E = Strides.end(); I != E; ++I)
Dan Gohman45774ce2010-02-12 10:34:29 +00002383 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002384 std::next(I); NewStrideIter != E; ++NewStrideIter) {
Dan Gohman2446f572010-02-19 00:05:23 +00002385 const SCEV *OldStride = *I;
Dan Gohman45774ce2010-02-12 10:34:29 +00002386 const SCEV *NewStride = *NewStrideIter;
Dan Gohman45774ce2010-02-12 10:34:29 +00002387
2388 if (SE.getTypeSizeInBits(OldStride->getType()) !=
2389 SE.getTypeSizeInBits(NewStride->getType())) {
2390 if (SE.getTypeSizeInBits(OldStride->getType()) >
2391 SE.getTypeSizeInBits(NewStride->getType()))
2392 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
2393 else
2394 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
2395 }
2396 if (const SCEVConstant *Factor =
Dan Gohman4eebb942010-02-19 19:35:48 +00002397 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
2398 SE, true))) {
Dan Gohman45774ce2010-02-12 10:34:29 +00002399 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
2400 Factors.insert(Factor->getValue()->getValue().getSExtValue());
2401 } else if (const SCEVConstant *Factor =
Dan Gohman8c16b382010-02-22 04:11:59 +00002402 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
2403 NewStride,
Dan Gohman4eebb942010-02-19 19:35:48 +00002404 SE, true))) {
Dan Gohman45774ce2010-02-12 10:34:29 +00002405 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
2406 Factors.insert(Factor->getValue()->getValue().getSExtValue());
2407 }
2408 }
Dan Gohman45774ce2010-02-12 10:34:29 +00002409
2410 // If all uses use the same type, don't bother looking for truncation-based
2411 // reuse.
2412 if (Types.size() == 1)
2413 Types.clear();
2414
2415 DEBUG(print_factors_and_types(dbgs()));
2416}
2417
Andrew Trick29fe5f02012-01-09 19:50:34 +00002418/// findIVOperand - Helper for CollectChains that finds an IV operand (computed
2419/// by an AddRec in this loop) within [OI,OE) or returns OE. If IVUsers mapped
2420/// Instructions to IVStrideUses, we could partially skip this.
2421static User::op_iterator
2422findIVOperand(User::op_iterator OI, User::op_iterator OE,
2423 Loop *L, ScalarEvolution &SE) {
2424 for(; OI != OE; ++OI) {
2425 if (Instruction *Oper = dyn_cast<Instruction>(*OI)) {
2426 if (!SE.isSCEVable(Oper->getType()))
2427 continue;
2428
2429 if (const SCEVAddRecExpr *AR =
2430 dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Oper))) {
2431 if (AR->getLoop() == L)
2432 break;
2433 }
2434 }
2435 }
2436 return OI;
2437}
2438
2439/// getWideOperand - IVChain logic must consistenctly peek base TruncInst
2440/// operands, so wrap it in a convenient helper.
2441static Value *getWideOperand(Value *Oper) {
2442 if (TruncInst *Trunc = dyn_cast<TruncInst>(Oper))
2443 return Trunc->getOperand(0);
2444 return Oper;
2445}
2446
2447/// isCompatibleIVType - Return true if we allow an IV chain to include both
2448/// types.
2449static bool isCompatibleIVType(Value *LVal, Value *RVal) {
2450 Type *LType = LVal->getType();
2451 Type *RType = RVal->getType();
2452 return (LType == RType) || (LType->isPointerTy() && RType->isPointerTy());
2453}
2454
Andrew Trickd5d2db92012-01-10 01:45:08 +00002455/// getExprBase - Return an approximation of this SCEV expression's "base", or
2456/// NULL for any constant. Returning the expression itself is
2457/// conservative. Returning a deeper subexpression is more precise and valid as
2458/// long as it isn't less complex than another subexpression. For expressions
2459/// involving multiple unscaled values, we need to return the pointer-type
2460/// SCEVUnknown. This avoids forming chains across objects, such as:
2461/// PrevOper==a[i], IVOper==b[i], IVInc==b-a.
2462///
2463/// Since SCEVUnknown is the rightmost type, and pointers are the rightmost
2464/// SCEVUnknown, we simply return the rightmost SCEV operand.
2465static const SCEV *getExprBase(const SCEV *S) {
2466 switch (S->getSCEVType()) {
2467 default: // uncluding scUnknown.
2468 return S;
2469 case scConstant:
Craig Topperf40110f2014-04-25 05:29:35 +00002470 return nullptr;
Andrew Trickd5d2db92012-01-10 01:45:08 +00002471 case scTruncate:
2472 return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand());
2473 case scZeroExtend:
2474 return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand());
2475 case scSignExtend:
2476 return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand());
2477 case scAddExpr: {
2478 // Skip over scaled operands (scMulExpr) to follow add operands as long as
2479 // there's nothing more complex.
2480 // FIXME: not sure if we want to recognize negation.
2481 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
2482 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(Add->op_end()),
2483 E(Add->op_begin()); I != E; ++I) {
2484 const SCEV *SubExpr = *I;
2485 if (SubExpr->getSCEVType() == scAddExpr)
2486 return getExprBase(SubExpr);
2487
2488 if (SubExpr->getSCEVType() != scMulExpr)
2489 return SubExpr;
2490 }
2491 return S; // all operands are scaled, be conservative.
2492 }
2493 case scAddRecExpr:
2494 return getExprBase(cast<SCEVAddRecExpr>(S)->getStart());
2495 }
2496}
2497
Andrew Trick248d4102012-01-09 21:18:52 +00002498/// Return true if the chain increment is profitable to expand into a loop
2499/// invariant value, which may require its own register. A profitable chain
2500/// increment will be an offset relative to the same base. We allow such offsets
2501/// to potentially be used as chain increment as long as it's not obviously
2502/// expensive to expand using real instructions.
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002503bool IVChain::isProfitableIncrement(const SCEV *OperExpr,
2504 const SCEV *IncExpr,
2505 ScalarEvolution &SE) {
2506 // Aggressively form chains when -stress-ivchain.
Andrew Trick248d4102012-01-09 21:18:52 +00002507 if (StressIVChain)
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002508 return true;
Andrew Trick248d4102012-01-09 21:18:52 +00002509
Andrew Trickd5d2db92012-01-10 01:45:08 +00002510 // Do not replace a constant offset from IV head with a nonconstant IV
2511 // increment.
2512 if (!isa<SCEVConstant>(IncExpr)) {
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002513 const SCEV *HeadExpr = SE.getSCEV(getWideOperand(Incs[0].IVOperand));
Andrew Trickd5d2db92012-01-10 01:45:08 +00002514 if (isa<SCEVConstant>(SE.getMinusSCEV(OperExpr, HeadExpr)))
2515 return 0;
2516 }
2517
2518 SmallPtrSet<const SCEV*, 8> Processed;
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002519 return !isHighCostExpansion(IncExpr, Processed, SE);
Andrew Trick248d4102012-01-09 21:18:52 +00002520}
2521
2522/// Return true if the number of registers needed for the chain is estimated to
2523/// be less than the number required for the individual IV users. First prohibit
2524/// any IV users that keep the IV live across increments (the Users set should
2525/// be empty). Next count the number and type of increments in the chain.
2526///
2527/// Chaining IVs can lead to considerable code bloat if ISEL doesn't
2528/// effectively use postinc addressing modes. Only consider it profitable it the
2529/// increments can be computed in fewer registers when chained.
2530///
2531/// TODO: Consider IVInc free if it's already used in another chains.
2532static bool
Craig Topper71b7b682014-08-21 05:55:13 +00002533isProfitableChain(IVChain &Chain, SmallPtrSetImpl<Instruction*> &Users,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002534 ScalarEvolution &SE, const TargetTransformInfo &TTI) {
Andrew Trick248d4102012-01-09 21:18:52 +00002535 if (StressIVChain)
2536 return true;
2537
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002538 if (!Chain.hasIncs())
Andrew Trickd5d2db92012-01-10 01:45:08 +00002539 return false;
2540
2541 if (!Users.empty()) {
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002542 DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " users:\n";
Craig Topper46276792014-08-24 23:23:06 +00002543 for (Instruction *Inst : Users) {
2544 dbgs() << " " << *Inst << "\n";
Andrew Trickd5d2db92012-01-10 01:45:08 +00002545 });
2546 return false;
2547 }
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002548 assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
Andrew Trickd5d2db92012-01-10 01:45:08 +00002549
2550 // The chain itself may require a register, so intialize cost to 1.
2551 int cost = 1;
2552
2553 // A complete chain likely eliminates the need for keeping the original IV in
2554 // a register. LSR does not currently know how to form a complete chain unless
2555 // the header phi already exists.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002556 if (isa<PHINode>(Chain.tailUserInst())
2557 && SE.getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) {
Andrew Trickd5d2db92012-01-10 01:45:08 +00002558 --cost;
2559 }
Craig Topperf40110f2014-04-25 05:29:35 +00002560 const SCEV *LastIncExpr = nullptr;
Andrew Trickd5d2db92012-01-10 01:45:08 +00002561 unsigned NumConstIncrements = 0;
2562 unsigned NumVarIncrements = 0;
2563 unsigned NumReusedIncrements = 0;
Craig Topper042a3922015-05-25 20:01:18 +00002564 for (const IVInc &Inc : Chain) {
2565 if (Inc.IncExpr->isZero())
Andrew Trickd5d2db92012-01-10 01:45:08 +00002566 continue;
2567
2568 // Incrementing by zero or some constant is neutral. We assume constants can
2569 // be folded into an addressing mode or an add's immediate operand.
Craig Topper042a3922015-05-25 20:01:18 +00002570 if (isa<SCEVConstant>(Inc.IncExpr)) {
Andrew Trickd5d2db92012-01-10 01:45:08 +00002571 ++NumConstIncrements;
2572 continue;
2573 }
2574
Craig Topper042a3922015-05-25 20:01:18 +00002575 if (Inc.IncExpr == LastIncExpr)
Andrew Trickd5d2db92012-01-10 01:45:08 +00002576 ++NumReusedIncrements;
2577 else
2578 ++NumVarIncrements;
2579
Craig Topper042a3922015-05-25 20:01:18 +00002580 LastIncExpr = Inc.IncExpr;
Andrew Trickd5d2db92012-01-10 01:45:08 +00002581 }
2582 // An IV chain with a single increment is handled by LSR's postinc
2583 // uses. However, a chain with multiple increments requires keeping the IV's
2584 // value live longer than it needs to be if chained.
2585 if (NumConstIncrements > 1)
2586 --cost;
2587
2588 // Materializing increment expressions in the preheader that didn't exist in
2589 // the original code may cost a register. For example, sign-extended array
2590 // indices can produce ridiculous increments like this:
2591 // IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64)))
2592 cost += NumVarIncrements;
2593
2594 // Reusing variable increments likely saves a register to hold the multiple of
2595 // the stride.
2596 cost -= NumReusedIncrements;
2597
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002598 DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " Cost: " << cost
2599 << "\n");
Andrew Trickd5d2db92012-01-10 01:45:08 +00002600
2601 return cost < 0;
Andrew Trick248d4102012-01-09 21:18:52 +00002602}
2603
Andrew Trick29fe5f02012-01-09 19:50:34 +00002604/// ChainInstruction - Add this IV user to an existing chain or make it the head
2605/// of a new chain.
2606void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVOper,
2607 SmallVectorImpl<ChainUsers> &ChainUsersVec) {
2608 // When IVs are used as types of varying widths, they are generally converted
2609 // to a wider type with some uses remaining narrow under a (free) trunc.
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002610 Value *const NextIV = getWideOperand(IVOper);
2611 const SCEV *const OperExpr = SE.getSCEV(NextIV);
2612 const SCEV *const OperExprBase = getExprBase(OperExpr);
Andrew Trick29fe5f02012-01-09 19:50:34 +00002613
2614 // Visit all existing chains. Check if its IVOper can be computed as a
2615 // profitable loop invariant increment from the last link in the Chain.
2616 unsigned ChainIdx = 0, NChains = IVChainVec.size();
Craig Topperf40110f2014-04-25 05:29:35 +00002617 const SCEV *LastIncExpr = nullptr;
Andrew Trick29fe5f02012-01-09 19:50:34 +00002618 for (; ChainIdx < NChains; ++ChainIdx) {
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002619 IVChain &Chain = IVChainVec[ChainIdx];
2620
2621 // Prune the solution space aggressively by checking that both IV operands
2622 // are expressions that operate on the same unscaled SCEVUnknown. This
2623 // "base" will be canceled by the subsequent getMinusSCEV call. Checking
2624 // first avoids creating extra SCEV expressions.
2625 if (!StressIVChain && Chain.ExprBase != OperExprBase)
2626 continue;
2627
2628 Value *PrevIV = getWideOperand(Chain.Incs.back().IVOperand);
Andrew Trick29fe5f02012-01-09 19:50:34 +00002629 if (!isCompatibleIVType(PrevIV, NextIV))
2630 continue;
2631
Andrew Trick356a8962012-03-26 20:28:35 +00002632 // A phi node terminates a chain.
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002633 if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst()))
Andrew Trick29fe5f02012-01-09 19:50:34 +00002634 continue;
2635
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002636 // The increment must be loop-invariant so it can be kept in a register.
2637 const SCEV *PrevExpr = SE.getSCEV(PrevIV);
2638 const SCEV *IncExpr = SE.getMinusSCEV(OperExpr, PrevExpr);
2639 if (!SE.isLoopInvariant(IncExpr, L))
2640 continue;
2641
2642 if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) {
Andrew Trick29fe5f02012-01-09 19:50:34 +00002643 LastIncExpr = IncExpr;
2644 break;
2645 }
2646 }
2647 // If we haven't found a chain, create a new one, unless we hit the max. Don't
2648 // bother for phi nodes, because they must be last in the chain.
2649 if (ChainIdx == NChains) {
2650 if (isa<PHINode>(UserInst))
2651 return;
Andrew Trick248d4102012-01-09 21:18:52 +00002652 if (NChains >= MaxChains && !StressIVChain) {
Andrew Trick29fe5f02012-01-09 19:50:34 +00002653 DEBUG(dbgs() << "IV Chain Limit\n");
2654 return;
2655 }
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002656 LastIncExpr = OperExpr;
Andrew Trickb9c822a2012-01-20 21:23:40 +00002657 // IVUsers may have skipped over sign/zero extensions. We don't currently
2658 // attempt to form chains involving extensions unless they can be hoisted
2659 // into this loop's AddRec.
2660 if (!isa<SCEVAddRecExpr>(LastIncExpr))
2661 return;
Andrew Trick29fe5f02012-01-09 19:50:34 +00002662 ++NChains;
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002663 IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr),
2664 OperExprBase));
Andrew Trick29fe5f02012-01-09 19:50:34 +00002665 ChainUsersVec.resize(NChains);
Jakob Stoklund Olesen293673d2012-04-25 18:01:32 +00002666 DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInst
2667 << ") IV=" << *LastIncExpr << "\n");
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002668 } else {
Jakob Stoklund Olesen293673d2012-04-25 18:01:32 +00002669 DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Inc: (" << *UserInst
2670 << ") IV+" << *LastIncExpr << "\n");
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002671 // Add this IV user to the end of the chain.
2672 IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr));
2673 }
Andrew Trickbc705902013-02-09 01:11:01 +00002674 IVChain &Chain = IVChainVec[ChainIdx];
Andrew Trick29fe5f02012-01-09 19:50:34 +00002675
2676 SmallPtrSet<Instruction*,4> &NearUsers = ChainUsersVec[ChainIdx].NearUsers;
2677 // This chain's NearUsers become FarUsers.
2678 if (!LastIncExpr->isZero()) {
2679 ChainUsersVec[ChainIdx].FarUsers.insert(NearUsers.begin(),
2680 NearUsers.end());
2681 NearUsers.clear();
2682 }
2683
2684 // All other uses of IVOperand become near uses of the chain.
2685 // We currently ignore intermediate values within SCEV expressions, assuming
2686 // they will eventually be used be the current chain, or can be computed
2687 // from one of the chain increments. To be more precise we could
2688 // transitively follow its user and only add leaf IV users to the set.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002689 for (User *U : IVOper->users()) {
2690 Instruction *OtherUse = dyn_cast<Instruction>(U);
Andrew Trickbc705902013-02-09 01:11:01 +00002691 if (!OtherUse)
Andrew Tricke51feea2012-03-26 18:03:16 +00002692 continue;
Andrew Trickbc705902013-02-09 01:11:01 +00002693 // Uses in the chain will no longer be uses if the chain is formed.
2694 // Include the head of the chain in this iteration (not Chain.begin()).
2695 IVChain::const_iterator IncIter = Chain.Incs.begin();
2696 IVChain::const_iterator IncEnd = Chain.Incs.end();
2697 for( ; IncIter != IncEnd; ++IncIter) {
2698 if (IncIter->UserInst == OtherUse)
2699 break;
2700 }
2701 if (IncIter != IncEnd)
2702 continue;
2703
Andrew Trick29fe5f02012-01-09 19:50:34 +00002704 if (SE.isSCEVable(OtherUse->getType())
2705 && !isa<SCEVUnknown>(SE.getSCEV(OtherUse))
2706 && IU.isIVUserOrOperand(OtherUse)) {
2707 continue;
2708 }
Andrew Tricke51feea2012-03-26 18:03:16 +00002709 NearUsers.insert(OtherUse);
Andrew Trick29fe5f02012-01-09 19:50:34 +00002710 }
2711
2712 // Since this user is part of the chain, it's no longer considered a use
2713 // of the chain.
2714 ChainUsersVec[ChainIdx].FarUsers.erase(UserInst);
2715}
2716
2717/// CollectChains - Populate the vector of Chains.
2718///
2719/// This decreases ILP at the architecture level. Targets with ample registers,
2720/// multiple memory ports, and no register renaming probably don't want
2721/// this. However, such targets should probably disable LSR altogether.
2722///
2723/// The job of LSR is to make a reasonable choice of induction variables across
2724/// the loop. Subsequent passes can easily "unchain" computation exposing more
2725/// ILP *within the loop* if the target wants it.
2726///
2727/// Finding the best IV chain is potentially a scheduling problem. Since LSR
2728/// will not reorder memory operations, it will recognize this as a chain, but
2729/// will generate redundant IV increments. Ideally this would be corrected later
2730/// by a smart scheduler:
2731/// = A[i]
2732/// = A[i+x]
2733/// A[i] =
2734/// A[i+x] =
2735///
2736/// TODO: Walk the entire domtree within this loop, not just the path to the
2737/// loop latch. This will discover chains on side paths, but requires
2738/// maintaining multiple copies of the Chains state.
2739void LSRInstance::CollectChains() {
Jakob Stoklund Olesen293673d2012-04-25 18:01:32 +00002740 DEBUG(dbgs() << "Collecting IV Chains.\n");
Andrew Trick29fe5f02012-01-09 19:50:34 +00002741 SmallVector<ChainUsers, 8> ChainUsersVec;
2742
2743 SmallVector<BasicBlock *,8> LatchPath;
2744 BasicBlock *LoopHeader = L->getHeader();
2745 for (DomTreeNode *Rung = DT.getNode(L->getLoopLatch());
2746 Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) {
2747 LatchPath.push_back(Rung->getBlock());
2748 }
2749 LatchPath.push_back(LoopHeader);
2750
2751 // Walk the instruction stream from the loop header to the loop latch.
2752 for (SmallVectorImpl<BasicBlock *>::reverse_iterator
2753 BBIter = LatchPath.rbegin(), BBEnd = LatchPath.rend();
2754 BBIter != BBEnd; ++BBIter) {
2755 for (BasicBlock::iterator I = (*BBIter)->begin(), E = (*BBIter)->end();
2756 I != E; ++I) {
2757 // Skip instructions that weren't seen by IVUsers analysis.
2758 if (isa<PHINode>(I) || !IU.isIVUserOrOperand(I))
2759 continue;
2760
2761 // Ignore users that are part of a SCEV expression. This way we only
2762 // consider leaf IV Users. This effectively rediscovers a portion of
2763 // IVUsers analysis but in program order this time.
2764 if (SE.isSCEVable(I->getType()) && !isa<SCEVUnknown>(SE.getSCEV(I)))
2765 continue;
2766
2767 // Remove this instruction from any NearUsers set it may be in.
2768 for (unsigned ChainIdx = 0, NChains = IVChainVec.size();
2769 ChainIdx < NChains; ++ChainIdx) {
2770 ChainUsersVec[ChainIdx].NearUsers.erase(I);
2771 }
2772 // Search for operands that can be chained.
2773 SmallPtrSet<Instruction*, 4> UniqueOperands;
2774 User::op_iterator IVOpEnd = I->op_end();
2775 User::op_iterator IVOpIter = findIVOperand(I->op_begin(), IVOpEnd, L, SE);
2776 while (IVOpIter != IVOpEnd) {
2777 Instruction *IVOpInst = cast<Instruction>(*IVOpIter);
David Blaikie70573dc2014-11-19 07:49:26 +00002778 if (UniqueOperands.insert(IVOpInst).second)
Andrew Trick29fe5f02012-01-09 19:50:34 +00002779 ChainInstruction(I, IVOpInst, ChainUsersVec);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002780 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
Andrew Trick29fe5f02012-01-09 19:50:34 +00002781 }
2782 } // Continue walking down the instructions.
2783 } // Continue walking down the domtree.
2784 // Visit phi backedges to determine if the chain can generate the IV postinc.
2785 for (BasicBlock::iterator I = L->getHeader()->begin();
2786 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2787 if (!SE.isSCEVable(PN->getType()))
2788 continue;
2789
2790 Instruction *IncV =
2791 dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
2792 if (IncV)
2793 ChainInstruction(PN, IncV, ChainUsersVec);
2794 }
Andrew Trick248d4102012-01-09 21:18:52 +00002795 // Remove any unprofitable chains.
2796 unsigned ChainIdx = 0;
2797 for (unsigned UsersIdx = 0, NChains = IVChainVec.size();
2798 UsersIdx < NChains; ++UsersIdx) {
2799 if (!isProfitableChain(IVChainVec[UsersIdx],
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002800 ChainUsersVec[UsersIdx].FarUsers, SE, TTI))
Andrew Trick248d4102012-01-09 21:18:52 +00002801 continue;
2802 // Preserve the chain at UsesIdx.
2803 if (ChainIdx != UsersIdx)
2804 IVChainVec[ChainIdx] = IVChainVec[UsersIdx];
2805 FinalizeChain(IVChainVec[ChainIdx]);
2806 ++ChainIdx;
2807 }
2808 IVChainVec.resize(ChainIdx);
2809}
2810
2811void LSRInstance::FinalizeChain(IVChain &Chain) {
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002812 assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
2813 DEBUG(dbgs() << "Final Chain: " << *Chain.Incs[0].UserInst << "\n");
Andrew Trick248d4102012-01-09 21:18:52 +00002814
Craig Topper042a3922015-05-25 20:01:18 +00002815 for (const IVInc &Inc : Chain) {
2816 DEBUG(dbgs() << " Inc: " << Inc.UserInst << "\n");
2817 auto UseI = std::find(Inc.UserInst->op_begin(), Inc.UserInst->op_end(),
2818 Inc.IVOperand);
2819 assert(UseI != Inc.UserInst->op_end() && "cannot find IV operand");
Andrew Trick248d4102012-01-09 21:18:52 +00002820 IVIncSet.insert(UseI);
2821 }
2822}
2823
2824/// Return true if the IVInc can be folded into an addressing mode.
2825static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002826 Value *Operand, const TargetTransformInfo &TTI) {
Andrew Trick248d4102012-01-09 21:18:52 +00002827 const SCEVConstant *IncConst = dyn_cast<SCEVConstant>(IncExpr);
2828 if (!IncConst || !isAddressUse(UserInst, Operand))
2829 return false;
2830
2831 if (IncConst->getValue()->getValue().getMinSignedBits() > 64)
2832 return false;
2833
2834 int64_t IncOffset = IncConst->getValue()->getSExtValue();
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002835 if (!isAlwaysFoldable(TTI, LSRUse::Address,
Craig Topperf40110f2014-04-25 05:29:35 +00002836 getAccessType(UserInst), /*BaseGV=*/ nullptr,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002837 IncOffset, /*HaseBaseReg=*/ false))
Andrew Trick248d4102012-01-09 21:18:52 +00002838 return false;
2839
2840 return true;
2841}
2842
2843/// GenerateIVChains - Generate an add or subtract for each IVInc in a chain to
2844/// materialize the IV user's operand from the previous IV user's operand.
2845void LSRInstance::GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
2846 SmallVectorImpl<WeakVH> &DeadInsts) {
2847 // Find the new IVOperand for the head of the chain. It may have been replaced
2848 // by LSR.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002849 const IVInc &Head = Chain.Incs[0];
Andrew Trick248d4102012-01-09 21:18:52 +00002850 User::op_iterator IVOpEnd = Head.UserInst->op_end();
Andrew Trickf3a25442013-03-19 05:10:27 +00002851 // findIVOperand returns IVOpEnd if it can no longer find a valid IV user.
Andrew Trick248d4102012-01-09 21:18:52 +00002852 User::op_iterator IVOpIter = findIVOperand(Head.UserInst->op_begin(),
2853 IVOpEnd, L, SE);
Craig Topperf40110f2014-04-25 05:29:35 +00002854 Value *IVSrc = nullptr;
Andrew Trickf3a25442013-03-19 05:10:27 +00002855 while (IVOpIter != IVOpEnd) {
Andrew Trick248d4102012-01-09 21:18:52 +00002856 IVSrc = getWideOperand(*IVOpIter);
2857
2858 // If this operand computes the expression that the chain needs, we may use
2859 // it. (Check this after setting IVSrc which is used below.)
2860 //
2861 // Note that if Head.IncExpr is wider than IVSrc, then this phi is too
2862 // narrow for the chain, so we can no longer use it. We do allow using a
2863 // wider phi, assuming the LSR checked for free truncation. In that case we
2864 // should already have a truncate on this operand such that
2865 // getSCEV(IVSrc) == IncExpr.
2866 if (SE.getSCEV(*IVOpIter) == Head.IncExpr
2867 || SE.getSCEV(IVSrc) == Head.IncExpr) {
2868 break;
2869 }
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002870 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
Andrew Trickf3a25442013-03-19 05:10:27 +00002871 }
Andrew Trick248d4102012-01-09 21:18:52 +00002872 if (IVOpIter == IVOpEnd) {
2873 // Gracefully give up on this chain.
2874 DEBUG(dbgs() << "Concealed chain head: " << *Head.UserInst << "\n");
2875 return;
2876 }
2877
2878 DEBUG(dbgs() << "Generate chain at: " << *IVSrc << "\n");
2879 Type *IVTy = IVSrc->getType();
2880 Type *IntTy = SE.getEffectiveSCEVType(IVTy);
Craig Topperf40110f2014-04-25 05:29:35 +00002881 const SCEV *LeftOverExpr = nullptr;
Craig Topper042a3922015-05-25 20:01:18 +00002882 for (const IVInc &Inc : Chain) {
2883 Instruction *InsertPt = Inc.UserInst;
Andrew Trick248d4102012-01-09 21:18:52 +00002884 if (isa<PHINode>(InsertPt))
2885 InsertPt = L->getLoopLatch()->getTerminator();
2886
2887 // IVOper will replace the current IV User's operand. IVSrc is the IV
2888 // value currently held in a register.
2889 Value *IVOper = IVSrc;
Craig Topper042a3922015-05-25 20:01:18 +00002890 if (!Inc.IncExpr->isZero()) {
Andrew Trick248d4102012-01-09 21:18:52 +00002891 // IncExpr was the result of subtraction of two narrow values, so must
2892 // be signed.
Craig Topper042a3922015-05-25 20:01:18 +00002893 const SCEV *IncExpr = SE.getNoopOrSignExtend(Inc.IncExpr, IntTy);
Andrew Trick248d4102012-01-09 21:18:52 +00002894 LeftOverExpr = LeftOverExpr ?
2895 SE.getAddExpr(LeftOverExpr, IncExpr) : IncExpr;
2896 }
2897 if (LeftOverExpr && !LeftOverExpr->isZero()) {
2898 // Expand the IV increment.
2899 Rewriter.clearPostInc();
2900 Value *IncV = Rewriter.expandCodeFor(LeftOverExpr, IntTy, InsertPt);
2901 const SCEV *IVOperExpr = SE.getAddExpr(SE.getUnknown(IVSrc),
2902 SE.getUnknown(IncV));
2903 IVOper = Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt);
2904
2905 // If an IV increment can't be folded, use it as the next IV value.
Craig Topper042a3922015-05-25 20:01:18 +00002906 if (!canFoldIVIncExpr(LeftOverExpr, Inc.UserInst, Inc.IVOperand, TTI)) {
Andrew Trick248d4102012-01-09 21:18:52 +00002907 assert(IVTy == IVOper->getType() && "inconsistent IV increment type");
2908 IVSrc = IVOper;
Craig Topperf40110f2014-04-25 05:29:35 +00002909 LeftOverExpr = nullptr;
Andrew Trick248d4102012-01-09 21:18:52 +00002910 }
2911 }
Craig Topper042a3922015-05-25 20:01:18 +00002912 Type *OperTy = Inc.IVOperand->getType();
Andrew Trick248d4102012-01-09 21:18:52 +00002913 if (IVTy != OperTy) {
2914 assert(SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) &&
2915 "cannot extend a chained IV");
2916 IRBuilder<> Builder(InsertPt);
2917 IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy, "lsr.chain");
2918 }
Craig Topper042a3922015-05-25 20:01:18 +00002919 Inc.UserInst->replaceUsesOfWith(Inc.IVOperand, IVOper);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002920 DeadInsts.emplace_back(Inc.IVOperand);
Andrew Trick248d4102012-01-09 21:18:52 +00002921 }
2922 // If LSR created a new, wider phi, we may also replace its postinc. We only
2923 // do this if we also found a wide value for the head of the chain.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002924 if (isa<PHINode>(Chain.tailUserInst())) {
Andrew Trick248d4102012-01-09 21:18:52 +00002925 for (BasicBlock::iterator I = L->getHeader()->begin();
2926 PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
2927 if (!isCompatibleIVType(Phi, IVSrc))
2928 continue;
2929 Instruction *PostIncV = dyn_cast<Instruction>(
2930 Phi->getIncomingValueForBlock(L->getLoopLatch()));
2931 if (!PostIncV || (SE.getSCEV(PostIncV) != SE.getSCEV(IVSrc)))
2932 continue;
2933 Value *IVOper = IVSrc;
2934 Type *PostIncTy = PostIncV->getType();
2935 if (IVTy != PostIncTy) {
2936 assert(PostIncTy->isPointerTy() && "mixing int/ptr IV types");
2937 IRBuilder<> Builder(L->getLoopLatch()->getTerminator());
2938 Builder.SetCurrentDebugLocation(PostIncV->getDebugLoc());
2939 IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy, "lsr.chain");
2940 }
2941 Phi->replaceUsesOfWith(PostIncV, IVOper);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002942 DeadInsts.emplace_back(PostIncV);
Andrew Trick248d4102012-01-09 21:18:52 +00002943 }
2944 }
Andrew Trick29fe5f02012-01-09 19:50:34 +00002945}
2946
Dan Gohman45774ce2010-02-12 10:34:29 +00002947void LSRInstance::CollectFixupsAndInitialFormulae() {
Craig Topper042a3922015-05-25 20:01:18 +00002948 for (const IVStrideUse &U : IU) {
2949 Instruction *UserInst = U.getUser();
Andrew Trick248d4102012-01-09 21:18:52 +00002950 // Skip IV users that are part of profitable IV Chains.
2951 User::op_iterator UseI = std::find(UserInst->op_begin(), UserInst->op_end(),
Craig Topper042a3922015-05-25 20:01:18 +00002952 U.getOperandValToReplace());
Andrew Trick248d4102012-01-09 21:18:52 +00002953 assert(UseI != UserInst->op_end() && "cannot find IV operand");
2954 if (IVIncSet.count(UseI))
2955 continue;
2956
Dan Gohman45774ce2010-02-12 10:34:29 +00002957 // Record the uses.
2958 LSRFixup &LF = getNewFixup();
Andrew Trick248d4102012-01-09 21:18:52 +00002959 LF.UserInst = UserInst;
Craig Topper042a3922015-05-25 20:01:18 +00002960 LF.OperandValToReplace = U.getOperandValToReplace();
2961 LF.PostIncLoops = U.getPostIncLoops();
Dan Gohman45774ce2010-02-12 10:34:29 +00002962
2963 LSRUse::KindType Kind = LSRUse::Basic;
Craig Topperf40110f2014-04-25 05:29:35 +00002964 Type *AccessTy = nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +00002965 if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
2966 Kind = LSRUse::Address;
2967 AccessTy = getAccessType(LF.UserInst);
2968 }
2969
Craig Topper042a3922015-05-25 20:01:18 +00002970 const SCEV *S = IU.getExpr(U);
Dan Gohman45774ce2010-02-12 10:34:29 +00002971
2972 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
2973 // (N - i == 0), and this allows (N - i) to be the expression that we work
2974 // with rather than just N or i, so we can consider the register
2975 // requirements for both N and i at the same time. Limiting this code to
2976 // equality icmps is not a problem because all interesting loops use
2977 // equality icmps, thanks to IndVarSimplify.
2978 if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
2979 if (CI->isEquality()) {
2980 // Swap the operands if needed to put the OperandValToReplace on the
2981 // left, for consistency.
2982 Value *NV = CI->getOperand(1);
2983 if (NV == LF.OperandValToReplace) {
2984 CI->setOperand(1, CI->getOperand(0));
2985 CI->setOperand(0, NV);
Dan Gohmanee2fea32010-05-20 19:26:52 +00002986 NV = CI->getOperand(1);
Dan Gohmanfdf98742010-05-20 19:16:03 +00002987 Changed = true;
Dan Gohman45774ce2010-02-12 10:34:29 +00002988 }
2989
2990 // x == y --> x - y == 0
2991 const SCEV *N = SE.getSCEV(NV);
Andrew Trick57243da2013-10-25 21:35:56 +00002992 if (SE.isLoopInvariant(N, L) && isSafeToExpand(N, SE)) {
Dan Gohman3268e4d2011-05-18 21:02:18 +00002993 // S is normalized, so normalize N before folding it into S
2994 // to keep the result normalized.
Craig Topperf40110f2014-04-25 05:29:35 +00002995 N = TransformForPostIncUse(Normalize, N, CI, nullptr,
Dan Gohman3268e4d2011-05-18 21:02:18 +00002996 LF.PostIncLoops, SE, DT);
Dan Gohman45774ce2010-02-12 10:34:29 +00002997 Kind = LSRUse::ICmpZero;
2998 S = SE.getMinusSCEV(N, S);
2999 }
3000
3001 // -1 and the negations of all interesting strides (except the negation
3002 // of -1) are now also interesting.
3003 for (size_t i = 0, e = Factors.size(); i != e; ++i)
3004 if (Factors[i] != -1)
3005 Factors.insert(-(uint64_t)Factors[i]);
3006 Factors.insert(-1);
3007 }
3008
3009 // Set up the initial formula for this use.
3010 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
3011 LF.LUIdx = P.first;
3012 LF.Offset = P.second;
3013 LSRUse &LU = Uses[LF.LUIdx];
Dan Gohmand006ab92010-04-07 22:27:08 +00003014 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Dan Gohman14152082010-07-15 20:24:58 +00003015 if (!LU.WidestFixupType ||
3016 SE.getTypeSizeInBits(LU.WidestFixupType) <
3017 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
3018 LU.WidestFixupType = LF.OperandValToReplace->getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00003019
3020 // If this is the first use of this LSRUse, give it a formula.
3021 if (LU.Formulae.empty()) {
Dan Gohman8c16b382010-02-22 04:11:59 +00003022 InsertInitialFormula(S, LU, LF.LUIdx);
Dan Gohman45774ce2010-02-12 10:34:29 +00003023 CountRegisters(LU.Formulae.back(), LF.LUIdx);
3024 }
3025 }
3026
3027 DEBUG(print_fixups(dbgs()));
3028}
3029
Dan Gohmana4ca28a2010-05-20 20:52:00 +00003030/// InsertInitialFormula - Insert a formula for the given expression into
3031/// the given use, separating out loop-variant portions from loop-invariant
3032/// and loop-computable portions.
Dan Gohman45774ce2010-02-12 10:34:29 +00003033void
Dan Gohman8c16b382010-02-22 04:11:59 +00003034LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
Andrew Trick57243da2013-10-25 21:35:56 +00003035 // Mark uses whose expressions cannot be expanded.
3036 if (!isSafeToExpand(S, SE))
3037 LU.RigidFormula = true;
3038
Dan Gohman45774ce2010-02-12 10:34:29 +00003039 Formula F;
Dan Gohman20d9ce22010-11-17 21:41:58 +00003040 F.InitialMatch(S, L, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +00003041 bool Inserted = InsertFormula(LU, LUIdx, F);
3042 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
3043}
3044
Dan Gohmana4ca28a2010-05-20 20:52:00 +00003045/// InsertSupplementalFormula - Insert a simple single-register formula for
3046/// the given expression into the given use.
Dan Gohman45774ce2010-02-12 10:34:29 +00003047void
3048LSRInstance::InsertSupplementalFormula(const SCEV *S,
3049 LSRUse &LU, size_t LUIdx) {
3050 Formula F;
3051 F.BaseRegs.push_back(S);
Chandler Carruth7e31c8f2013-01-12 23:46:04 +00003052 F.HasBaseReg = true;
Dan Gohman45774ce2010-02-12 10:34:29 +00003053 bool Inserted = InsertFormula(LU, LUIdx, F);
3054 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
3055}
3056
3057/// CountRegisters - Note which registers are used by the given formula,
3058/// updating RegUses.
3059void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
3060 if (F.ScaledReg)
3061 RegUses.CountRegister(F.ScaledReg, LUIdx);
Craig Topper042a3922015-05-25 20:01:18 +00003062 for (const SCEV *BaseReg : F.BaseRegs)
3063 RegUses.CountRegister(BaseReg, LUIdx);
Dan Gohman45774ce2010-02-12 10:34:29 +00003064}
3065
3066/// InsertFormula - If the given formula has not yet been inserted, add it to
3067/// the list, and return true. Return false otherwise.
3068bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003069 // Do not insert formula that we will not be able to expand.
3070 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) &&
3071 "Formula is illegal");
Dan Gohman8c16b382010-02-22 04:11:59 +00003072 if (!LU.InsertFormula(F))
Dan Gohman45774ce2010-02-12 10:34:29 +00003073 return false;
3074
3075 CountRegisters(F, LUIdx);
3076 return true;
3077}
3078
3079/// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
3080/// loop-invariant values which we're tracking. These other uses will pin these
3081/// values in registers, making them less profitable for elimination.
3082/// TODO: This currently misses non-constant addrec step registers.
3083/// TODO: Should this give more weight to users inside the loop?
3084void
3085LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
3086 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
Andrew Trickdd925ad2014-10-25 19:59:30 +00003087 SmallPtrSet<const SCEV *, 32> Visited;
Dan Gohman45774ce2010-02-12 10:34:29 +00003088
3089 while (!Worklist.empty()) {
3090 const SCEV *S = Worklist.pop_back_val();
3091
Andrew Trick9ccbed52014-10-25 19:42:07 +00003092 // Don't process the same SCEV twice
David Blaikie70573dc2014-11-19 07:49:26 +00003093 if (!Visited.insert(S).second)
Andrew Trick9ccbed52014-10-25 19:42:07 +00003094 continue;
3095
Dan Gohman45774ce2010-02-12 10:34:29 +00003096 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
Dan Gohmandd41bba2010-06-21 19:47:52 +00003097 Worklist.append(N->op_begin(), N->op_end());
Dan Gohman45774ce2010-02-12 10:34:29 +00003098 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
3099 Worklist.push_back(C->getOperand());
3100 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
3101 Worklist.push_back(D->getLHS());
3102 Worklist.push_back(D->getRHS());
Chandler Carruthcdf47882014-03-09 03:16:01 +00003103 } else if (const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003104 const Value *V = US->getValue();
Dan Gohman67b44032010-06-04 23:16:05 +00003105 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
3106 // Look for instructions defined outside the loop.
Dan Gohman45774ce2010-02-12 10:34:29 +00003107 if (L->contains(Inst)) continue;
Dan Gohman67b44032010-06-04 23:16:05 +00003108 } else if (isa<UndefValue>(V))
3109 // Undef doesn't have a live range, so it doesn't matter.
3110 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003111 for (const Use &U : V->uses()) {
3112 const Instruction *UserInst = dyn_cast<Instruction>(U.getUser());
Dan Gohman45774ce2010-02-12 10:34:29 +00003113 // Ignore non-instructions.
3114 if (!UserInst)
Dan Gohman045f8192010-01-22 00:46:49 +00003115 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003116 // Ignore instructions in other functions (as can happen with
3117 // Constants).
3118 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
Dan Gohman045f8192010-01-22 00:46:49 +00003119 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003120 // Ignore instructions not dominated by the loop.
3121 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
3122 UserInst->getParent() :
3123 cast<PHINode>(UserInst)->getIncomingBlock(
Chandler Carruthcdf47882014-03-09 03:16:01 +00003124 PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
Dan Gohman45774ce2010-02-12 10:34:29 +00003125 if (!DT.dominates(L->getHeader(), UseBB))
3126 continue;
3127 // Ignore uses which are part of other SCEV expressions, to avoid
3128 // analyzing them multiple times.
Dan Gohman42ec4eb2010-04-09 19:12:34 +00003129 if (SE.isSCEVable(UserInst->getType())) {
3130 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
3131 // If the user is a no-op, look through to its uses.
3132 if (!isa<SCEVUnknown>(UserS))
3133 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003134 if (UserS == US) {
Dan Gohman42ec4eb2010-04-09 19:12:34 +00003135 Worklist.push_back(
3136 SE.getUnknown(const_cast<Instruction *>(UserInst)));
3137 continue;
3138 }
3139 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003140 // Ignore icmp instructions which are already being analyzed.
3141 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003142 unsigned OtherIdx = !U.getOperandNo();
Dan Gohman45774ce2010-02-12 10:34:29 +00003143 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
Dan Gohmanafd6db92010-11-17 21:23:15 +00003144 if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L))
Dan Gohman45774ce2010-02-12 10:34:29 +00003145 continue;
3146 }
3147
3148 LSRFixup &LF = getNewFixup();
3149 LF.UserInst = const_cast<Instruction *>(UserInst);
Chandler Carruthcdf47882014-03-09 03:16:01 +00003150 LF.OperandValToReplace = U;
Craig Topperf40110f2014-04-25 05:29:35 +00003151 std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, nullptr);
Dan Gohman45774ce2010-02-12 10:34:29 +00003152 LF.LUIdx = P.first;
3153 LF.Offset = P.second;
3154 LSRUse &LU = Uses[LF.LUIdx];
Dan Gohmand006ab92010-04-07 22:27:08 +00003155 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Dan Gohman14152082010-07-15 20:24:58 +00003156 if (!LU.WidestFixupType ||
3157 SE.getTypeSizeInBits(LU.WidestFixupType) <
3158 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
3159 LU.WidestFixupType = LF.OperandValToReplace->getType();
Chandler Carruthcdf47882014-03-09 03:16:01 +00003160 InsertSupplementalFormula(US, LU, LF.LUIdx);
Dan Gohman45774ce2010-02-12 10:34:29 +00003161 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
3162 break;
3163 }
3164 }
3165 }
3166}
3167
3168/// CollectSubexprs - Split S into subexpressions which can be pulled out into
3169/// separate registers. If C is non-null, multiply each subexpression by C.
Andrew Trickc8037062012-07-17 05:30:37 +00003170///
3171/// Return remainder expression after factoring the subexpressions captured by
3172/// Ops. If Ops is complete, return NULL.
3173static const SCEV *CollectSubexprs(const SCEV *S, const SCEVConstant *C,
3174 SmallVectorImpl<const SCEV *> &Ops,
3175 const Loop *L,
3176 ScalarEvolution &SE,
3177 unsigned Depth = 0) {
3178 // Arbitrarily cap recursion to protect compile time.
3179 if (Depth >= 3)
3180 return S;
3181
Dan Gohman45774ce2010-02-12 10:34:29 +00003182 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3183 // Break out add operands.
Craig Topper042a3922015-05-25 20:01:18 +00003184 for (const SCEV *S : Add->operands()) {
3185 const SCEV *Remainder = CollectSubexprs(S, C, Ops, L, SE, Depth+1);
Andrew Trickc8037062012-07-17 05:30:37 +00003186 if (Remainder)
3187 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
3188 }
Craig Topperf40110f2014-04-25 05:29:35 +00003189 return nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +00003190 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
3191 // Split a non-zero base out of an addrec.
Andrew Trickc8037062012-07-17 05:30:37 +00003192 if (AR->getStart()->isZero())
3193 return S;
3194
3195 const SCEV *Remainder = CollectSubexprs(AR->getStart(),
3196 C, Ops, L, SE, Depth+1);
3197 // Split the non-zero AddRec unless it is part of a nested recurrence that
3198 // does not pertain to this loop.
3199 if (Remainder && (AR->getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) {
3200 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
Craig Topperf40110f2014-04-25 05:29:35 +00003201 Remainder = nullptr;
Andrew Trickc8037062012-07-17 05:30:37 +00003202 }
3203 if (Remainder != AR->getStart()) {
3204 if (!Remainder)
3205 Remainder = SE.getConstant(AR->getType(), 0);
3206 return SE.getAddRecExpr(Remainder,
3207 AR->getStepRecurrence(SE),
3208 AR->getLoop(),
3209 //FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
3210 SCEV::FlagAnyWrap);
Dan Gohman45774ce2010-02-12 10:34:29 +00003211 }
3212 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3213 // Break (C * (a + b + c)) into C*a + C*b + C*c.
Andrew Trickc8037062012-07-17 05:30:37 +00003214 if (Mul->getNumOperands() != 2)
3215 return S;
3216 if (const SCEVConstant *Op0 =
3217 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3218 C = C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0;
3219 const SCEV *Remainder =
3220 CollectSubexprs(Mul->getOperand(1), C, Ops, L, SE, Depth+1);
3221 if (Remainder)
3222 Ops.push_back(SE.getMulExpr(C, Remainder));
Craig Topperf40110f2014-04-25 05:29:35 +00003223 return nullptr;
Andrew Trickc8037062012-07-17 05:30:37 +00003224 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003225 }
Andrew Trickc8037062012-07-17 05:30:37 +00003226 return S;
Dan Gohman45774ce2010-02-12 10:34:29 +00003227}
3228
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003229/// \brief Helper function for LSRInstance::GenerateReassociations.
3230void LSRInstance::GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
3231 const Formula &Base,
3232 unsigned Depth, size_t Idx,
3233 bool IsScaledReg) {
3234 const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3235 SmallVector<const SCEV *, 8> AddOps;
3236 const SCEV *Remainder = CollectSubexprs(BaseReg, nullptr, AddOps, L, SE);
3237 if (Remainder)
3238 AddOps.push_back(Remainder);
3239
3240 if (AddOps.size() == 1)
3241 return;
3242
3243 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
3244 JE = AddOps.end();
3245 J != JE; ++J) {
3246
3247 // Loop-variant "unknown" values are uninteresting; we won't be able to
3248 // do anything meaningful with them.
3249 if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L))
3250 continue;
3251
3252 // Don't pull a constant into a register if the constant could be folded
3253 // into an immediate field.
3254 if (isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
3255 LU.AccessTy, *J, Base.getNumRegs() > 1))
3256 continue;
3257
3258 // Collect all operands except *J.
3259 SmallVector<const SCEV *, 8> InnerAddOps(
3260 ((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J);
3261 InnerAddOps.append(std::next(J),
3262 ((const SmallVector<const SCEV *, 8> &)AddOps).end());
3263
3264 // Don't leave just a constant behind in a register if the constant could
3265 // be folded into an immediate field.
3266 if (InnerAddOps.size() == 1 &&
3267 isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
3268 LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1))
3269 continue;
3270
3271 const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
3272 if (InnerSum->isZero())
3273 continue;
3274 Formula F = Base;
3275
3276 // Add the remaining pieces of the add back into the new formula.
3277 const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(InnerSum);
3278 if (InnerSumSC && SE.getTypeSizeInBits(InnerSumSC->getType()) <= 64 &&
3279 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
3280 InnerSumSC->getValue()->getZExtValue())) {
3281 F.UnfoldedOffset =
3282 (uint64_t)F.UnfoldedOffset + InnerSumSC->getValue()->getZExtValue();
3283 if (IsScaledReg)
3284 F.ScaledReg = nullptr;
3285 else
3286 F.BaseRegs.erase(F.BaseRegs.begin() + Idx);
3287 } else if (IsScaledReg)
3288 F.ScaledReg = InnerSum;
3289 else
3290 F.BaseRegs[Idx] = InnerSum;
3291
3292 // Add J as its own register, or an unfolded immediate.
3293 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*J);
3294 if (SC && SE.getTypeSizeInBits(SC->getType()) <= 64 &&
3295 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
3296 SC->getValue()->getZExtValue()))
3297 F.UnfoldedOffset =
3298 (uint64_t)F.UnfoldedOffset + SC->getValue()->getZExtValue();
3299 else
3300 F.BaseRegs.push_back(*J);
3301 // We may have changed the number of register in base regs, adjust the
3302 // formula accordingly.
3303 F.Canonicalize();
3304
3305 if (InsertFormula(LU, LUIdx, F))
3306 // If that formula hadn't been seen before, recurse to find more like
3307 // it.
3308 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth + 1);
3309 }
3310}
3311
Dan Gohman45774ce2010-02-12 10:34:29 +00003312/// GenerateReassociations - Split out subexpressions from adds and the bases of
3313/// addrecs.
3314void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003315 Formula Base, unsigned Depth) {
3316 assert(Base.isCanonical() && "Input must be in the canonical form");
Dan Gohman45774ce2010-02-12 10:34:29 +00003317 // Arbitrarily cap recursion to protect compile time.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003318 if (Depth >= 3)
3319 return;
Dan Gohman45774ce2010-02-12 10:34:29 +00003320
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003321 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3322 GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i);
Dan Gohman45774ce2010-02-12 10:34:29 +00003323
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003324 if (Base.Scale == 1)
3325 GenerateReassociationsImpl(LU, LUIdx, Base, Depth,
3326 /* Idx */ -1, /* IsScaledReg */ true);
Dan Gohman45774ce2010-02-12 10:34:29 +00003327}
3328
3329/// GenerateCombinations - Generate a formula consisting of all of the
3330/// loop-dominating registers added into a single register.
3331void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
Dan Gohmane4e51a62010-02-14 18:51:39 +00003332 Formula Base) {
Dan Gohman8b0a4192010-03-01 17:49:51 +00003333 // This method is only interesting on a plurality of registers.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003334 if (Base.BaseRegs.size() + (Base.Scale == 1) <= 1)
3335 return;
Dan Gohman45774ce2010-02-12 10:34:29 +00003336
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003337 // Flatten the representation, i.e., reg1 + 1*reg2 => reg1 + reg2, before
3338 // processing the formula.
3339 Base.Unscale();
Dan Gohman45774ce2010-02-12 10:34:29 +00003340 Formula F = Base;
3341 F.BaseRegs.clear();
3342 SmallVector<const SCEV *, 4> Ops;
Craig Topper042a3922015-05-25 20:01:18 +00003343 for (const SCEV *BaseReg : Base.BaseRegs) {
Dan Gohman20d9ce22010-11-17 21:41:58 +00003344 if (SE.properlyDominates(BaseReg, L->getHeader()) &&
Dan Gohmanafd6db92010-11-17 21:23:15 +00003345 !SE.hasComputableLoopEvolution(BaseReg, L))
Dan Gohman45774ce2010-02-12 10:34:29 +00003346 Ops.push_back(BaseReg);
3347 else
3348 F.BaseRegs.push_back(BaseReg);
3349 }
3350 if (Ops.size() > 1) {
Dan Gohmanbb7d5222010-02-14 18:50:49 +00003351 const SCEV *Sum = SE.getAddExpr(Ops);
3352 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
3353 // opportunity to fold something. For now, just ignore such cases
Dan Gohman8b0a4192010-03-01 17:49:51 +00003354 // rather than proceed with zero in a register.
Dan Gohmanbb7d5222010-02-14 18:50:49 +00003355 if (!Sum->isZero()) {
3356 F.BaseRegs.push_back(Sum);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003357 F.Canonicalize();
Dan Gohmanbb7d5222010-02-14 18:50:49 +00003358 (void)InsertFormula(LU, LUIdx, F);
3359 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003360 }
3361}
3362
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003363/// \brief Helper function for LSRInstance::GenerateSymbolicOffsets.
3364void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
3365 const Formula &Base, size_t Idx,
3366 bool IsScaledReg) {
3367 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3368 GlobalValue *GV = ExtractSymbol(G, SE);
3369 if (G->isZero() || !GV)
3370 return;
3371 Formula F = Base;
3372 F.BaseGV = GV;
3373 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3374 return;
3375 if (IsScaledReg)
3376 F.ScaledReg = G;
3377 else
3378 F.BaseRegs[Idx] = G;
3379 (void)InsertFormula(LU, LUIdx, F);
3380}
3381
Dan Gohman45774ce2010-02-12 10:34:29 +00003382/// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
3383void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
3384 Formula Base) {
3385 // We can't add a symbolic offset if the address already contains one.
Chandler Carruth6e479322013-01-07 15:04:40 +00003386 if (Base.BaseGV) return;
Dan Gohman45774ce2010-02-12 10:34:29 +00003387
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003388 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3389 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i);
3390 if (Base.Scale == 1)
3391 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, /* Idx */ -1,
3392 /* IsScaledReg */ true);
3393}
3394
3395/// \brief Helper function for LSRInstance::GenerateConstantOffsets.
3396void LSRInstance::GenerateConstantOffsetsImpl(
3397 LSRUse &LU, unsigned LUIdx, const Formula &Base,
3398 const SmallVectorImpl<int64_t> &Worklist, size_t Idx, bool IsScaledReg) {
3399 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
Craig Topper042a3922015-05-25 20:01:18 +00003400 for (int64_t Offset : Worklist) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003401 Formula F = Base;
Craig Topper042a3922015-05-25 20:01:18 +00003402 F.BaseOffset = (uint64_t)Base.BaseOffset - Offset;
3403 if (isLegalUse(TTI, LU.MinOffset - Offset, LU.MaxOffset - Offset, LU.Kind,
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003404 LU.AccessTy, F)) {
3405 // Add the offset to the base register.
Craig Topper042a3922015-05-25 20:01:18 +00003406 const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), Offset), G);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003407 // If it cancelled out, drop the base register, otherwise update it.
3408 if (NewG->isZero()) {
3409 if (IsScaledReg) {
3410 F.Scale = 0;
3411 F.ScaledReg = nullptr;
3412 } else
3413 F.DeleteBaseReg(F.BaseRegs[Idx]);
3414 F.Canonicalize();
3415 } else if (IsScaledReg)
3416 F.ScaledReg = NewG;
3417 else
3418 F.BaseRegs[Idx] = NewG;
3419
3420 (void)InsertFormula(LU, LUIdx, F);
3421 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003422 }
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003423
3424 int64_t Imm = ExtractImmediate(G, SE);
3425 if (G->isZero() || Imm == 0)
3426 return;
3427 Formula F = Base;
3428 F.BaseOffset = (uint64_t)F.BaseOffset + Imm;
3429 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3430 return;
3431 if (IsScaledReg)
3432 F.ScaledReg = G;
3433 else
3434 F.BaseRegs[Idx] = G;
3435 (void)InsertFormula(LU, LUIdx, F);
Dan Gohman45774ce2010-02-12 10:34:29 +00003436}
3437
3438/// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
3439void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
3440 Formula Base) {
3441 // TODO: For now, just add the min and max offset, because it usually isn't
3442 // worthwhile looking at everything inbetween.
Dan Gohman4afd4122010-07-15 15:14:45 +00003443 SmallVector<int64_t, 2> Worklist;
Dan Gohman45774ce2010-02-12 10:34:29 +00003444 Worklist.push_back(LU.MinOffset);
3445 if (LU.MaxOffset != LU.MinOffset)
3446 Worklist.push_back(LU.MaxOffset);
3447
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003448 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3449 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i);
3450 if (Base.Scale == 1)
3451 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, /* Idx */ -1,
3452 /* IsScaledReg */ true);
Dan Gohman45774ce2010-02-12 10:34:29 +00003453}
3454
3455/// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
3456/// the comparison. For example, x == y -> x*c == y*c.
3457void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
3458 Formula Base) {
3459 if (LU.Kind != LSRUse::ICmpZero) return;
3460
3461 // Determine the integer type for the base formula.
Chris Lattner229907c2011-07-18 04:54:35 +00003462 Type *IntTy = Base.getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00003463 if (!IntTy) return;
3464 if (SE.getTypeSizeInBits(IntTy) > 64) return;
3465
3466 // Don't do this if there is more than one offset.
3467 if (LU.MinOffset != LU.MaxOffset) return;
3468
Chandler Carruth6e479322013-01-07 15:04:40 +00003469 assert(!Base.BaseGV && "ICmpZero use is not legal!");
Dan Gohman45774ce2010-02-12 10:34:29 +00003470
3471 // Check each interesting stride.
Craig Topper042a3922015-05-25 20:01:18 +00003472 for (int64_t Factor : Factors) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003473 // Check that the multiplication doesn't overflow.
Chandler Carruth6e479322013-01-07 15:04:40 +00003474 if (Base.BaseOffset == INT64_MIN && Factor == -1)
Dan Gohman5f10d6c2010-02-17 00:41:53 +00003475 continue;
Chandler Carruth6e479322013-01-07 15:04:40 +00003476 int64_t NewBaseOffset = (uint64_t)Base.BaseOffset * Factor;
3477 if (NewBaseOffset / Factor != Base.BaseOffset)
Dan Gohman45774ce2010-02-12 10:34:29 +00003478 continue;
Andrew Trick429e9ed2014-02-26 16:31:56 +00003479 // If the offset will be truncated at this use, check that it is in bounds.
3480 if (!IntTy->isPointerTy() &&
3481 !ConstantInt::isValueValidForType(IntTy, NewBaseOffset))
3482 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003483
3484 // Check that multiplying with the use offset doesn't overflow.
3485 int64_t Offset = LU.MinOffset;
Dan Gohman5f10d6c2010-02-17 00:41:53 +00003486 if (Offset == INT64_MIN && Factor == -1)
3487 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003488 Offset = (uint64_t)Offset * Factor;
Dan Gohman13ac3b22010-02-17 00:42:19 +00003489 if (Offset / Factor != LU.MinOffset)
Dan Gohman45774ce2010-02-12 10:34:29 +00003490 continue;
Andrew Trick429e9ed2014-02-26 16:31:56 +00003491 // If the offset will be truncated at this use, check that it is in bounds.
3492 if (!IntTy->isPointerTy() &&
3493 !ConstantInt::isValueValidForType(IntTy, Offset))
3494 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003495
Dan Gohman963b1c12010-06-24 16:57:52 +00003496 Formula F = Base;
Chandler Carruth6e479322013-01-07 15:04:40 +00003497 F.BaseOffset = NewBaseOffset;
Dan Gohman963b1c12010-06-24 16:57:52 +00003498
Dan Gohman45774ce2010-02-12 10:34:29 +00003499 // Check that this scale is legal.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003500 if (!isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F))
Dan Gohman45774ce2010-02-12 10:34:29 +00003501 continue;
3502
3503 // Compensate for the use having MinOffset built into it.
Chandler Carruth6e479322013-01-07 15:04:40 +00003504 F.BaseOffset = (uint64_t)F.BaseOffset + Offset - LU.MinOffset;
Dan Gohman45774ce2010-02-12 10:34:29 +00003505
Dan Gohman1d2ded72010-05-03 22:09:21 +00003506 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
Dan Gohman45774ce2010-02-12 10:34:29 +00003507
3508 // Check that multiplying with each base register doesn't overflow.
3509 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
3510 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
Dan Gohman4eebb942010-02-19 19:35:48 +00003511 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
Dan Gohman45774ce2010-02-12 10:34:29 +00003512 goto next;
3513 }
3514
3515 // Check that multiplying with the scaled register doesn't overflow.
3516 if (F.ScaledReg) {
3517 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
Dan Gohman4eebb942010-02-19 19:35:48 +00003518 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
Dan Gohman45774ce2010-02-12 10:34:29 +00003519 continue;
3520 }
3521
Dan Gohman6136e942011-05-03 00:46:49 +00003522 // Check that multiplying with the unfolded offset doesn't overflow.
3523 if (F.UnfoldedOffset != 0) {
Dan Gohman6c4a3192011-05-23 21:07:39 +00003524 if (F.UnfoldedOffset == INT64_MIN && Factor == -1)
3525 continue;
Dan Gohman6136e942011-05-03 00:46:49 +00003526 F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor;
3527 if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset)
3528 continue;
Andrew Trick429e9ed2014-02-26 16:31:56 +00003529 // If the offset will be truncated, check that it is in bounds.
3530 if (!IntTy->isPointerTy() &&
3531 !ConstantInt::isValueValidForType(IntTy, F.UnfoldedOffset))
3532 continue;
Dan Gohman6136e942011-05-03 00:46:49 +00003533 }
3534
Dan Gohman45774ce2010-02-12 10:34:29 +00003535 // If we make it here and it's legal, add it.
3536 (void)InsertFormula(LU, LUIdx, F);
3537 next:;
3538 }
3539}
3540
3541/// GenerateScales - Generate stride factor reuse formulae by making use of
3542/// scaled-offset address modes, for example.
Dan Gohmanab5fb7f2010-05-20 19:44:23 +00003543void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003544 // Determine the integer type for the base formula.
Chris Lattner229907c2011-07-18 04:54:35 +00003545 Type *IntTy = Base.getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00003546 if (!IntTy) return;
3547
3548 // If this Formula already has a scaled register, we can't add another one.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003549 // Try to unscale the formula to generate a better scale.
3550 if (Base.Scale != 0 && !Base.Unscale())
3551 return;
3552
3553 assert(Base.Scale == 0 && "Unscale did not did its job!");
Dan Gohman45774ce2010-02-12 10:34:29 +00003554
3555 // Check each interesting stride.
Craig Topper042a3922015-05-25 20:01:18 +00003556 for (int64_t Factor : Factors) {
Chandler Carruth6e479322013-01-07 15:04:40 +00003557 Base.Scale = Factor;
3558 Base.HasBaseReg = Base.BaseRegs.size() > 1;
Dan Gohman45774ce2010-02-12 10:34:29 +00003559 // Check whether this scale is going to be legal.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003560 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
3561 Base)) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003562 // As a special-case, handle special out-of-loop Basic users specially.
3563 // TODO: Reconsider this special case.
3564 if (LU.Kind == LSRUse::Basic &&
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003565 isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special,
3566 LU.AccessTy, Base) &&
Dan Gohman45774ce2010-02-12 10:34:29 +00003567 LU.AllFixupsOutsideLoop)
3568 LU.Kind = LSRUse::Special;
3569 else
3570 continue;
3571 }
3572 // For an ICmpZero, negating a solitary base register won't lead to
3573 // new solutions.
3574 if (LU.Kind == LSRUse::ICmpZero &&
Chandler Carruth6e479322013-01-07 15:04:40 +00003575 !Base.HasBaseReg && Base.BaseOffset == 0 && !Base.BaseGV)
Dan Gohman45774ce2010-02-12 10:34:29 +00003576 continue;
3577 // For each addrec base reg, apply the scale, if possible.
3578 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3579 if (const SCEVAddRecExpr *AR =
3580 dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00003581 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
Dan Gohman45774ce2010-02-12 10:34:29 +00003582 if (FactorS->isZero())
3583 continue;
3584 // Divide out the factor, ignoring high bits, since we'll be
3585 // scaling the value back up in the end.
Dan Gohman4eebb942010-02-19 19:35:48 +00003586 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003587 // TODO: This could be optimized to avoid all the copying.
3588 Formula F = Base;
3589 F.ScaledReg = Quotient;
Dan Gohman80a96082010-05-20 15:17:54 +00003590 F.DeleteBaseReg(F.BaseRegs[i]);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003591 // The canonical representation of 1*reg is reg, which is already in
3592 // Base. In that case, do not try to insert the formula, it will be
3593 // rejected anyway.
3594 if (F.Scale == 1 && F.BaseRegs.empty())
3595 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003596 (void)InsertFormula(LU, LUIdx, F);
3597 }
3598 }
3599 }
3600}
3601
3602/// GenerateTruncates - Generate reuse formulae from different IV types.
Dan Gohmanab5fb7f2010-05-20 19:44:23 +00003603void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003604 // Don't bother truncating symbolic values.
Chandler Carruth6e479322013-01-07 15:04:40 +00003605 if (Base.BaseGV) return;
Dan Gohman45774ce2010-02-12 10:34:29 +00003606
3607 // Determine the integer type for the base formula.
Chris Lattner229907c2011-07-18 04:54:35 +00003608 Type *DstTy = Base.getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00003609 if (!DstTy) return;
3610 DstTy = SE.getEffectiveSCEVType(DstTy);
3611
Craig Topper042a3922015-05-25 20:01:18 +00003612 for (Type *SrcTy : Types) {
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003613 if (SrcTy != DstTy && TTI.isTruncateFree(SrcTy, DstTy)) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003614 Formula F = Base;
3615
Craig Topper042a3922015-05-25 20:01:18 +00003616 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, SrcTy);
3617 for (const SCEV *&BaseReg : F.BaseRegs)
3618 BaseReg = SE.getAnyExtendExpr(BaseReg, SrcTy);
Dan Gohman45774ce2010-02-12 10:34:29 +00003619
3620 // TODO: This assumes we've done basic processing on all uses and
3621 // have an idea what the register usage is.
3622 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
3623 continue;
3624
3625 (void)InsertFormula(LU, LUIdx, F);
3626 }
3627 }
3628}
3629
3630namespace {
3631
Dan Gohmane7f74bb2010-02-14 18:51:20 +00003632/// WorkItem - Helper class for GenerateCrossUseConstantOffsets. It's used to
Dan Gohman45774ce2010-02-12 10:34:29 +00003633/// defer modifications so that the search phase doesn't have to worry about
3634/// the data structures moving underneath it.
3635struct WorkItem {
3636 size_t LUIdx;
3637 int64_t Imm;
3638 const SCEV *OrigReg;
3639
3640 WorkItem(size_t LI, int64_t I, const SCEV *R)
3641 : LUIdx(LI), Imm(I), OrigReg(R) {}
3642
3643 void print(raw_ostream &OS) const;
3644 void dump() const;
3645};
3646
Alexander Kornienkof00654e2015-06-23 09:49:53 +00003647}
Dan Gohman45774ce2010-02-12 10:34:29 +00003648
3649void WorkItem::print(raw_ostream &OS) const {
3650 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
3651 << " , add offset " << Imm;
3652}
3653
Manman Ren49d684e2012-09-12 05:06:18 +00003654#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman45774ce2010-02-12 10:34:29 +00003655void WorkItem::dump() const {
3656 print(errs()); errs() << '\n';
3657}
Manman Renc3366cc2012-09-06 19:55:56 +00003658#endif
Dan Gohman45774ce2010-02-12 10:34:29 +00003659
3660/// GenerateCrossUseConstantOffsets - Look for registers which are a constant
3661/// distance apart and try to form reuse opportunities between them.
3662void LSRInstance::GenerateCrossUseConstantOffsets() {
3663 // Group the registers by their value without any added constant offset.
3664 typedef std::map<int64_t, const SCEV *> ImmMapTy;
Craig Topper042a3922015-05-25 20:01:18 +00003665 DenseMap<const SCEV *, ImmMapTy> Map;
Dan Gohman45774ce2010-02-12 10:34:29 +00003666 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
3667 SmallVector<const SCEV *, 8> Sequence;
Craig Topper042a3922015-05-25 20:01:18 +00003668 for (const SCEV *Use : RegUses) {
3669 const SCEV *Reg = Use; // Make a copy for ExtractImmediate to modify.
Dan Gohman45774ce2010-02-12 10:34:29 +00003670 int64_t Imm = ExtractImmediate(Reg, SE);
Craig Topper042a3922015-05-25 20:01:18 +00003671 auto Pair = Map.insert(std::make_pair(Reg, ImmMapTy()));
Dan Gohman45774ce2010-02-12 10:34:29 +00003672 if (Pair.second)
3673 Sequence.push_back(Reg);
Craig Topper042a3922015-05-25 20:01:18 +00003674 Pair.first->second.insert(std::make_pair(Imm, Use));
3675 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(Use);
Dan Gohman45774ce2010-02-12 10:34:29 +00003676 }
3677
3678 // Now examine each set of registers with the same base value. Build up
3679 // a list of work to do and do the work in a separate step so that we're
3680 // not adding formulae and register counts while we're searching.
Dan Gohman110ed642010-09-01 01:45:53 +00003681 SmallVector<WorkItem, 32> WorkItems;
3682 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
Craig Topper042a3922015-05-25 20:01:18 +00003683 for (const SCEV *Reg : Sequence) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003684 const ImmMapTy &Imms = Map.find(Reg)->second;
3685
Dan Gohman363f8472010-02-12 19:20:37 +00003686 // It's not worthwhile looking for reuse if there's only one offset.
3687 if (Imms.size() == 1)
3688 continue;
3689
Dan Gohman45774ce2010-02-12 10:34:29 +00003690 DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
Craig Topper042a3922015-05-25 20:01:18 +00003691 for (const auto &Entry : Imms)
3692 dbgs() << ' ' << Entry.first;
Dan Gohman45774ce2010-02-12 10:34:29 +00003693 dbgs() << '\n');
3694
3695 // Examine each offset.
3696 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
3697 J != JE; ++J) {
3698 const SCEV *OrigReg = J->second;
3699
3700 int64_t JImm = J->first;
3701 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
3702
3703 if (!isa<SCEVConstant>(OrigReg) &&
3704 UsedByIndicesMap[Reg].count() == 1) {
3705 DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
3706 continue;
3707 }
3708
3709 // Conservatively examine offsets between this orig reg a few selected
3710 // other orig regs.
3711 ImmMapTy::const_iterator OtherImms[] = {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00003712 Imms.begin(), std::prev(Imms.end()),
3713 Imms.lower_bound((Imms.begin()->first + std::prev(Imms.end())->first) /
3714 2)
Dan Gohman45774ce2010-02-12 10:34:29 +00003715 };
3716 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
3717 ImmMapTy::const_iterator M = OtherImms[i];
Dan Gohman363f8472010-02-12 19:20:37 +00003718 if (M == J || M == JE) continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003719
3720 // Compute the difference between the two.
3721 int64_t Imm = (uint64_t)JImm - M->first;
3722 for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
Dan Gohman110ed642010-09-01 01:45:53 +00003723 LUIdx = UsedByIndices.find_next(LUIdx))
Dan Gohman45774ce2010-02-12 10:34:29 +00003724 // Make a memo of this use, offset, and register tuple.
David Blaikie70573dc2014-11-19 07:49:26 +00003725 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)).second)
Dan Gohman110ed642010-09-01 01:45:53 +00003726 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
Evan Cheng85a9f432009-11-12 07:35:05 +00003727 }
3728 }
3729 }
3730
Dan Gohman45774ce2010-02-12 10:34:29 +00003731 Map.clear();
3732 Sequence.clear();
3733 UsedByIndicesMap.clear();
Dan Gohman110ed642010-09-01 01:45:53 +00003734 UniqueItems.clear();
Dan Gohman45774ce2010-02-12 10:34:29 +00003735
3736 // Now iterate through the worklist and add new formulae.
Craig Topper042a3922015-05-25 20:01:18 +00003737 for (const WorkItem &WI : WorkItems) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003738 size_t LUIdx = WI.LUIdx;
3739 LSRUse &LU = Uses[LUIdx];
3740 int64_t Imm = WI.Imm;
3741 const SCEV *OrigReg = WI.OrigReg;
3742
Chris Lattner229907c2011-07-18 04:54:35 +00003743 Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
Dan Gohman45774ce2010-02-12 10:34:29 +00003744 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
3745 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
3746
Dan Gohman8b0a4192010-03-01 17:49:51 +00003747 // TODO: Use a more targeted data structure.
Dan Gohman45774ce2010-02-12 10:34:29 +00003748 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003749 Formula F = LU.Formulae[L];
3750 // FIXME: The code for the scaled and unscaled registers looks
3751 // very similar but slightly different. Investigate if they
3752 // could be merged. That way, we would not have to unscale the
3753 // Formula.
3754 F.Unscale();
Dan Gohman45774ce2010-02-12 10:34:29 +00003755 // Use the immediate in the scaled register.
3756 if (F.ScaledReg == OrigReg) {
Chandler Carruth6e479322013-01-07 15:04:40 +00003757 int64_t Offset = (uint64_t)F.BaseOffset + Imm * (uint64_t)F.Scale;
Dan Gohman45774ce2010-02-12 10:34:29 +00003758 // Don't create 50 + reg(-50).
3759 if (F.referencesReg(SE.getSCEV(
Chandler Carruth6e479322013-01-07 15:04:40 +00003760 ConstantInt::get(IntTy, -(uint64_t)Offset))))
Dan Gohman45774ce2010-02-12 10:34:29 +00003761 continue;
3762 Formula NewF = F;
Chandler Carruth6e479322013-01-07 15:04:40 +00003763 NewF.BaseOffset = Offset;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003764 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
3765 NewF))
Dan Gohman45774ce2010-02-12 10:34:29 +00003766 continue;
3767 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
3768
3769 // If the new scale is a constant in a register, and adding the constant
3770 // value to the immediate would produce a value closer to zero than the
3771 // immediate itself, then the formula isn't worthwhile.
3772 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
Chris Lattnerb1a15122011-07-15 06:08:15 +00003773 if (C->getValue()->isNegative() !=
Chandler Carruth6e479322013-01-07 15:04:40 +00003774 (NewF.BaseOffset < 0) &&
3775 (C->getValue()->getValue().abs() * APInt(BitWidth, F.Scale))
Benjamin Kramer7bd1f7c2015-03-09 20:20:16 +00003776 .ule(std::abs(NewF.BaseOffset)))
Dan Gohman45774ce2010-02-12 10:34:29 +00003777 continue;
3778
3779 // OK, looks good.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003780 NewF.Canonicalize();
Dan Gohman45774ce2010-02-12 10:34:29 +00003781 (void)InsertFormula(LU, LUIdx, NewF);
3782 } else {
3783 // Use the immediate in a base register.
3784 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
3785 const SCEV *BaseReg = F.BaseRegs[N];
3786 if (BaseReg != OrigReg)
3787 continue;
3788 Formula NewF = F;
Chandler Carruth6e479322013-01-07 15:04:40 +00003789 NewF.BaseOffset = (uint64_t)NewF.BaseOffset + Imm;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003790 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset,
3791 LU.Kind, LU.AccessTy, NewF)) {
3792 if (!TTI.isLegalAddImmediate((uint64_t)NewF.UnfoldedOffset + Imm))
Dan Gohman6136e942011-05-03 00:46:49 +00003793 continue;
3794 NewF = F;
3795 NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm;
3796 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003797 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
3798
3799 // If the new formula has a constant in a register, and adding the
3800 // constant value to the immediate would produce a value closer to
3801 // zero than the immediate itself, then the formula isn't worthwhile.
Craig Topper10949ae2015-05-23 08:45:10 +00003802 for (const SCEV *NewReg : NewF.BaseRegs)
3803 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewReg))
Chandler Carruth6e479322013-01-07 15:04:40 +00003804 if ((C->getValue()->getValue() + NewF.BaseOffset).abs().slt(
Benjamin Kramer7bd1f7c2015-03-09 20:20:16 +00003805 std::abs(NewF.BaseOffset)) &&
Dan Gohman50f8f2c2010-05-18 23:48:08 +00003806 (C->getValue()->getValue() +
Chandler Carruth6e479322013-01-07 15:04:40 +00003807 NewF.BaseOffset).countTrailingZeros() >=
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00003808 countTrailingZeros<uint64_t>(NewF.BaseOffset))
Dan Gohman45774ce2010-02-12 10:34:29 +00003809 goto skip_formula;
3810
3811 // Ok, looks good.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003812 NewF.Canonicalize();
Dan Gohman45774ce2010-02-12 10:34:29 +00003813 (void)InsertFormula(LU, LUIdx, NewF);
3814 break;
3815 skip_formula:;
3816 }
3817 }
3818 }
3819 }
Dale Johannesen02cb2bf2009-05-11 17:15:42 +00003820}
3821
Dan Gohman45774ce2010-02-12 10:34:29 +00003822/// GenerateAllReuseFormulae - Generate formulae for each use.
3823void
3824LSRInstance::GenerateAllReuseFormulae() {
Dan Gohman521efe62010-02-16 01:42:53 +00003825 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
Dan Gohman45774ce2010-02-12 10:34:29 +00003826 // queries are more precise.
3827 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3828 LSRUse &LU = Uses[LUIdx];
3829 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3830 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
3831 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3832 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
3833 }
3834 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3835 LSRUse &LU = Uses[LUIdx];
3836 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3837 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
3838 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3839 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
3840 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3841 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
3842 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3843 GenerateScales(LU, LUIdx, LU.Formulae[i]);
Dan Gohman521efe62010-02-16 01:42:53 +00003844 }
3845 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3846 LSRUse &LU = Uses[LUIdx];
Dan Gohman45774ce2010-02-12 10:34:29 +00003847 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3848 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
3849 }
3850
3851 GenerateCrossUseConstantOffsets();
Dan Gohmanbf673e02010-08-29 15:21:38 +00003852
3853 DEBUG(dbgs() << "\n"
3854 "After generating reuse formulae:\n";
3855 print_uses(dbgs()));
Dan Gohman45774ce2010-02-12 10:34:29 +00003856}
3857
Dan Gohman1b61fd92010-10-07 23:43:09 +00003858/// If there are multiple formulae with the same set of registers used
Dan Gohman45774ce2010-02-12 10:34:29 +00003859/// by other uses, pick the best one and delete the others.
3860void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
Dan Gohman5947e162010-10-07 23:52:18 +00003861 DenseSet<const SCEV *> VisitedRegs;
3862 SmallPtrSet<const SCEV *, 16> Regs;
Andrew Trick5df90962011-12-06 03:13:31 +00003863 SmallPtrSet<const SCEV *, 16> LoserRegs;
Dan Gohman45774ce2010-02-12 10:34:29 +00003864#ifndef NDEBUG
Dan Gohman4c4043c2010-05-20 20:05:31 +00003865 bool ChangedFormulae = false;
Dan Gohman45774ce2010-02-12 10:34:29 +00003866#endif
3867
3868 // Collect the best formula for each unique set of shared registers. This
3869 // is reset for each use.
Preston Gurd25c3b6a2013-02-01 20:41:27 +00003870 typedef DenseMap<SmallVector<const SCEV *, 4>, size_t, UniquifierDenseMapInfo>
Dan Gohman45774ce2010-02-12 10:34:29 +00003871 BestFormulaeTy;
3872 BestFormulaeTy BestFormulae;
3873
3874 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3875 LSRUse &LU = Uses[LUIdx];
Dan Gohmanab5fb7f2010-05-20 19:44:23 +00003876 DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << '\n');
Dan Gohman45774ce2010-02-12 10:34:29 +00003877
Dan Gohman4cf99b52010-05-18 23:42:37 +00003878 bool Any = false;
Dan Gohman45774ce2010-02-12 10:34:29 +00003879 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
3880 FIdx != NumForms; ++FIdx) {
3881 Formula &F = LU.Formulae[FIdx];
3882
Andrew Trick5df90962011-12-06 03:13:31 +00003883 // Some formulas are instant losers. For example, they may depend on
3884 // nonexistent AddRecs from other loops. These need to be filtered
3885 // immediately, otherwise heuristics could choose them over others leading
3886 // to an unsatisfactory solution. Passing LoserRegs into RateFormula here
3887 // avoids the need to recompute this information across formulae using the
3888 // same bad AddRec. Passing LoserRegs is also essential unless we remove
3889 // the corresponding bad register from the Regs set.
3890 Cost CostF;
3891 Regs.clear();
Quentin Colombet8aa7abe2013-05-31 17:20:29 +00003892 CostF.RateFormula(TTI, F, Regs, VisitedRegs, L, LU.Offsets, SE, DT, LU,
Andrew Trick5df90962011-12-06 03:13:31 +00003893 &LoserRegs);
3894 if (CostF.isLoser()) {
3895 // During initial formula generation, undesirable formulae are generated
3896 // by uses within other loops that have some non-trivial address mode or
3897 // use the postinc form of the IV. LSR needs to provide these formulae
3898 // as the basis of rediscovering the desired formula that uses an AddRec
3899 // corresponding to the existing phi. Once all formulae have been
3900 // generated, these initial losers may be pruned.
3901 DEBUG(dbgs() << " Filtering loser "; F.print(dbgs());
3902 dbgs() << "\n");
Dan Gohman45774ce2010-02-12 10:34:29 +00003903 }
Andrew Trick5df90962011-12-06 03:13:31 +00003904 else {
Preston Gurd25c3b6a2013-02-01 20:41:27 +00003905 SmallVector<const SCEV *, 4> Key;
Craig Topper77b99412015-05-23 08:01:41 +00003906 for (const SCEV *Reg : F.BaseRegs) {
Andrew Trick5df90962011-12-06 03:13:31 +00003907 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
3908 Key.push_back(Reg);
3909 }
3910 if (F.ScaledReg &&
3911 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
3912 Key.push_back(F.ScaledReg);
3913 // Unstable sort by host order ok, because this is only used for
3914 // uniquifying.
3915 std::sort(Key.begin(), Key.end());
Dan Gohman45774ce2010-02-12 10:34:29 +00003916
Andrew Trick5df90962011-12-06 03:13:31 +00003917 std::pair<BestFormulaeTy::const_iterator, bool> P =
3918 BestFormulae.insert(std::make_pair(Key, FIdx));
3919 if (P.second)
3920 continue;
3921
Dan Gohman45774ce2010-02-12 10:34:29 +00003922 Formula &Best = LU.Formulae[P.first->second];
Dan Gohman5947e162010-10-07 23:52:18 +00003923
Dan Gohman5947e162010-10-07 23:52:18 +00003924 Cost CostBest;
Dan Gohman5947e162010-10-07 23:52:18 +00003925 Regs.clear();
Quentin Colombet8aa7abe2013-05-31 17:20:29 +00003926 CostBest.RateFormula(TTI, Best, Regs, VisitedRegs, L, LU.Offsets, SE,
3927 DT, LU);
Dan Gohman5947e162010-10-07 23:52:18 +00003928 if (CostF < CostBest)
Dan Gohman45774ce2010-02-12 10:34:29 +00003929 std::swap(F, Best);
Dan Gohman8aca7ef2010-05-18 22:37:37 +00003930 DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
Dan Gohman45774ce2010-02-12 10:34:29 +00003931 dbgs() << "\n"
Dan Gohman8aca7ef2010-05-18 22:37:37 +00003932 " in favor of formula "; Best.print(dbgs());
Dan Gohman45774ce2010-02-12 10:34:29 +00003933 dbgs() << '\n');
Dan Gohman45774ce2010-02-12 10:34:29 +00003934 }
Andrew Trick5df90962011-12-06 03:13:31 +00003935#ifndef NDEBUG
3936 ChangedFormulae = true;
3937#endif
3938 LU.DeleteFormula(F);
3939 --FIdx;
3940 --NumForms;
3941 Any = true;
Dan Gohmand0800242010-05-07 23:36:59 +00003942 }
3943
Dan Gohmanbeebef42010-05-18 23:55:57 +00003944 // Now that we've filtered out some formulae, recompute the Regs set.
Dan Gohman4cf99b52010-05-18 23:42:37 +00003945 if (Any)
3946 LU.RecomputeRegs(LUIdx, RegUses);
Dan Gohmand0800242010-05-07 23:36:59 +00003947
3948 // Reset this to prepare for the next use.
Dan Gohman45774ce2010-02-12 10:34:29 +00003949 BestFormulae.clear();
3950 }
3951
Dan Gohman4c4043c2010-05-20 20:05:31 +00003952 DEBUG(if (ChangedFormulae) {
Dan Gohman5b18f032010-02-13 02:06:02 +00003953 dbgs() << "\n"
3954 "After filtering out undesirable candidates:\n";
Dan Gohman45774ce2010-02-12 10:34:29 +00003955 print_uses(dbgs());
3956 });
3957}
3958
Dan Gohmana4eca052010-05-18 22:51:59 +00003959// This is a rough guess that seems to work fairly well.
3960static const size_t ComplexityLimit = UINT16_MAX;
3961
3962/// EstimateSearchSpaceComplexity - Estimate the worst-case number of
3963/// solutions the solver might have to consider. It almost never considers
3964/// this many solutions because it prune the search space, but the pruning
3965/// isn't always sufficient.
3966size_t LSRInstance::EstimateSearchSpaceComplexity() const {
Dan Gohman49d638b2010-10-07 23:37:58 +00003967 size_t Power = 1;
Craig Topper10949ae2015-05-23 08:45:10 +00003968 for (const LSRUse &LU : Uses) {
3969 size_t FSize = LU.Formulae.size();
Dan Gohmana4eca052010-05-18 22:51:59 +00003970 if (FSize >= ComplexityLimit) {
3971 Power = ComplexityLimit;
3972 break;
3973 }
3974 Power *= FSize;
3975 if (Power >= ComplexityLimit)
3976 break;
3977 }
3978 return Power;
3979}
3980
Dan Gohmane9e08732010-08-29 16:09:42 +00003981/// NarrowSearchSpaceByDetectingSupersets - When one formula uses a superset
3982/// of the registers of another formula, it won't help reduce register
3983/// pressure (though it may not necessarily hurt register pressure); remove
3984/// it to simplify the system.
3985void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
Dan Gohman20fab452010-05-19 23:43:12 +00003986 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
3987 DEBUG(dbgs() << "The search space is too complex.\n");
3988
3989 DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
3990 "which use a superset of registers used by other "
3991 "formulae.\n");
3992
3993 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3994 LSRUse &LU = Uses[LUIdx];
3995 bool Any = false;
3996 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
3997 Formula &F = LU.Formulae[i];
Dan Gohman8ec018c2010-05-20 20:00:41 +00003998 // Look for a formula with a constant or GV in a register. If the use
3999 // also has a formula with that same value in an immediate field,
4000 // delete the one that uses a register.
Dan Gohman20fab452010-05-19 23:43:12 +00004001 for (SmallVectorImpl<const SCEV *>::const_iterator
4002 I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
4003 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
4004 Formula NewF = F;
Chandler Carruth6e479322013-01-07 15:04:40 +00004005 NewF.BaseOffset += C->getValue()->getSExtValue();
Dan Gohman20fab452010-05-19 23:43:12 +00004006 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4007 (I - F.BaseRegs.begin()));
4008 if (LU.HasFormulaWithSameRegs(NewF)) {
4009 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
4010 LU.DeleteFormula(F);
4011 --i;
4012 --e;
4013 Any = true;
4014 break;
4015 }
4016 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
4017 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
Chandler Carruth6e479322013-01-07 15:04:40 +00004018 if (!F.BaseGV) {
Dan Gohman20fab452010-05-19 23:43:12 +00004019 Formula NewF = F;
Chandler Carruth6e479322013-01-07 15:04:40 +00004020 NewF.BaseGV = GV;
Dan Gohman20fab452010-05-19 23:43:12 +00004021 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4022 (I - F.BaseRegs.begin()));
4023 if (LU.HasFormulaWithSameRegs(NewF)) {
4024 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
4025 dbgs() << '\n');
4026 LU.DeleteFormula(F);
4027 --i;
4028 --e;
4029 Any = true;
4030 break;
4031 }
4032 }
4033 }
4034 }
4035 }
4036 if (Any)
4037 LU.RecomputeRegs(LUIdx, RegUses);
4038 }
4039
4040 DEBUG(dbgs() << "After pre-selection:\n";
4041 print_uses(dbgs()));
4042 }
Dan Gohmane9e08732010-08-29 16:09:42 +00004043}
Dan Gohman20fab452010-05-19 23:43:12 +00004044
Dan Gohmane9e08732010-08-29 16:09:42 +00004045/// NarrowSearchSpaceByCollapsingUnrolledCode - When there are many registers
4046/// for expressions like A, A+1, A+2, etc., allocate a single register for
4047/// them.
4048void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
Jakub Staszak11bd8352013-02-16 16:08:15 +00004049 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4050 return;
Dan Gohman20fab452010-05-19 23:43:12 +00004051
Jakub Staszak11bd8352013-02-16 16:08:15 +00004052 DEBUG(dbgs() << "The search space is too complex.\n"
4053 "Narrowing the search space by assuming that uses separated "
4054 "by a constant offset will use the same registers.\n");
Dan Gohman20fab452010-05-19 23:43:12 +00004055
Jakub Staszak11bd8352013-02-16 16:08:15 +00004056 // This is especially useful for unrolled loops.
Dan Gohman8ec018c2010-05-20 20:00:41 +00004057
Jakub Staszak11bd8352013-02-16 16:08:15 +00004058 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4059 LSRUse &LU = Uses[LUIdx];
Craig Topper77b99412015-05-23 08:01:41 +00004060 for (const Formula &F : LU.Formulae) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004061 if (F.BaseOffset == 0 || (F.Scale != 0 && F.Scale != 1))
Jakub Staszak11bd8352013-02-16 16:08:15 +00004062 continue;
Dan Gohman20fab452010-05-19 23:43:12 +00004063
Jakub Staszak11bd8352013-02-16 16:08:15 +00004064 LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU);
4065 if (!LUThatHas)
4066 continue;
Dan Gohman20fab452010-05-19 23:43:12 +00004067
Jakub Staszak11bd8352013-02-16 16:08:15 +00004068 if (!reconcileNewOffset(*LUThatHas, F.BaseOffset, /*HasBaseReg=*/ false,
4069 LU.Kind, LU.AccessTy))
4070 continue;
Dan Gohman110ed642010-09-01 01:45:53 +00004071
Jakub Staszak11bd8352013-02-16 16:08:15 +00004072 DEBUG(dbgs() << " Deleting use "; LU.print(dbgs()); dbgs() << '\n');
Dan Gohman2fd85d72010-10-08 19:33:26 +00004073
Jakub Staszak11bd8352013-02-16 16:08:15 +00004074 LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
4075
4076 // Update the relocs to reference the new use.
Craig Topper77b99412015-05-23 08:01:41 +00004077 for (LSRFixup &Fixup : Fixups) {
Jakub Staszak11bd8352013-02-16 16:08:15 +00004078 if (Fixup.LUIdx == LUIdx) {
4079 Fixup.LUIdx = LUThatHas - &Uses.front();
4080 Fixup.Offset += F.BaseOffset;
4081 // Add the new offset to LUThatHas' offset list.
4082 if (LUThatHas->Offsets.back() != Fixup.Offset) {
4083 LUThatHas->Offsets.push_back(Fixup.Offset);
4084 if (Fixup.Offset > LUThatHas->MaxOffset)
4085 LUThatHas->MaxOffset = Fixup.Offset;
4086 if (Fixup.Offset < LUThatHas->MinOffset)
4087 LUThatHas->MinOffset = Fixup.Offset;
Dan Gohman20fab452010-05-19 23:43:12 +00004088 }
Jakub Staszak11bd8352013-02-16 16:08:15 +00004089 DEBUG(dbgs() << "New fixup has offset " << Fixup.Offset << '\n');
4090 }
4091 if (Fixup.LUIdx == NumUses-1)
4092 Fixup.LUIdx = LUIdx;
4093 }
4094
4095 // Delete formulae from the new use which are no longer legal.
4096 bool Any = false;
4097 for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
4098 Formula &F = LUThatHas->Formulae[i];
4099 if (!isLegalUse(TTI, LUThatHas->MinOffset, LUThatHas->MaxOffset,
4100 LUThatHas->Kind, LUThatHas->AccessTy, F)) {
4101 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
4102 dbgs() << '\n');
4103 LUThatHas->DeleteFormula(F);
4104 --i;
4105 --e;
4106 Any = true;
Dan Gohman20fab452010-05-19 23:43:12 +00004107 }
4108 }
Dan Gohman20fab452010-05-19 23:43:12 +00004109
Jakub Staszak11bd8352013-02-16 16:08:15 +00004110 if (Any)
4111 LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
4112
4113 // Delete the old use.
4114 DeleteUse(LU, LUIdx);
4115 --LUIdx;
4116 --NumUses;
4117 break;
4118 }
Dan Gohman20fab452010-05-19 23:43:12 +00004119 }
Jakub Staszak11bd8352013-02-16 16:08:15 +00004120
4121 DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
Dan Gohmane9e08732010-08-29 16:09:42 +00004122}
Dan Gohman20fab452010-05-19 23:43:12 +00004123
Andrew Trick8b55b732011-03-14 16:50:06 +00004124/// NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters - Call
Dan Gohman002ff892010-08-29 16:39:22 +00004125/// FilterOutUndesirableDedicatedRegisters again, if necessary, now that
4126/// we've done more filtering, as it may be able to find more formulae to
4127/// eliminate.
4128void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
4129 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4130 DEBUG(dbgs() << "The search space is too complex.\n");
4131
4132 DEBUG(dbgs() << "Narrowing the search space by re-filtering out "
4133 "undesirable dedicated registers.\n");
4134
4135 FilterOutUndesirableDedicatedRegisters();
4136
4137 DEBUG(dbgs() << "After pre-selection:\n";
4138 print_uses(dbgs()));
4139 }
4140}
4141
Dan Gohmane9e08732010-08-29 16:09:42 +00004142/// NarrowSearchSpaceByPickingWinnerRegs - Pick a register which seems likely
4143/// to be profitable, and then in any use which has any reference to that
4144/// register, delete all formulae which do not reference that register.
4145void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
Dan Gohmana4ca28a2010-05-20 20:52:00 +00004146 // With all other options exhausted, loop until the system is simple
4147 // enough to handle.
Dan Gohman45774ce2010-02-12 10:34:29 +00004148 SmallPtrSet<const SCEV *, 4> Taken;
Dan Gohmana4eca052010-05-18 22:51:59 +00004149 while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004150 // Ok, we have too many of formulae on our hands to conveniently handle.
4151 // Use a rough heuristic to thin out the list.
Dan Gohman63e90152010-05-18 22:41:32 +00004152 DEBUG(dbgs() << "The search space is too complex.\n");
Dan Gohman45774ce2010-02-12 10:34:29 +00004153
4154 // Pick the register which is used by the most LSRUses, which is likely
4155 // to be a good reuse register candidate.
Craig Topperf40110f2014-04-25 05:29:35 +00004156 const SCEV *Best = nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +00004157 unsigned BestNum = 0;
Craig Topper77b99412015-05-23 08:01:41 +00004158 for (const SCEV *Reg : RegUses) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004159 if (Taken.count(Reg))
4160 continue;
4161 if (!Best)
4162 Best = Reg;
4163 else {
4164 unsigned Count = RegUses.getUsedByIndices(Reg).count();
4165 if (Count > BestNum) {
4166 Best = Reg;
4167 BestNum = Count;
4168 }
4169 }
4170 }
4171
4172 DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
Dan Gohman8b0a4192010-03-01 17:49:51 +00004173 << " will yield profitable reuse.\n");
Dan Gohman45774ce2010-02-12 10:34:29 +00004174 Taken.insert(Best);
4175
4176 // In any use with formulae which references this register, delete formulae
4177 // which don't reference it.
Dan Gohman4cf99b52010-05-18 23:42:37 +00004178 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4179 LSRUse &LU = Uses[LUIdx];
Dan Gohman45774ce2010-02-12 10:34:29 +00004180 if (!LU.Regs.count(Best)) continue;
4181
Dan Gohman4cf99b52010-05-18 23:42:37 +00004182 bool Any = false;
Dan Gohman45774ce2010-02-12 10:34:29 +00004183 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4184 Formula &F = LU.Formulae[i];
4185 if (!F.referencesReg(Best)) {
4186 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
Dan Gohmanf1c7b1b2010-05-18 22:39:15 +00004187 LU.DeleteFormula(F);
Dan Gohman45774ce2010-02-12 10:34:29 +00004188 --e;
4189 --i;
Dan Gohman4cf99b52010-05-18 23:42:37 +00004190 Any = true;
Dan Gohmand0800242010-05-07 23:36:59 +00004191 assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
Dan Gohman45774ce2010-02-12 10:34:29 +00004192 continue;
4193 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004194 }
Dan Gohman4cf99b52010-05-18 23:42:37 +00004195
4196 if (Any)
4197 LU.RecomputeRegs(LUIdx, RegUses);
Dan Gohman45774ce2010-02-12 10:34:29 +00004198 }
4199
4200 DEBUG(dbgs() << "After pre-selection:\n";
4201 print_uses(dbgs()));
4202 }
4203}
4204
Dan Gohmane9e08732010-08-29 16:09:42 +00004205/// NarrowSearchSpaceUsingHeuristics - If there are an extraordinary number of
4206/// formulae to choose from, use some rough heuristics to prune down the number
4207/// of formulae. This keeps the main solver from taking an extraordinary amount
4208/// of time in some worst-case scenarios.
4209void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
4210 NarrowSearchSpaceByDetectingSupersets();
4211 NarrowSearchSpaceByCollapsingUnrolledCode();
Dan Gohman002ff892010-08-29 16:39:22 +00004212 NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
Dan Gohmane9e08732010-08-29 16:09:42 +00004213 NarrowSearchSpaceByPickingWinnerRegs();
4214}
4215
Dan Gohman45774ce2010-02-12 10:34:29 +00004216/// SolveRecurse - This is the recursive solver.
4217void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
4218 Cost &SolutionCost,
4219 SmallVectorImpl<const Formula *> &Workspace,
4220 const Cost &CurCost,
4221 const SmallPtrSet<const SCEV *, 16> &CurRegs,
4222 DenseSet<const SCEV *> &VisitedRegs) const {
4223 // Some ideas:
4224 // - prune more:
4225 // - use more aggressive filtering
4226 // - sort the formula so that the most profitable solutions are found first
4227 // - sort the uses too
4228 // - search faster:
Dan Gohman8b0a4192010-03-01 17:49:51 +00004229 // - don't compute a cost, and then compare. compare while computing a cost
Dan Gohman45774ce2010-02-12 10:34:29 +00004230 // and bail early.
4231 // - track register sets with SmallBitVector
4232
4233 const LSRUse &LU = Uses[Workspace.size()];
4234
4235 // If this use references any register that's already a part of the
4236 // in-progress solution, consider it a requirement that a formula must
4237 // reference that register in order to be considered. This prunes out
4238 // unprofitable searching.
4239 SmallSetVector<const SCEV *, 4> ReqRegs;
Craig Topper46276792014-08-24 23:23:06 +00004240 for (const SCEV *S : CurRegs)
4241 if (LU.Regs.count(S))
4242 ReqRegs.insert(S);
Dan Gohman45774ce2010-02-12 10:34:29 +00004243
4244 SmallPtrSet<const SCEV *, 16> NewRegs;
4245 Cost NewCost;
Craig Topper77b99412015-05-23 08:01:41 +00004246 for (const Formula &F : LU.Formulae) {
Adam Nemetdeab6f92014-04-29 18:25:28 +00004247 // Ignore formulae which may not be ideal in terms of register reuse of
4248 // ReqRegs. The formula should use all required registers before
4249 // introducing new ones.
4250 int NumReqRegsToFind = std::min(F.getNumRegs(), ReqRegs.size());
Craig Topper77b99412015-05-23 08:01:41 +00004251 for (const SCEV *Reg : ReqRegs) {
Adam Nemetdeab6f92014-04-29 18:25:28 +00004252 if ((F.ScaledReg && F.ScaledReg == Reg) ||
4253 std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) !=
Andrew Tricke3502cb2012-03-22 22:42:51 +00004254 F.BaseRegs.end()) {
Adam Nemetdeab6f92014-04-29 18:25:28 +00004255 --NumReqRegsToFind;
4256 if (NumReqRegsToFind == 0)
4257 break;
Andrew Tricke3502cb2012-03-22 22:42:51 +00004258 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004259 }
Adam Nemetdeab6f92014-04-29 18:25:28 +00004260 if (NumReqRegsToFind != 0) {
Andrew Tricke3502cb2012-03-22 22:42:51 +00004261 // If none of the formulae satisfied the required registers, then we could
4262 // clear ReqRegs and try again. Currently, we simply give up in this case.
4263 continue;
4264 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004265
4266 // Evaluate the cost of the current formula. If it's already worse than
4267 // the current best, prune the search at that point.
4268 NewCost = CurCost;
4269 NewRegs = CurRegs;
Quentin Colombet8aa7abe2013-05-31 17:20:29 +00004270 NewCost.RateFormula(TTI, F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT,
4271 LU);
Dan Gohman45774ce2010-02-12 10:34:29 +00004272 if (NewCost < SolutionCost) {
4273 Workspace.push_back(&F);
4274 if (Workspace.size() != Uses.size()) {
4275 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
4276 NewRegs, VisitedRegs);
4277 if (F.getNumRegs() == 1 && Workspace.size() == 1)
4278 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
4279 } else {
4280 DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
Andrew Trick4dc3eff2012-01-09 18:58:16 +00004281 dbgs() << ".\n Regs:";
Craig Topper46276792014-08-24 23:23:06 +00004282 for (const SCEV *S : NewRegs)
4283 dbgs() << ' ' << *S;
Dan Gohman45774ce2010-02-12 10:34:29 +00004284 dbgs() << '\n');
4285
4286 SolutionCost = NewCost;
4287 Solution = Workspace;
4288 }
4289 Workspace.pop_back();
4290 }
Dan Gohman5b18f032010-02-13 02:06:02 +00004291 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004292}
4293
Dan Gohmana4ca28a2010-05-20 20:52:00 +00004294/// Solve - Choose one formula from each use. Return the results in the given
4295/// Solution vector.
Dan Gohman45774ce2010-02-12 10:34:29 +00004296void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
4297 SmallVector<const Formula *, 8> Workspace;
4298 Cost SolutionCost;
Tim Northoverbc6659c2014-01-22 13:27:00 +00004299 SolutionCost.Lose();
Dan Gohman45774ce2010-02-12 10:34:29 +00004300 Cost CurCost;
4301 SmallPtrSet<const SCEV *, 16> CurRegs;
4302 DenseSet<const SCEV *> VisitedRegs;
4303 Workspace.reserve(Uses.size());
4304
Dan Gohman8ec018c2010-05-20 20:00:41 +00004305 // SolveRecurse does all the work.
Dan Gohman45774ce2010-02-12 10:34:29 +00004306 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
4307 CurRegs, VisitedRegs);
Andrew Trick58124392011-09-27 00:44:14 +00004308 if (Solution.empty()) {
4309 DEBUG(dbgs() << "\nNo Satisfactory Solution\n");
4310 return;
4311 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004312
4313 // Ok, we've now made all our decisions.
4314 DEBUG(dbgs() << "\n"
4315 "The chosen solution requires "; SolutionCost.print(dbgs());
4316 dbgs() << ":\n";
4317 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
4318 dbgs() << " ";
4319 Uses[i].print(dbgs());
4320 dbgs() << "\n"
4321 " ";
4322 Solution[i]->print(dbgs());
4323 dbgs() << '\n';
4324 });
Dan Gohman6295f2e2010-05-20 20:59:23 +00004325
4326 assert(Solution.size() == Uses.size() && "Malformed solution!");
Dan Gohman45774ce2010-02-12 10:34:29 +00004327}
4328
Dan Gohman607e02b2010-04-09 22:07:05 +00004329/// HoistInsertPosition - Helper for AdjustInsertPositionForExpand. Climb up
4330/// the dominator tree far as we can go while still being dominated by the
4331/// input positions. This helps canonicalize the insert position, which
4332/// encourages sharing.
4333BasicBlock::iterator
4334LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
4335 const SmallVectorImpl<Instruction *> &Inputs)
4336 const {
4337 for (;;) {
4338 const Loop *IPLoop = LI.getLoopFor(IP->getParent());
4339 unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
4340
4341 BasicBlock *IDom;
Dan Gohman8ce95cc2010-05-20 20:00:25 +00004342 for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) {
Dan Gohman9b48b852010-05-20 22:46:54 +00004343 if (!Rung) return IP;
Dan Gohman8ce95cc2010-05-20 20:00:25 +00004344 Rung = Rung->getIDom();
4345 if (!Rung) return IP;
4346 IDom = Rung->getBlock();
Dan Gohman607e02b2010-04-09 22:07:05 +00004347
4348 // Don't climb into a loop though.
4349 const Loop *IDomLoop = LI.getLoopFor(IDom);
4350 unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
4351 if (IDomDepth <= IPLoopDepth &&
4352 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
4353 break;
4354 }
4355
4356 bool AllDominate = true;
Craig Topperf40110f2014-04-25 05:29:35 +00004357 Instruction *BetterPos = nullptr;
Dan Gohman607e02b2010-04-09 22:07:05 +00004358 Instruction *Tentative = IDom->getTerminator();
Craig Topper77b99412015-05-23 08:01:41 +00004359 for (Instruction *Inst : Inputs) {
Dan Gohman607e02b2010-04-09 22:07:05 +00004360 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
4361 AllDominate = false;
4362 break;
4363 }
4364 // Attempt to find an insert position in the middle of the block,
4365 // instead of at the end, so that it can be used for other expansions.
4366 if (IDom == Inst->getParent() &&
Rafael Espindoladd489312012-04-30 03:53:06 +00004367 (!BetterPos || !DT.dominates(Inst, BetterPos)))
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00004368 BetterPos = std::next(BasicBlock::iterator(Inst));
Dan Gohman607e02b2010-04-09 22:07:05 +00004369 }
4370 if (!AllDominate)
4371 break;
4372 if (BetterPos)
4373 IP = BetterPos;
4374 else
4375 IP = Tentative;
4376 }
4377
4378 return IP;
4379}
4380
4381/// AdjustInsertPositionForExpand - Determine an input position which will be
Dan Gohmand2df6432010-04-09 02:00:38 +00004382/// dominated by the operands and which will dominate the result.
4383BasicBlock::iterator
Andrew Trickc908b432012-01-20 07:41:13 +00004384LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator LowestIP,
Dan Gohman607e02b2010-04-09 22:07:05 +00004385 const LSRFixup &LF,
Andrew Trickc908b432012-01-20 07:41:13 +00004386 const LSRUse &LU,
4387 SCEVExpander &Rewriter) const {
Dan Gohmand2df6432010-04-09 02:00:38 +00004388 // Collect some instructions which must be dominated by the
Dan Gohmand006ab92010-04-07 22:27:08 +00004389 // expanding replacement. These must be dominated by any operands that
Dan Gohman45774ce2010-02-12 10:34:29 +00004390 // will be required in the expansion.
4391 SmallVector<Instruction *, 4> Inputs;
4392 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
4393 Inputs.push_back(I);
4394 if (LU.Kind == LSRUse::ICmpZero)
4395 if (Instruction *I =
4396 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
4397 Inputs.push_back(I);
Dan Gohmand006ab92010-04-07 22:27:08 +00004398 if (LF.PostIncLoops.count(L)) {
4399 if (LF.isUseFullyOutsideLoop(L))
Dan Gohman52f55632010-03-02 01:59:21 +00004400 Inputs.push_back(L->getLoopLatch()->getTerminator());
4401 else
4402 Inputs.push_back(IVIncInsertPos);
4403 }
Dan Gohman45065392010-04-08 05:57:57 +00004404 // The expansion must also be dominated by the increment positions of any
4405 // loops it for which it is using post-inc mode.
Craig Topper77b99412015-05-23 08:01:41 +00004406 for (const Loop *PIL : LF.PostIncLoops) {
Dan Gohman45065392010-04-08 05:57:57 +00004407 if (PIL == L) continue;
4408
Dan Gohman607e02b2010-04-09 22:07:05 +00004409 // Be dominated by the loop exit.
Dan Gohman45065392010-04-08 05:57:57 +00004410 SmallVector<BasicBlock *, 4> ExitingBlocks;
4411 PIL->getExitingBlocks(ExitingBlocks);
4412 if (!ExitingBlocks.empty()) {
4413 BasicBlock *BB = ExitingBlocks[0];
4414 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
4415 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
4416 Inputs.push_back(BB->getTerminator());
4417 }
4418 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004419
Andrew Trickc908b432012-01-20 07:41:13 +00004420 assert(!isa<PHINode>(LowestIP) && !isa<LandingPadInst>(LowestIP)
4421 && !isa<DbgInfoIntrinsic>(LowestIP) &&
4422 "Insertion point must be a normal instruction");
4423
Dan Gohman45774ce2010-02-12 10:34:29 +00004424 // Then, climb up the immediate dominator tree as far as we can go while
4425 // still being dominated by the input positions.
Andrew Trickc908b432012-01-20 07:41:13 +00004426 BasicBlock::iterator IP = HoistInsertPosition(LowestIP, Inputs);
Dan Gohmand2df6432010-04-09 02:00:38 +00004427
4428 // Don't insert instructions before PHI nodes.
Dan Gohman45774ce2010-02-12 10:34:29 +00004429 while (isa<PHINode>(IP)) ++IP;
Dan Gohmand2df6432010-04-09 02:00:38 +00004430
Bill Wendling86c5cbe2011-08-24 21:06:46 +00004431 // Ignore landingpad instructions.
4432 while (isa<LandingPadInst>(IP)) ++IP;
4433
Dan Gohmand2df6432010-04-09 02:00:38 +00004434 // Ignore debug intrinsics.
Dan Gohmand42e09d2010-03-26 00:33:27 +00004435 while (isa<DbgInfoIntrinsic>(IP)) ++IP;
Dan Gohman45774ce2010-02-12 10:34:29 +00004436
Andrew Trickc908b432012-01-20 07:41:13 +00004437 // Set IP below instructions recently inserted by SCEVExpander. This keeps the
4438 // IP consistent across expansions and allows the previously inserted
4439 // instructions to be reused by subsequent expansion.
4440 while (Rewriter.isInsertedInstruction(IP) && IP != LowestIP) ++IP;
4441
Dan Gohmand2df6432010-04-09 02:00:38 +00004442 return IP;
4443}
4444
Dan Gohmana4ca28a2010-05-20 20:52:00 +00004445/// Expand - Emit instructions for the leading candidate expression for this
4446/// LSRUse (this is called "expanding").
Dan Gohmand2df6432010-04-09 02:00:38 +00004447Value *LSRInstance::Expand(const LSRFixup &LF,
4448 const Formula &F,
4449 BasicBlock::iterator IP,
4450 SCEVExpander &Rewriter,
4451 SmallVectorImpl<WeakVH> &DeadInsts) const {
4452 const LSRUse &LU = Uses[LF.LUIdx];
Andrew Trick57243da2013-10-25 21:35:56 +00004453 if (LU.RigidFormula)
4454 return LF.OperandValToReplace;
Dan Gohmand2df6432010-04-09 02:00:38 +00004455
4456 // Determine an input position which will be dominated by the operands and
4457 // which will dominate the result.
Andrew Trickc908b432012-01-20 07:41:13 +00004458 IP = AdjustInsertPositionForExpand(IP, LF, LU, Rewriter);
Dan Gohmand2df6432010-04-09 02:00:38 +00004459
Dan Gohman45774ce2010-02-12 10:34:29 +00004460 // Inform the Rewriter if we have a post-increment use, so that it can
4461 // perform an advantageous expansion.
Dan Gohmand006ab92010-04-07 22:27:08 +00004462 Rewriter.setPostInc(LF.PostIncLoops);
Dan Gohman45774ce2010-02-12 10:34:29 +00004463
4464 // This is the type that the user actually needs.
Chris Lattner229907c2011-07-18 04:54:35 +00004465 Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00004466 // This will be the type that we'll initially expand to.
Chris Lattner229907c2011-07-18 04:54:35 +00004467 Type *Ty = F.getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00004468 if (!Ty)
4469 // No type known; just expand directly to the ultimate type.
4470 Ty = OpTy;
4471 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
4472 // Expand directly to the ultimate type if it's the right size.
4473 Ty = OpTy;
4474 // This is the type to do integer arithmetic in.
Chris Lattner229907c2011-07-18 04:54:35 +00004475 Type *IntTy = SE.getEffectiveSCEVType(Ty);
Dan Gohman45774ce2010-02-12 10:34:29 +00004476
4477 // Build up a list of operands to add together to form the full base.
4478 SmallVector<const SCEV *, 8> Ops;
4479
4480 // Expand the BaseRegs portion.
Craig Topper77b99412015-05-23 08:01:41 +00004481 for (const SCEV *Reg : F.BaseRegs) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004482 assert(!Reg->isZero() && "Zero allocated in a base register!");
4483
Dan Gohmand006ab92010-04-07 22:27:08 +00004484 // If we're expanding for a post-inc user, make the post-inc adjustment.
4485 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
4486 Reg = TransformForPostIncUse(Denormalize, Reg,
4487 LF.UserInst, LF.OperandValToReplace,
4488 Loops, SE, DT);
Dan Gohman45774ce2010-02-12 10:34:29 +00004489
Craig Topperf40110f2014-04-25 05:29:35 +00004490 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr, IP)));
Dan Gohman45774ce2010-02-12 10:34:29 +00004491 }
4492
4493 // Expand the ScaledReg portion.
Craig Topperf40110f2014-04-25 05:29:35 +00004494 Value *ICmpScaledV = nullptr;
Chandler Carruth6e479322013-01-07 15:04:40 +00004495 if (F.Scale != 0) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004496 const SCEV *ScaledS = F.ScaledReg;
4497
Dan Gohmand006ab92010-04-07 22:27:08 +00004498 // If we're expanding for a post-inc user, make the post-inc adjustment.
4499 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
4500 ScaledS = TransformForPostIncUse(Denormalize, ScaledS,
4501 LF.UserInst, LF.OperandValToReplace,
4502 Loops, SE, DT);
Dan Gohman45774ce2010-02-12 10:34:29 +00004503
4504 if (LU.Kind == LSRUse::ICmpZero) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004505 // Expand ScaleReg as if it was part of the base regs.
4506 if (F.Scale == 1)
4507 Ops.push_back(
4508 SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, IP)));
4509 else {
4510 // An interesting way of "folding" with an icmp is to use a negated
4511 // scale, which we'll implement by inserting it into the other operand
4512 // of the icmp.
4513 assert(F.Scale == -1 &&
4514 "The only scale supported by ICmpZero uses is -1!");
4515 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr, IP);
4516 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004517 } else {
4518 // Otherwise just expand the scaled register and an explicit scale,
4519 // which is expected to be matched as part of the address.
Andrew Trick8370c7c2012-06-15 20:07:29 +00004520
4521 // Flush the operand list to suppress SCEVExpander hoisting address modes.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004522 // Unless the addressing mode will not be folded.
4523 if (!Ops.empty() && LU.Kind == LSRUse::Address &&
4524 isAMCompletelyFolded(TTI, LU, F)) {
Andrew Trick8370c7c2012-06-15 20:07:29 +00004525 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
4526 Ops.clear();
4527 Ops.push_back(SE.getUnknown(FullV));
4528 }
Craig Topperf40110f2014-04-25 05:29:35 +00004529 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, IP));
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004530 if (F.Scale != 1)
4531 ScaledS =
4532 SE.getMulExpr(ScaledS, SE.getConstant(ScaledS->getType(), F.Scale));
Dan Gohman45774ce2010-02-12 10:34:29 +00004533 Ops.push_back(ScaledS);
4534 }
4535 }
4536
Dan Gohman29707de2010-03-03 05:29:13 +00004537 // Expand the GV portion.
Chandler Carruth6e479322013-01-07 15:04:40 +00004538 if (F.BaseGV) {
Dan Gohman29707de2010-03-03 05:29:13 +00004539 // Flush the operand list to suppress SCEVExpander hoisting.
Andrew Trick8370c7c2012-06-15 20:07:29 +00004540 if (!Ops.empty()) {
4541 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
4542 Ops.clear();
4543 Ops.push_back(SE.getUnknown(FullV));
4544 }
Chandler Carruth6e479322013-01-07 15:04:40 +00004545 Ops.push_back(SE.getUnknown(F.BaseGV));
Andrew Trick8370c7c2012-06-15 20:07:29 +00004546 }
4547
4548 // Flush the operand list to suppress SCEVExpander hoisting of both folded and
4549 // unfolded offsets. LSR assumes they both live next to their uses.
4550 if (!Ops.empty()) {
Dan Gohman29707de2010-03-03 05:29:13 +00004551 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
4552 Ops.clear();
4553 Ops.push_back(SE.getUnknown(FullV));
4554 }
4555
4556 // Expand the immediate portion.
Chandler Carruth6e479322013-01-07 15:04:40 +00004557 int64_t Offset = (uint64_t)F.BaseOffset + LF.Offset;
Dan Gohman45774ce2010-02-12 10:34:29 +00004558 if (Offset != 0) {
4559 if (LU.Kind == LSRUse::ICmpZero) {
4560 // The other interesting way of "folding" with an ICmpZero is to use a
4561 // negated immediate.
4562 if (!ICmpScaledV)
Eli Friedmanb46345d2011-10-13 23:48:33 +00004563 ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset);
Dan Gohman45774ce2010-02-12 10:34:29 +00004564 else {
4565 Ops.push_back(SE.getUnknown(ICmpScaledV));
4566 ICmpScaledV = ConstantInt::get(IntTy, Offset);
4567 }
4568 } else {
4569 // Just add the immediate values. These again are expected to be matched
4570 // as part of the address.
Dan Gohman29707de2010-03-03 05:29:13 +00004571 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
Dan Gohman45774ce2010-02-12 10:34:29 +00004572 }
4573 }
4574
Dan Gohman6136e942011-05-03 00:46:49 +00004575 // Expand the unfolded offset portion.
4576 int64_t UnfoldedOffset = F.UnfoldedOffset;
4577 if (UnfoldedOffset != 0) {
4578 // Just add the immediate values.
4579 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy,
4580 UnfoldedOffset)));
4581 }
4582
Dan Gohman45774ce2010-02-12 10:34:29 +00004583 // Emit instructions summing all the operands.
4584 const SCEV *FullS = Ops.empty() ?
Dan Gohman1d2ded72010-05-03 22:09:21 +00004585 SE.getConstant(IntTy, 0) :
Dan Gohman45774ce2010-02-12 10:34:29 +00004586 SE.getAddExpr(Ops);
4587 Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
4588
4589 // We're done expanding now, so reset the rewriter.
Dan Gohmand006ab92010-04-07 22:27:08 +00004590 Rewriter.clearPostInc();
Dan Gohman45774ce2010-02-12 10:34:29 +00004591
4592 // An ICmpZero Formula represents an ICmp which we're handling as a
4593 // comparison against zero. Now that we've expanded an expression for that
4594 // form, update the ICmp's other operand.
4595 if (LU.Kind == LSRUse::ICmpZero) {
4596 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004597 DeadInsts.emplace_back(CI->getOperand(1));
Chandler Carruth6e479322013-01-07 15:04:40 +00004598 assert(!F.BaseGV && "ICmp does not support folding a global value and "
Dan Gohman45774ce2010-02-12 10:34:29 +00004599 "a scale at the same time!");
Chandler Carruth6e479322013-01-07 15:04:40 +00004600 if (F.Scale == -1) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004601 if (ICmpScaledV->getType() != OpTy) {
4602 Instruction *Cast =
4603 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
4604 OpTy, false),
4605 ICmpScaledV, OpTy, "tmp", CI);
4606 ICmpScaledV = Cast;
4607 }
4608 CI->setOperand(1, ICmpScaledV);
4609 } else {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004610 // A scale of 1 means that the scale has been expanded as part of the
4611 // base regs.
4612 assert((F.Scale == 0 || F.Scale == 1) &&
Dan Gohman45774ce2010-02-12 10:34:29 +00004613 "ICmp does not support folding a global value and "
4614 "a scale at the same time!");
4615 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
4616 -(uint64_t)Offset);
4617 if (C->getType() != OpTy)
4618 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4619 OpTy, false),
4620 C, OpTy);
4621
4622 CI->setOperand(1, C);
4623 }
4624 }
4625
4626 return FullV;
4627}
4628
Dan Gohman6deab962010-02-16 20:25:07 +00004629/// RewriteForPHI - Helper for Rewrite. PHI nodes are special because the use
4630/// of their operands effectively happens in their predecessor blocks, so the
4631/// expression may need to be expanded in multiple places.
4632void LSRInstance::RewriteForPHI(PHINode *PN,
4633 const LSRFixup &LF,
4634 const Formula &F,
Dan Gohman6deab962010-02-16 20:25:07 +00004635 SCEVExpander &Rewriter,
4636 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman6deab962010-02-16 20:25:07 +00004637 Pass *P) const {
4638 DenseMap<BasicBlock *, Value *> Inserted;
4639 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4640 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
4641 BasicBlock *BB = PN->getIncomingBlock(i);
4642
4643 // If this is a critical edge, split the edge so that we do not insert
4644 // the code on all predecessor/successor paths. We do this unless this
4645 // is the canonical backedge for this loop, which complicates post-inc
4646 // users.
4647 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
Dan Gohmande7f6992011-02-08 00:55:13 +00004648 !isa<IndirectBrInst>(BB->getTerminator())) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00004649 BasicBlock *Parent = PN->getParent();
4650 Loop *PNLoop = LI.getLoopFor(Parent);
4651 if (!PNLoop || Parent != PNLoop->getHeader()) {
Dan Gohmande7f6992011-02-08 00:55:13 +00004652 // Split the critical edge.
Craig Topperf40110f2014-04-25 05:29:35 +00004653 BasicBlock *NewBB = nullptr;
Bill Wendling3fb137f2011-08-25 05:55:40 +00004654 if (!Parent->isLandingPad()) {
Chandler Carruth37df2cf2015-01-19 12:09:11 +00004655 NewBB = SplitCriticalEdge(BB, Parent,
4656 CriticalEdgeSplittingOptions(&DT, &LI)
4657 .setMergeIdenticalEdges()
4658 .setDontDeleteUselessPHIs());
Bill Wendling3fb137f2011-08-25 05:55:40 +00004659 } else {
4660 SmallVector<BasicBlock*, 2> NewBBs;
Chandler Carruth96ada252015-07-22 09:52:54 +00004661 SplitLandingPadPredecessors(Parent, BB, "", "", NewBBs, &DT, &LI);
Bill Wendling3fb137f2011-08-25 05:55:40 +00004662 NewBB = NewBBs[0];
4663 }
Andrew Trick402edbb2012-09-18 17:51:33 +00004664 // If NewBB==NULL, then SplitCriticalEdge refused to split because all
4665 // phi predecessors are identical. The simple thing to do is skip
4666 // splitting in this case rather than complicate the API.
4667 if (NewBB) {
4668 // If PN is outside of the loop and BB is in the loop, we want to
4669 // move the block to be immediately before the PHI block, not
4670 // immediately after BB.
4671 if (L->contains(BB) && !L->contains(PN))
4672 NewBB->moveBefore(PN->getParent());
Dan Gohman6deab962010-02-16 20:25:07 +00004673
Andrew Trick402edbb2012-09-18 17:51:33 +00004674 // Splitting the edge can reduce the number of PHI entries we have.
4675 e = PN->getNumIncomingValues();
4676 BB = NewBB;
4677 i = PN->getBasicBlockIndex(BB);
4678 }
Dan Gohmande7f6992011-02-08 00:55:13 +00004679 }
Dan Gohman6deab962010-02-16 20:25:07 +00004680 }
4681
4682 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
Craig Topperf40110f2014-04-25 05:29:35 +00004683 Inserted.insert(std::make_pair(BB, static_cast<Value *>(nullptr)));
Dan Gohman6deab962010-02-16 20:25:07 +00004684 if (!Pair.second)
4685 PN->setIncomingValue(i, Pair.first->second);
4686 else {
Dan Gohman8c16b382010-02-22 04:11:59 +00004687 Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
Dan Gohman6deab962010-02-16 20:25:07 +00004688
4689 // If this is reuse-by-noop-cast, insert the noop cast.
Chris Lattner229907c2011-07-18 04:54:35 +00004690 Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman6deab962010-02-16 20:25:07 +00004691 if (FullV->getType() != OpTy)
4692 FullV =
4693 CastInst::Create(CastInst::getCastOpcode(FullV, false,
4694 OpTy, false),
4695 FullV, LF.OperandValToReplace->getType(),
4696 "tmp", BB->getTerminator());
4697
4698 PN->setIncomingValue(i, FullV);
4699 Pair.first->second = FullV;
4700 }
4701 }
4702}
4703
Dan Gohman45774ce2010-02-12 10:34:29 +00004704/// Rewrite - Emit instructions for the leading candidate expression for this
4705/// LSRUse (this is called "expanding"), and update the UserInst to reference
4706/// the newly expanded value.
4707void LSRInstance::Rewrite(const LSRFixup &LF,
4708 const Formula &F,
Dan Gohman45774ce2010-02-12 10:34:29 +00004709 SCEVExpander &Rewriter,
4710 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman45774ce2010-02-12 10:34:29 +00004711 Pass *P) const {
Dan Gohman45774ce2010-02-12 10:34:29 +00004712 // First, find an insertion point that dominates UserInst. For PHI nodes,
4713 // find the nearest block which dominates all the relevant uses.
4714 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
Dan Gohman8c16b382010-02-22 04:11:59 +00004715 RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
Dan Gohman45774ce2010-02-12 10:34:29 +00004716 } else {
Dan Gohman8c16b382010-02-22 04:11:59 +00004717 Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
Dan Gohman45774ce2010-02-12 10:34:29 +00004718
4719 // If this is reuse-by-noop-cast, insert the noop cast.
Chris Lattner229907c2011-07-18 04:54:35 +00004720 Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00004721 if (FullV->getType() != OpTy) {
4722 Instruction *Cast =
4723 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
4724 FullV, OpTy, "tmp", LF.UserInst);
4725 FullV = Cast;
4726 }
4727
4728 // Update the user. ICmpZero is handled specially here (for now) because
4729 // Expand may have updated one of the operands of the icmp already, and
4730 // its new value may happen to be equal to LF.OperandValToReplace, in
4731 // which case doing replaceUsesOfWith leads to replacing both operands
4732 // with the same value. TODO: Reorganize this.
4733 if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
4734 LF.UserInst->setOperand(0, FullV);
4735 else
4736 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
4737 }
4738
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004739 DeadInsts.emplace_back(LF.OperandValToReplace);
Dan Gohman45774ce2010-02-12 10:34:29 +00004740}
4741
Dan Gohmana4ca28a2010-05-20 20:52:00 +00004742/// ImplementSolution - Rewrite all the fixup locations with new values,
4743/// following the chosen solution.
Dan Gohman45774ce2010-02-12 10:34:29 +00004744void
4745LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
4746 Pass *P) {
4747 // Keep track of instructions we may have made dead, so that
4748 // we can remove them after we are done working.
4749 SmallVector<WeakVH, 16> DeadInsts;
4750
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004751 SCEVExpander Rewriter(SE, L->getHeader()->getModule()->getDataLayout(),
4752 "lsr");
Andrew Trick4dc3eff2012-01-09 18:58:16 +00004753#ifndef NDEBUG
4754 Rewriter.setDebugType(DEBUG_TYPE);
4755#endif
Dan Gohman45774ce2010-02-12 10:34:29 +00004756 Rewriter.disableCanonicalMode();
Andrew Trick7fb669a2011-10-07 23:46:21 +00004757 Rewriter.enableLSRMode();
Dan Gohman45774ce2010-02-12 10:34:29 +00004758 Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
4759
Andrew Trickd5d2db92012-01-10 01:45:08 +00004760 // Mark phi nodes that terminate chains so the expander tries to reuse them.
Craig Topper77b99412015-05-23 08:01:41 +00004761 for (const IVChain &Chain : IVChainVec) {
4762 if (PHINode *PN = dyn_cast<PHINode>(Chain.tailUserInst()))
Andrew Trickd5d2db92012-01-10 01:45:08 +00004763 Rewriter.setChainedPhi(PN);
4764 }
4765
Dan Gohman45774ce2010-02-12 10:34:29 +00004766 // Expand the new value definitions and update the users.
Craig Topper77b99412015-05-23 08:01:41 +00004767 for (const LSRFixup &Fixup : Fixups) {
Dan Gohman927bcaa2010-05-20 20:33:18 +00004768 Rewrite(Fixup, *Solution[Fixup.LUIdx], Rewriter, DeadInsts, P);
Dan Gohman45774ce2010-02-12 10:34:29 +00004769
4770 Changed = true;
4771 }
4772
Craig Topper77b99412015-05-23 08:01:41 +00004773 for (const IVChain &Chain : IVChainVec) {
4774 GenerateIVChain(Chain, Rewriter, DeadInsts);
Andrew Trick248d4102012-01-09 21:18:52 +00004775 Changed = true;
4776 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004777 // Clean up after ourselves. This must be done before deleting any
4778 // instructions.
4779 Rewriter.clear();
4780
4781 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
4782}
4783
Chandler Carruth26c59fa2013-01-07 14:41:08 +00004784LSRInstance::LSRInstance(Loop *L, Pass *P)
4785 : IU(P->getAnalysis<IVUsers>()), SE(P->getAnalysis<ScalarEvolution>()),
Chandler Carruth73523022014-01-13 13:07:17 +00004786 DT(P->getAnalysis<DominatorTreeWrapperPass>().getDomTree()),
Chandler Carruth4f8f3072015-01-17 14:16:18 +00004787 LI(P->getAnalysis<LoopInfoWrapperPass>().getLoopInfo()),
Chandler Carruthfdb9c572015-02-01 12:01:35 +00004788 TTI(P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
4789 *L->getHeader()->getParent())),
4790 L(L), Changed(false), IVIncInsertPos(nullptr) {
Dan Gohmana83ac2d2009-11-05 21:11:53 +00004791 // If LoopSimplify form is not available, stay out of trouble.
Andrew Trick732ad802012-01-07 03:16:50 +00004792 if (!L->isLoopSimplifyForm())
4793 return;
Dan Gohmana83ac2d2009-11-05 21:11:53 +00004794
Andrew Trick070e5402012-03-16 03:16:56 +00004795 // If there's no interesting work to be done, bail early.
4796 if (IU.empty()) return;
4797
Andrew Trick19f80c12012-04-18 04:00:10 +00004798 // If there's too much analysis to be done, bail early. We won't be able to
4799 // model the problem anyway.
4800 unsigned NumUsers = 0;
Craig Topper77b99412015-05-23 08:01:41 +00004801 for (const IVStrideUse &U : IU) {
Andrew Trick19f80c12012-04-18 04:00:10 +00004802 if (++NumUsers > MaxIVUsers) {
Craig Topper37d0d862015-05-23 08:20:33 +00004803 (void)U;
Craig Topper77b99412015-05-23 08:01:41 +00004804 DEBUG(dbgs() << "LSR skipping loop, too many IV Users in " << U << "\n");
Andrew Trick19f80c12012-04-18 04:00:10 +00004805 return;
4806 }
4807 }
4808
Andrew Trick070e5402012-03-16 03:16:56 +00004809#ifndef NDEBUG
Andrew Trick12728f02012-01-17 06:45:52 +00004810 // All dominating loops must have preheaders, or SCEVExpander may not be able
4811 // to materialize an AddRecExpr whose Start is an outer AddRecExpr.
4812 //
Andrew Trick070e5402012-03-16 03:16:56 +00004813 // IVUsers analysis should only create users that are dominated by simple loop
4814 // headers. Since this loop should dominate all of its users, its user list
4815 // should be empty if this loop itself is not within a simple loop nest.
Andrew Trick12728f02012-01-17 06:45:52 +00004816 for (DomTreeNode *Rung = DT.getNode(L->getLoopPreheader());
4817 Rung; Rung = Rung->getIDom()) {
4818 BasicBlock *BB = Rung->getBlock();
4819 const Loop *DomLoop = LI.getLoopFor(BB);
4820 if (DomLoop && DomLoop->getHeader() == BB) {
Andrew Trick070e5402012-03-16 03:16:56 +00004821 assert(DomLoop->getLoopPreheader() && "LSR needs a simplified loop nest");
Andrew Trick12728f02012-01-17 06:45:52 +00004822 }
Andrew Trick732ad802012-01-07 03:16:50 +00004823 }
Andrew Trick070e5402012-03-16 03:16:56 +00004824#endif // DEBUG
Dan Gohman85875f72009-03-09 20:34:59 +00004825
Dan Gohman45774ce2010-02-12 10:34:29 +00004826 DEBUG(dbgs() << "\nLSR on loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00004827 L->getHeader()->printAsOperand(dbgs(), /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +00004828 dbgs() << ":\n");
Dan Gohmane201f8f2009-03-09 20:46:50 +00004829
Dan Gohman927bcaa2010-05-20 20:33:18 +00004830 // First, perform some low-level loop optimizations.
Dan Gohman45774ce2010-02-12 10:34:29 +00004831 OptimizeShadowIV();
Dan Gohman4c4043c2010-05-20 20:05:31 +00004832 OptimizeLoopTermCond();
Evan Cheng78a4eb82009-05-11 22:33:01 +00004833
Andrew Trick8acb4342011-07-21 00:40:04 +00004834 // If loop preparation eliminates all interesting IV users, bail.
4835 if (IU.empty()) return;
4836
Andrew Trick168dfff2011-09-29 01:53:08 +00004837 // Skip nested loops until we can model them better with formulae.
Andrew Trickd97b83e2012-03-22 22:42:45 +00004838 if (!L->empty()) {
Andrew Trickbc6de902011-09-29 01:33:38 +00004839 DEBUG(dbgs() << "LSR skipping outer loop " << *L << "\n");
Andrew Trick168dfff2011-09-29 01:53:08 +00004840 return;
Andrew Trickbc6de902011-09-29 01:33:38 +00004841 }
4842
Dan Gohman927bcaa2010-05-20 20:33:18 +00004843 // Start collecting data and preparing for the solver.
Andrew Trick29fe5f02012-01-09 19:50:34 +00004844 CollectChains();
Dan Gohman45774ce2010-02-12 10:34:29 +00004845 CollectInterestingTypesAndFactors();
4846 CollectFixupsAndInitialFormulae();
4847 CollectLoopInvariantFixupsAndFormulae();
Chris Lattner9bfa6f82005-08-08 05:28:22 +00004848
Andrew Trick248d4102012-01-09 21:18:52 +00004849 assert(!Uses.empty() && "IVUsers reported at least one use");
Dan Gohman45774ce2010-02-12 10:34:29 +00004850 DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
4851 print_uses(dbgs()));
Misha Brukmanb1c93172005-04-21 23:48:37 +00004852
Dan Gohman45774ce2010-02-12 10:34:29 +00004853 // Now use the reuse data to generate a bunch of interesting ways
4854 // to formulate the values needed for the uses.
4855 GenerateAllReuseFormulae();
Evan Cheng3df447d2006-03-16 21:53:05 +00004856
Dan Gohman45774ce2010-02-12 10:34:29 +00004857 FilterOutUndesirableDedicatedRegisters();
4858 NarrowSearchSpaceUsingHeuristics();
Dan Gohman92c36962009-12-18 00:06:20 +00004859
Dan Gohman45774ce2010-02-12 10:34:29 +00004860 SmallVector<const Formula *, 8> Solution;
4861 Solve(Solution);
Dan Gohman92c36962009-12-18 00:06:20 +00004862
Dan Gohman45774ce2010-02-12 10:34:29 +00004863 // Release memory that is no longer needed.
4864 Factors.clear();
4865 Types.clear();
4866 RegUses.clear();
4867
Andrew Trick58124392011-09-27 00:44:14 +00004868 if (Solution.empty())
4869 return;
4870
Dan Gohman45774ce2010-02-12 10:34:29 +00004871#ifndef NDEBUG
4872 // Formulae should be legal.
Craig Topper77b99412015-05-23 08:01:41 +00004873 for (const LSRUse &LU : Uses) {
4874 for (const Formula &F : LU.Formulae)
Chandler Carruth26c59fa2013-01-07 14:41:08 +00004875 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
Craig Topper77b99412015-05-23 08:01:41 +00004876 F) && "Illegal formula generated!");
Dan Gohman45774ce2010-02-12 10:34:29 +00004877 };
4878#endif
4879
4880 // Now that we've decided what we want, make it so.
4881 ImplementSolution(Solution, P);
4882}
4883
4884void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
4885 if (Factors.empty() && Types.empty()) return;
4886
4887 OS << "LSR has identified the following interesting factors and types: ";
4888 bool First = true;
4889
Craig Topper10949ae2015-05-23 08:45:10 +00004890 for (int64_t Factor : Factors) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004891 if (!First) OS << ", ";
4892 First = false;
Craig Topper10949ae2015-05-23 08:45:10 +00004893 OS << '*' << Factor;
Evan Cheng87fe40b2009-11-10 21:14:05 +00004894 }
Dale Johannesen02cb2bf2009-05-11 17:15:42 +00004895
Craig Topper10949ae2015-05-23 08:45:10 +00004896 for (Type *Ty : Types) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004897 if (!First) OS << ", ";
4898 First = false;
Craig Topper10949ae2015-05-23 08:45:10 +00004899 OS << '(' << *Ty << ')';
Dan Gohman45774ce2010-02-12 10:34:29 +00004900 }
4901 OS << '\n';
4902}
4903
4904void LSRInstance::print_fixups(raw_ostream &OS) const {
4905 OS << "LSR is examining the following fixup sites:\n";
Craig Topper77b99412015-05-23 08:01:41 +00004906 for (const LSRFixup &LF : Fixups) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004907 dbgs() << " ";
Craig Topper77b99412015-05-23 08:01:41 +00004908 LF.print(OS);
Dan Gohman45774ce2010-02-12 10:34:29 +00004909 OS << '\n';
4910 }
4911}
4912
4913void LSRInstance::print_uses(raw_ostream &OS) const {
4914 OS << "LSR is examining the following uses:\n";
Craig Topper77b99412015-05-23 08:01:41 +00004915 for (const LSRUse &LU : Uses) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004916 dbgs() << " ";
4917 LU.print(OS);
4918 OS << '\n';
Craig Topper77b99412015-05-23 08:01:41 +00004919 for (const Formula &F : LU.Formulae) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004920 OS << " ";
Craig Topper77b99412015-05-23 08:01:41 +00004921 F.print(OS);
Dan Gohman45774ce2010-02-12 10:34:29 +00004922 OS << '\n';
4923 }
4924 }
4925}
4926
4927void LSRInstance::print(raw_ostream &OS) const {
4928 print_factors_and_types(OS);
4929 print_fixups(OS);
4930 print_uses(OS);
4931}
4932
Manman Ren49d684e2012-09-12 05:06:18 +00004933#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman45774ce2010-02-12 10:34:29 +00004934void LSRInstance::dump() const {
4935 print(errs()); errs() << '\n';
4936}
Manman Renc3366cc2012-09-06 19:55:56 +00004937#endif
Dan Gohman45774ce2010-02-12 10:34:29 +00004938
4939namespace {
4940
4941class LoopStrengthReduce : public LoopPass {
Dan Gohman45774ce2010-02-12 10:34:29 +00004942public:
4943 static char ID; // Pass ID, replacement for typeid
Chandler Carruth26c59fa2013-01-07 14:41:08 +00004944 LoopStrengthReduce();
Dan Gohman45774ce2010-02-12 10:34:29 +00004945
4946private:
Craig Topper3e4c6972014-03-05 09:10:37 +00004947 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
4948 void getAnalysisUsage(AnalysisUsage &AU) const override;
Dan Gohman45774ce2010-02-12 10:34:29 +00004949};
4950
Alexander Kornienkof00654e2015-06-23 09:49:53 +00004951}
Dan Gohman45774ce2010-02-12 10:34:29 +00004952
4953char LoopStrengthReduce::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +00004954INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce",
Owen Andersondf7a4f22010-10-07 22:25:06 +00004955 "Loop Strength Reduction", false, false)
Chandler Carruth705b1852015-01-31 03:43:40 +00004956INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chandler Carruth73523022014-01-13 13:07:17 +00004957INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +00004958INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
4959INITIALIZE_PASS_DEPENDENCY(IVUsers)
Chandler Carruth4f8f3072015-01-17 14:16:18 +00004960INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Owen Andersona4fefc12010-10-19 20:08:44 +00004961INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Owen Anderson8ac477f2010-10-12 19:48:12 +00004962INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce",
4963 "Loop Strength Reduction", false, false)
4964
Nadav Rotem4dc976f2012-10-19 21:28:43 +00004965
Chandler Carruth26c59fa2013-01-07 14:41:08 +00004966Pass *llvm::createLoopStrengthReducePass() {
4967 return new LoopStrengthReduce();
Dan Gohman45774ce2010-02-12 10:34:29 +00004968}
4969
Chandler Carruth26c59fa2013-01-07 14:41:08 +00004970LoopStrengthReduce::LoopStrengthReduce() : LoopPass(ID) {
4971 initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry());
4972}
Dan Gohman45774ce2010-02-12 10:34:29 +00004973
4974void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
4975 // We split critical edges, so we change the CFG. However, we do update
4976 // many analyses if they are around.
Eric Christopherda6bd452011-02-10 01:48:24 +00004977 AU.addPreservedID(LoopSimplifyID);
Dan Gohman45774ce2010-02-12 10:34:29 +00004978
Chandler Carruth4f8f3072015-01-17 14:16:18 +00004979 AU.addRequired<LoopInfoWrapperPass>();
4980 AU.addPreserved<LoopInfoWrapperPass>();
Eric Christopherda6bd452011-02-10 01:48:24 +00004981 AU.addRequiredID(LoopSimplifyID);
Chandler Carruth73523022014-01-13 13:07:17 +00004982 AU.addRequired<DominatorTreeWrapperPass>();
4983 AU.addPreserved<DominatorTreeWrapperPass>();
Dan Gohman45774ce2010-02-12 10:34:29 +00004984 AU.addRequired<ScalarEvolution>();
4985 AU.addPreserved<ScalarEvolution>();
Cameron Zwarich97dae4d2011-02-10 23:53:14 +00004986 // Requiring LoopSimplify a second time here prevents IVUsers from running
4987 // twice, since LoopSimplify was invalidated by running ScalarEvolution.
4988 AU.addRequiredID(LoopSimplifyID);
Dan Gohman45774ce2010-02-12 10:34:29 +00004989 AU.addRequired<IVUsers>();
4990 AU.addPreserved<IVUsers>();
Chandler Carruth705b1852015-01-31 03:43:40 +00004991 AU.addRequired<TargetTransformInfoWrapperPass>();
Dan Gohman45774ce2010-02-12 10:34:29 +00004992}
4993
4994bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00004995 if (skipOptnoneFunction(L))
4996 return false;
4997
Dan Gohman45774ce2010-02-12 10:34:29 +00004998 bool Changed = false;
4999
5000 // Run the main LSR transformation.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00005001 Changed |= LSRInstance(L, this).getChanged();
Dan Gohman45774ce2010-02-12 10:34:29 +00005002
Andrew Trick2ec61a82012-01-07 01:36:44 +00005003 // Remove any extra phis created by processing inner loops.
Dan Gohmanb5358002010-01-05 16:31:45 +00005004 Changed |= DeleteDeadPHIs(L->getHeader());
Andrew Trickf950ce82013-01-06 05:59:39 +00005005 if (EnablePhiElim && L->isLoopSimplifyForm()) {
Andrew Trick2ec61a82012-01-07 01:36:44 +00005006 SmallVector<WeakVH, 16> DeadInsts;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005007 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
5008 SCEVExpander Rewriter(getAnalysis<ScalarEvolution>(), DL, "lsr");
Andrew Trick2ec61a82012-01-07 01:36:44 +00005009#ifndef NDEBUG
5010 Rewriter.setDebugType(DEBUG_TYPE);
5011#endif
Chandler Carruth73523022014-01-13 13:07:17 +00005012 unsigned numFolded = Rewriter.replaceCongruentIVs(
5013 L, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(), DeadInsts,
Chandler Carruthfdb9c572015-02-01 12:01:35 +00005014 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
5015 *L->getHeader()->getParent()));
Andrew Trick2ec61a82012-01-07 01:36:44 +00005016 if (numFolded) {
5017 Changed = true;
5018 DeleteTriviallyDeadInstructions(DeadInsts);
5019 DeleteDeadPHIs(L->getHeader());
5020 }
5021 }
Evan Cheng03001cb2008-07-07 19:51:32 +00005022 return Changed;
Nate Begemanb18121e2004-10-18 21:08:22 +00005023}