blob: 3efea34cc175d659c71b9a9703d4ee2bdc7a333e [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
119}
120
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
Dan Gohman51ad99d2010-01-21 02:09:26 +0000160}
161
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 Topper77b99412015-05-23 08:01:41 +0000188 for (auto &I : RegUsesMap) {
189 SmallBitVector &UsedByIndices = I.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
284}
285
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())));
327 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyGood.begin(),
328 E = MyGood.end(); I != E; ++I)
329 Good.push_back(SE.getMulExpr(NegOne, *I));
330 for (SmallVectorImpl<const SCEV *>::const_iterator I = MyBad.begin(),
331 E = MyBad.end(); I != E; ++I)
332 Bad.push_back(SE.getMulExpr(NegOne, *I));
333 return;
334 }
335
336 // Ok, we can't do anything interesting. Just stuff the whole thing into a
337 // register and hope for the best.
338 Bad.push_back(S);
339}
340
341/// InitialMatch - Incorporate loop-variant parts of S into this Formula,
342/// attempting to keep all loop-invariant and loop-computable values in a
343/// single base register.
Dan Gohman20d9ce22010-11-17 21:41:58 +0000344void Formula::InitialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000345 SmallVector<const SCEV *, 4> Good;
346 SmallVector<const SCEV *, 4> Bad;
Dan Gohman20d9ce22010-11-17 21:41:58 +0000347 DoInitialMatch(S, L, Good, Bad, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +0000348 if (!Good.empty()) {
Dan Gohman9b5d0bb72010-04-08 23:36:27 +0000349 const SCEV *Sum = SE.getAddExpr(Good);
350 if (!Sum->isZero())
351 BaseRegs.push_back(Sum);
Chandler Carruth6e479322013-01-07 15:04:40 +0000352 HasBaseReg = true;
Dan Gohman45774ce2010-02-12 10:34:29 +0000353 }
354 if (!Bad.empty()) {
Dan Gohman9b5d0bb72010-04-08 23:36:27 +0000355 const SCEV *Sum = SE.getAddExpr(Bad);
356 if (!Sum->isZero())
357 BaseRegs.push_back(Sum);
Chandler Carruth6e479322013-01-07 15:04:40 +0000358 HasBaseReg = true;
Dan Gohman45774ce2010-02-12 10:34:29 +0000359 }
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000360 Canonicalize();
361}
362
363/// \brief Check whether or not this formula statisfies the canonical
364/// representation.
365/// \see Formula::BaseRegs.
366bool Formula::isCanonical() const {
367 if (ScaledReg)
368 return Scale != 1 || !BaseRegs.empty();
369 return BaseRegs.size() <= 1;
370}
371
372/// \brief Helper method to morph a formula into its canonical representation.
373/// \see Formula::BaseRegs.
374/// Every formula having more than one base register, must use the ScaledReg
375/// field. Otherwise, we would have to do special cases everywhere in LSR
376/// to treat reg1 + reg2 + ... the same way as reg1 + 1*reg2 + ...
377/// On the other hand, 1*reg should be canonicalized into reg.
378void Formula::Canonicalize() {
379 if (isCanonical())
380 return;
381 // So far we did not need this case. This is easy to implement but it is
382 // useless to maintain dead code. Beside it could hurt compile time.
383 assert(!BaseRegs.empty() && "1*reg => reg, should not be needed.");
384 // Keep the invariant sum in BaseRegs and one of the variant sum in ScaledReg.
385 ScaledReg = BaseRegs.back();
386 BaseRegs.pop_back();
387 Scale = 1;
388 size_t BaseRegsSize = BaseRegs.size();
389 size_t Try = 0;
390 // If ScaledReg is an invariant, try to find a variant expression.
391 while (Try < BaseRegsSize && !isa<SCEVAddRecExpr>(ScaledReg))
392 std::swap(ScaledReg, BaseRegs[Try++]);
393}
394
395/// \brief Get rid of the scale in the formula.
396/// In other words, this method morphes reg1 + 1*reg2 into reg1 + reg2.
397/// \return true if it was possible to get rid of the scale, false otherwise.
398/// \note After this operation the formula may not be in the canonical form.
399bool Formula::Unscale() {
400 if (Scale != 1)
401 return false;
402 Scale = 0;
403 BaseRegs.push_back(ScaledReg);
404 ScaledReg = nullptr;
405 return true;
Dan Gohman45774ce2010-02-12 10:34:29 +0000406}
407
408/// getNumRegs - Return the total number of register operands used by this
409/// formula. This does not include register uses implied by non-constant
410/// addrec strides.
Adam Nemetdeab6f92014-04-29 18:25:28 +0000411size_t Formula::getNumRegs() const {
Dan Gohman45774ce2010-02-12 10:34:29 +0000412 return !!ScaledReg + BaseRegs.size();
413}
414
415/// getType - Return the type of this formula, if it has one, or null
416/// otherwise. This type is meaningless except for the bit size.
Chris Lattner229907c2011-07-18 04:54:35 +0000417Type *Formula::getType() const {
Dan Gohman45774ce2010-02-12 10:34:29 +0000418 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
419 ScaledReg ? ScaledReg->getType() :
Chandler Carruth6e479322013-01-07 15:04:40 +0000420 BaseGV ? BaseGV->getType() :
Craig Topperf40110f2014-04-25 05:29:35 +0000421 nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000422}
423
Dan Gohman80a96082010-05-20 15:17:54 +0000424/// DeleteBaseReg - Delete the given base reg from the BaseRegs list.
425void Formula::DeleteBaseReg(const SCEV *&S) {
426 if (&S != &BaseRegs.back())
427 std::swap(S, BaseRegs.back());
428 BaseRegs.pop_back();
429}
430
Dan Gohman45774ce2010-02-12 10:34:29 +0000431/// referencesReg - Test if this formula references the given register.
432bool Formula::referencesReg(const SCEV *S) const {
433 return S == ScaledReg ||
434 std::find(BaseRegs.begin(), BaseRegs.end(), S) != BaseRegs.end();
435}
436
437/// hasRegsUsedByUsesOtherThan - Test whether this formula uses registers
438/// which are used by uses other than the use with the given index.
439bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
440 const RegUseTracker &RegUses) const {
441 if (ScaledReg)
442 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
443 return true;
444 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
445 E = BaseRegs.end(); I != E; ++I)
446 if (RegUses.isRegUsedByUsesOtherThan(*I, LUIdx))
447 return true;
448 return false;
449}
450
451void Formula::print(raw_ostream &OS) const {
452 bool First = true;
Chandler Carruth6e479322013-01-07 15:04:40 +0000453 if (BaseGV) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000454 if (!First) OS << " + "; else First = false;
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000455 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +0000456 }
Chandler Carruth6e479322013-01-07 15:04:40 +0000457 if (BaseOffset != 0) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000458 if (!First) OS << " + "; else First = false;
Chandler Carruth6e479322013-01-07 15:04:40 +0000459 OS << BaseOffset;
Dan Gohman45774ce2010-02-12 10:34:29 +0000460 }
461 for (SmallVectorImpl<const SCEV *>::const_iterator I = BaseRegs.begin(),
462 E = BaseRegs.end(); I != E; ++I) {
463 if (!First) OS << " + "; else First = false;
464 OS << "reg(" << **I << ')';
465 }
Chandler Carruth6e479322013-01-07 15:04:40 +0000466 if (HasBaseReg && BaseRegs.empty()) {
Dan Gohman06ab08f2010-05-18 22:35:55 +0000467 if (!First) OS << " + "; else First = false;
468 OS << "**error: HasBaseReg**";
Chandler Carruth6e479322013-01-07 15:04:40 +0000469 } else if (!HasBaseReg && !BaseRegs.empty()) {
Dan Gohman06ab08f2010-05-18 22:35:55 +0000470 if (!First) OS << " + "; else First = false;
471 OS << "**error: !HasBaseReg**";
472 }
Chandler Carruth6e479322013-01-07 15:04:40 +0000473 if (Scale != 0) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000474 if (!First) OS << " + "; else First = false;
Chandler Carruth6e479322013-01-07 15:04:40 +0000475 OS << Scale << "*reg(";
Dan Gohman45774ce2010-02-12 10:34:29 +0000476 if (ScaledReg)
477 OS << *ScaledReg;
478 else
479 OS << "<unknown>";
480 OS << ')';
481 }
Dan Gohman6136e942011-05-03 00:46:49 +0000482 if (UnfoldedOffset != 0) {
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +0000483 if (!First) OS << " + ";
Dan Gohman6136e942011-05-03 00:46:49 +0000484 OS << "imm(" << UnfoldedOffset << ')';
485 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000486}
487
Manman Ren49d684e2012-09-12 05:06:18 +0000488#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman45774ce2010-02-12 10:34:29 +0000489void Formula::dump() const {
490 print(errs()); errs() << '\n';
491}
Manman Renc3366cc2012-09-06 19:55:56 +0000492#endif
Dan Gohman45774ce2010-02-12 10:34:29 +0000493
Dan Gohman85af2562010-02-19 19:32:49 +0000494/// isAddRecSExtable - Return true if the given addrec can be sign-extended
495/// without changing its value.
496static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
Chris Lattner229907c2011-07-18 04:54:35 +0000497 Type *WideTy =
Dan Gohmanab5fb7f2010-05-20 19:44:23 +0000498 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1);
Dan Gohman85af2562010-02-19 19:32:49 +0000499 return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
500}
501
502/// isAddSExtable - Return true if the given add can be sign-extended
503/// without changing its value.
504static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
Chris Lattner229907c2011-07-18 04:54:35 +0000505 Type *WideTy =
Dan Gohmanab5fb7f2010-05-20 19:44:23 +0000506 IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1);
Dan Gohman85af2562010-02-19 19:32:49 +0000507 return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
508}
509
Dan Gohmanab542222010-06-24 16:45:11 +0000510/// isMulSExtable - Return true if the given mul can be sign-extended
Dan Gohman85af2562010-02-19 19:32:49 +0000511/// without changing its value.
Dan Gohmanab542222010-06-24 16:45:11 +0000512static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {
Chris Lattner229907c2011-07-18 04:54:35 +0000513 Type *WideTy =
Dan Gohmanab542222010-06-24 16:45:11 +0000514 IntegerType::get(SE.getContext(),
515 SE.getTypeSizeInBits(M->getType()) * M->getNumOperands());
516 return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy));
Dan Gohman85af2562010-02-19 19:32:49 +0000517}
518
Dan Gohman4eebb942010-02-19 19:35:48 +0000519/// getExactSDiv - Return an expression for LHS /s RHS, if it can be determined
520/// and if the remainder is known to be zero, or null otherwise. If
521/// IgnoreSignificantBits is true, expressions like (X * Y) /s Y are simplified
522/// to Y, ignoring that the multiplication may overflow, which is useful when
523/// the result will be used in a context where the most significant bits are
524/// ignored.
525static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
526 ScalarEvolution &SE,
527 bool IgnoreSignificantBits = false) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000528 // Handle the trivial case, which works for any SCEV type.
529 if (LHS == RHS)
Dan Gohman1d2ded72010-05-03 22:09:21 +0000530 return SE.getConstant(LHS->getType(), 1);
Dan Gohman45774ce2010-02-12 10:34:29 +0000531
Dan Gohman47ddf762010-06-24 16:51:25 +0000532 // Handle a few RHS special cases.
533 const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
534 if (RC) {
535 const APInt &RA = RC->getValue()->getValue();
536 // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do
537 // some folding.
538 if (RA.isAllOnesValue())
539 return SE.getMulExpr(LHS, RC);
540 // Handle x /s 1 as x.
541 if (RA == 1)
542 return LHS;
543 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000544
545 // Check for a division of a constant by a constant.
546 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000547 if (!RC)
Craig Topperf40110f2014-04-25 05:29:35 +0000548 return nullptr;
Dan Gohman47ddf762010-06-24 16:51:25 +0000549 const APInt &LA = C->getValue()->getValue();
550 const APInt &RA = RC->getValue()->getValue();
551 if (LA.srem(RA) != 0)
Craig Topperf40110f2014-04-25 05:29:35 +0000552 return nullptr;
Dan Gohman47ddf762010-06-24 16:51:25 +0000553 return SE.getConstant(LA.sdiv(RA));
Dan Gohman45774ce2010-02-12 10:34:29 +0000554 }
555
Dan Gohman85af2562010-02-19 19:32:49 +0000556 // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
Dan Gohman45774ce2010-02-12 10:34:29 +0000557 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman85af2562010-02-19 19:32:49 +0000558 if (IgnoreSignificantBits || isAddRecSExtable(AR, SE)) {
Dan Gohman4eebb942010-02-19 19:35:48 +0000559 const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
560 IgnoreSignificantBits);
Craig Topperf40110f2014-04-25 05:29:35 +0000561 if (!Step) return nullptr;
Dan Gohman129a8162010-08-19 01:02:31 +0000562 const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
563 IgnoreSignificantBits);
Craig Topperf40110f2014-04-25 05:29:35 +0000564 if (!Start) return nullptr;
Andrew Trick8b55b732011-03-14 16:50:06 +0000565 // FlagNW is independent of the start value, step direction, and is
566 // preserved with smaller magnitude steps.
567 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
568 return SE.getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagAnyWrap);
Dan Gohman85af2562010-02-19 19:32:49 +0000569 }
Craig Topperf40110f2014-04-25 05:29:35 +0000570 return nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000571 }
572
Dan Gohman85af2562010-02-19 19:32:49 +0000573 // Distribute the sdiv over add operands, if the add doesn't overflow.
Dan Gohman45774ce2010-02-12 10:34:29 +0000574 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohman85af2562010-02-19 19:32:49 +0000575 if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
576 SmallVector<const SCEV *, 8> Ops;
577 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
578 I != E; ++I) {
Dan Gohman4eebb942010-02-19 19:35:48 +0000579 const SCEV *Op = getExactSDiv(*I, RHS, SE,
580 IgnoreSignificantBits);
Craig Topperf40110f2014-04-25 05:29:35 +0000581 if (!Op) return nullptr;
Dan Gohman85af2562010-02-19 19:32:49 +0000582 Ops.push_back(Op);
583 }
584 return SE.getAddExpr(Ops);
Dan Gohman45774ce2010-02-12 10:34:29 +0000585 }
Craig Topperf40110f2014-04-25 05:29:35 +0000586 return nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000587 }
588
589 // Check for a multiply operand that we can pull RHS out of.
Dan Gohman963b1c12010-06-24 16:57:52 +0000590 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman85af2562010-02-19 19:32:49 +0000591 if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
Dan Gohman45774ce2010-02-12 10:34:29 +0000592 SmallVector<const SCEV *, 4> Ops;
593 bool Found = false;
594 for (SCEVMulExpr::op_iterator I = Mul->op_begin(), E = Mul->op_end();
595 I != E; ++I) {
Dan Gohman6b733fc2010-05-20 16:23:28 +0000596 const SCEV *S = *I;
Dan Gohman45774ce2010-02-12 10:34:29 +0000597 if (!Found)
Dan Gohman6b733fc2010-05-20 16:23:28 +0000598 if (const SCEV *Q = getExactSDiv(S, RHS, SE,
Dan Gohman4eebb942010-02-19 19:35:48 +0000599 IgnoreSignificantBits)) {
Dan Gohman6b733fc2010-05-20 16:23:28 +0000600 S = Q;
Dan Gohman45774ce2010-02-12 10:34:29 +0000601 Found = true;
Dan Gohman45774ce2010-02-12 10:34:29 +0000602 }
Dan Gohman6b733fc2010-05-20 16:23:28 +0000603 Ops.push_back(S);
Dan Gohman45774ce2010-02-12 10:34:29 +0000604 }
Craig Topperf40110f2014-04-25 05:29:35 +0000605 return Found ? SE.getMulExpr(Ops) : nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000606 }
Craig Topperf40110f2014-04-25 05:29:35 +0000607 return nullptr;
Dan Gohman963b1c12010-06-24 16:57:52 +0000608 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000609
610 // Otherwise we don't know.
Craig Topperf40110f2014-04-25 05:29:35 +0000611 return nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000612}
613
614/// ExtractImmediate - If S involves the addition of a constant integer value,
615/// return that integer value, and mutate S to point to a new SCEV with that
616/// value excluded.
617static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
618 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
619 if (C->getValue()->getValue().getMinSignedBits() <= 64) {
Dan Gohman1d2ded72010-05-03 22:09:21 +0000620 S = SE.getConstant(C->getType(), 0);
Dan Gohman45774ce2010-02-12 10:34:29 +0000621 return C->getValue()->getSExtValue();
622 }
623 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
624 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
625 int64_t Result = ExtractImmediate(NewOps.front(), SE);
Dan Gohman081ffcd2010-08-13 21:17:19 +0000626 if (Result != 0)
627 S = SE.getAddExpr(NewOps);
Dan Gohman45774ce2010-02-12 10:34:29 +0000628 return Result;
629 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
630 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
631 int64_t Result = ExtractImmediate(NewOps.front(), SE);
Dan Gohman081ffcd2010-08-13 21:17:19 +0000632 if (Result != 0)
Andrew Trick8b55b732011-03-14 16:50:06 +0000633 S = SE.getAddRecExpr(NewOps, AR->getLoop(),
634 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
635 SCEV::FlagAnyWrap);
Dan Gohman45774ce2010-02-12 10:34:29 +0000636 return Result;
637 }
638 return 0;
639}
640
641/// ExtractSymbol - If S involves the addition of a GlobalValue address,
642/// return that symbol, and mutate S to point to a new SCEV with that
643/// value excluded.
644static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
645 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
646 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
Dan Gohman1d2ded72010-05-03 22:09:21 +0000647 S = SE.getConstant(GV->getType(), 0);
Dan Gohman45774ce2010-02-12 10:34:29 +0000648 return GV;
649 }
650 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
651 SmallVector<const SCEV *, 8> NewOps(Add->op_begin(), Add->op_end());
652 GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
Dan Gohman081ffcd2010-08-13 21:17:19 +0000653 if (Result)
654 S = SE.getAddExpr(NewOps);
Dan Gohman45774ce2010-02-12 10:34:29 +0000655 return Result;
656 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
657 SmallVector<const SCEV *, 8> NewOps(AR->op_begin(), AR->op_end());
658 GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
Dan Gohman081ffcd2010-08-13 21:17:19 +0000659 if (Result)
Andrew Trick8b55b732011-03-14 16:50:06 +0000660 S = SE.getAddRecExpr(NewOps, AR->getLoop(),
661 // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
662 SCEV::FlagAnyWrap);
Dan Gohman45774ce2010-02-12 10:34:29 +0000663 return Result;
664 }
Craig Topperf40110f2014-04-25 05:29:35 +0000665 return nullptr;
Nate Begemanb18121e2004-10-18 21:08:22 +0000666}
667
Dan Gohmand0b1fbd2009-02-18 00:08:39 +0000668/// isAddressUse - Returns true if the specified instruction is using the
Dale Johannesen9efd2ce2008-12-05 21:47:27 +0000669/// specified value as an address.
670static bool isAddressUse(Instruction *Inst, Value *OperandVal) {
671 bool isAddress = isa<LoadInst>(Inst);
672 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
673 if (SI->getOperand(1) == OperandVal)
674 isAddress = true;
675 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
676 // Addressing modes can also be folded into prefetches and a variety
677 // of intrinsics.
678 switch (II->getIntrinsicID()) {
679 default: break;
680 case Intrinsic::prefetch:
Dale Johannesen9efd2ce2008-12-05 21:47:27 +0000681 case Intrinsic::x86_sse_storeu_ps:
682 case Intrinsic::x86_sse2_storeu_pd:
683 case Intrinsic::x86_sse2_storeu_dq:
684 case Intrinsic::x86_sse2_storel_dq:
Gabor Greif8ae30952010-06-30 09:15:28 +0000685 if (II->getArgOperand(0) == OperandVal)
Dale Johannesen9efd2ce2008-12-05 21:47:27 +0000686 isAddress = true;
687 break;
688 }
689 }
690 return isAddress;
691}
Chris Lattnere4ed42a2005-10-03 01:04:44 +0000692
Dan Gohman917ffe42009-03-09 21:01:17 +0000693/// getAccessType - Return the type of the memory being accessed.
Chris Lattner229907c2011-07-18 04:54:35 +0000694static Type *getAccessType(const Instruction *Inst) {
695 Type *AccessTy = Inst->getType();
Dan Gohman917ffe42009-03-09 21:01:17 +0000696 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst))
Dan Gohman14d13392009-05-18 16:45:28 +0000697 AccessTy = SI->getOperand(0)->getType();
Dan Gohman917ffe42009-03-09 21:01:17 +0000698 else if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
699 // Addressing modes can also be folded into prefetches and a variety
700 // of intrinsics.
701 switch (II->getIntrinsicID()) {
702 default: break;
703 case Intrinsic::x86_sse_storeu_ps:
704 case Intrinsic::x86_sse2_storeu_pd:
705 case Intrinsic::x86_sse2_storeu_dq:
706 case Intrinsic::x86_sse2_storel_dq:
Gabor Greif8ae30952010-06-30 09:15:28 +0000707 AccessTy = II->getArgOperand(0)->getType();
Dan Gohman917ffe42009-03-09 21:01:17 +0000708 break;
709 }
710 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000711
712 // All pointers have the same requirements, so canonicalize them to an
713 // arbitrary pointer type to minimize variation.
Chris Lattner229907c2011-07-18 04:54:35 +0000714 if (PointerType *PTy = dyn_cast<PointerType>(AccessTy))
Dan Gohman45774ce2010-02-12 10:34:29 +0000715 AccessTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
716 PTy->getAddressSpace());
717
Dan Gohman14d13392009-05-18 16:45:28 +0000718 return AccessTy;
Dan Gohman917ffe42009-03-09 21:01:17 +0000719}
720
Andrew Trick5df90962011-12-06 03:13:31 +0000721/// isExistingPhi - Return true if this AddRec is already a phi in its loop.
722static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
723 for (BasicBlock::iterator I = AR->getLoop()->getHeader()->begin();
724 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
725 if (SE.isSCEVable(PN->getType()) &&
726 (SE.getEffectiveSCEVType(PN->getType()) ==
727 SE.getEffectiveSCEVType(AR->getType())) &&
728 SE.getSCEV(PN) == AR)
729 return true;
730 }
731 return false;
732}
733
Andrew Trickd5d2db92012-01-10 01:45:08 +0000734/// Check if expanding this expression is likely to incur significant cost. This
735/// is tricky because SCEV doesn't track which expressions are actually computed
736/// by the current IR.
737///
738/// We currently allow expansion of IV increments that involve adds,
739/// multiplication by constants, and AddRecs from existing phis.
740///
741/// TODO: Allow UDivExpr if we can find an existing IV increment that is an
742/// obvious multiple of the UDivExpr.
743static bool isHighCostExpansion(const SCEV *S,
Craig Topper71b7b682014-08-21 05:55:13 +0000744 SmallPtrSetImpl<const SCEV*> &Processed,
Andrew Trickd5d2db92012-01-10 01:45:08 +0000745 ScalarEvolution &SE) {
746 // Zero/One operand expressions
747 switch (S->getSCEVType()) {
748 case scUnknown:
749 case scConstant:
750 return false;
751 case scTruncate:
752 return isHighCostExpansion(cast<SCEVTruncateExpr>(S)->getOperand(),
753 Processed, SE);
754 case scZeroExtend:
755 return isHighCostExpansion(cast<SCEVZeroExtendExpr>(S)->getOperand(),
756 Processed, SE);
757 case scSignExtend:
758 return isHighCostExpansion(cast<SCEVSignExtendExpr>(S)->getOperand(),
759 Processed, SE);
760 }
761
David Blaikie70573dc2014-11-19 07:49:26 +0000762 if (!Processed.insert(S).second)
Andrew Trickd5d2db92012-01-10 01:45:08 +0000763 return false;
764
765 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
766 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
767 I != E; ++I) {
768 if (isHighCostExpansion(*I, Processed, SE))
769 return true;
770 }
771 return false;
772 }
773
774 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
775 if (Mul->getNumOperands() == 2) {
776 // Multiplication by a constant is ok
777 if (isa<SCEVConstant>(Mul->getOperand(0)))
778 return isHighCostExpansion(Mul->getOperand(1), Processed, SE);
779
780 // If we have the value of one operand, check if an existing
781 // multiplication already generates this expression.
782 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) {
783 Value *UVal = U->getValue();
Chandler Carruthcdf47882014-03-09 03:16:01 +0000784 for (User *UR : UVal->users()) {
Andrew Trick14779cc2012-03-26 20:28:37 +0000785 // If U is a constant, it may be used by a ConstantExpr.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000786 Instruction *UI = dyn_cast<Instruction>(UR);
787 if (UI && UI->getOpcode() == Instruction::Mul &&
788 SE.isSCEVable(UI->getType())) {
789 return SE.getSCEV(UI) == Mul;
Andrew Trickd5d2db92012-01-10 01:45:08 +0000790 }
791 }
792 }
793 }
794 }
795
796 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
797 if (isExistingPhi(AR, SE))
798 return false;
799 }
800
801 // Fow now, consider any other type of expression (div/mul/min/max) high cost.
802 return true;
803}
804
Dan Gohman45774ce2010-02-12 10:34:29 +0000805/// DeleteTriviallyDeadInstructions - If any of the instructions is the
806/// specified set are trivially dead, delete them and see if this makes any of
807/// their operands subsequently dead.
808static bool
809DeleteTriviallyDeadInstructions(SmallVectorImpl<WeakVH> &DeadInsts) {
810 bool Changed = false;
811
812 while (!DeadInsts.empty()) {
Richard Smithad9c8e82012-08-21 20:35:14 +0000813 Value *V = DeadInsts.pop_back_val();
814 Instruction *I = dyn_cast_or_null<Instruction>(V);
Dan Gohman45774ce2010-02-12 10:34:29 +0000815
Craig Topperf40110f2014-04-25 05:29:35 +0000816 if (!I || !isInstructionTriviallyDead(I))
Dan Gohman45774ce2010-02-12 10:34:29 +0000817 continue;
818
819 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
820 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000821 *OI = nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +0000822 if (U->use_empty())
823 DeadInsts.push_back(U);
824 }
825
826 I->eraseFromParent();
827 Changed = true;
828 }
829
830 return Changed;
831}
832
Dan Gohman045f8192010-01-22 00:46:49 +0000833namespace {
Quentin Colombet8aa7abe2013-05-31 17:20:29 +0000834class LSRUse;
835}
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000836
837/// \brief Check if the addressing mode defined by \p F is completely
838/// folded in \p LU at isel time.
839/// This includes address-mode folding and special icmp tricks.
840/// This function returns true if \p LU can accommodate what \p F
841/// defines and up to 1 base + 1 scaled + offset.
842/// In other words, if \p F has several base registers, this function may
843/// still return true. Therefore, users still need to account for
844/// additional base registers and/or unfolded offsets to derive an
845/// accurate cost model.
846static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
847 const LSRUse &LU, const Formula &F);
Quentin Colombetbf490d42013-05-31 21:29:03 +0000848// Get the cost of the scaling factor used in F for LU.
849static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
850 const LSRUse &LU, const Formula &F);
Quentin Colombet8aa7abe2013-05-31 17:20:29 +0000851
852namespace {
Jim Grosbach60f48542009-11-17 17:53:56 +0000853
Dan Gohman45774ce2010-02-12 10:34:29 +0000854/// Cost - This class is used to measure and compare candidate formulae.
855class Cost {
856 /// TODO: Some of these could be merged. Also, a lexical ordering
857 /// isn't always optimal.
858 unsigned NumRegs;
859 unsigned AddRecCost;
860 unsigned NumIVMuls;
861 unsigned NumBaseAdds;
862 unsigned ImmCost;
863 unsigned SetupCost;
Quentin Colombetbf490d42013-05-31 21:29:03 +0000864 unsigned ScaleCost;
Nate Begemane68bcd12005-07-30 00:15:07 +0000865
Dan Gohman45774ce2010-02-12 10:34:29 +0000866public:
867 Cost()
868 : NumRegs(0), AddRecCost(0), NumIVMuls(0), NumBaseAdds(0), ImmCost(0),
Quentin Colombetbf490d42013-05-31 21:29:03 +0000869 SetupCost(0), ScaleCost(0) {}
Jim Grosbach60f48542009-11-17 17:53:56 +0000870
Dan Gohman45774ce2010-02-12 10:34:29 +0000871 bool operator<(const Cost &Other) const;
Dan Gohman045f8192010-01-22 00:46:49 +0000872
Tim Northoverbc6659c2014-01-22 13:27:00 +0000873 void Lose();
Dan Gohman045f8192010-01-22 00:46:49 +0000874
Andrew Trick784729d2011-09-26 23:11:04 +0000875#ifndef NDEBUG
876 // Once any of the metrics loses, they must all remain losers.
877 bool isValid() {
878 return ((NumRegs | AddRecCost | NumIVMuls | NumBaseAdds
Quentin Colombetbf490d42013-05-31 21:29:03 +0000879 | ImmCost | SetupCost | ScaleCost) != ~0u)
Andrew Trick784729d2011-09-26 23:11:04 +0000880 || ((NumRegs & AddRecCost & NumIVMuls & NumBaseAdds
Quentin Colombetbf490d42013-05-31 21:29:03 +0000881 & ImmCost & SetupCost & ScaleCost) == ~0u);
Andrew Trick784729d2011-09-26 23:11:04 +0000882 }
883#endif
884
885 bool isLoser() {
886 assert(isValid() && "invalid cost");
887 return NumRegs == ~0u;
888 }
889
Quentin Colombet8aa7abe2013-05-31 17:20:29 +0000890 void RateFormula(const TargetTransformInfo &TTI,
891 const Formula &F,
Craig Topper71b7b682014-08-21 05:55:13 +0000892 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman45774ce2010-02-12 10:34:29 +0000893 const DenseSet<const SCEV *> &VisitedRegs,
894 const Loop *L,
895 const SmallVectorImpl<int64_t> &Offsets,
Andrew Trick5df90962011-12-06 03:13:31 +0000896 ScalarEvolution &SE, DominatorTree &DT,
Quentin Colombet8aa7abe2013-05-31 17:20:29 +0000897 const LSRUse &LU,
Craig Topper71b7b682014-08-21 05:55:13 +0000898 SmallPtrSetImpl<const SCEV *> *LoserRegs = nullptr);
Dan Gohman045f8192010-01-22 00:46:49 +0000899
Dan Gohman45774ce2010-02-12 10:34:29 +0000900 void print(raw_ostream &OS) const;
901 void dump() const;
Dan Gohman045f8192010-01-22 00:46:49 +0000902
Dan Gohman45774ce2010-02-12 10:34:29 +0000903private:
904 void RateRegister(const SCEV *Reg,
Craig Topper71b7b682014-08-21 05:55:13 +0000905 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman45774ce2010-02-12 10:34:29 +0000906 const Loop *L,
907 ScalarEvolution &SE, DominatorTree &DT);
Dan Gohman5b18f032010-02-13 02:06:02 +0000908 void RatePrimaryRegister(const SCEV *Reg,
Craig Topper71b7b682014-08-21 05:55:13 +0000909 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman5b18f032010-02-13 02:06:02 +0000910 const Loop *L,
Andrew Trick5df90962011-12-06 03:13:31 +0000911 ScalarEvolution &SE, DominatorTree &DT,
Craig Topper71b7b682014-08-21 05:55:13 +0000912 SmallPtrSetImpl<const SCEV *> *LoserRegs);
Dan Gohman45774ce2010-02-12 10:34:29 +0000913};
914
915}
916
917/// RateRegister - Tally up interesting quantities from the given register.
918void Cost::RateRegister(const SCEV *Reg,
Craig Topper71b7b682014-08-21 05:55:13 +0000919 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman45774ce2010-02-12 10:34:29 +0000920 const Loop *L,
921 ScalarEvolution &SE, DominatorTree &DT) {
Dan Gohman5b18f032010-02-13 02:06:02 +0000922 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
Andrew Trickbc6de902011-09-29 01:33:38 +0000923 // If this is an addrec for another loop, don't second-guess its addrec phi
924 // nodes. LSR isn't currently smart enough to reason about more than one
Andrew Trickd97b83e2012-03-22 22:42:45 +0000925 // loop at a time. LSR has already run on inner loops, will not run on outer
926 // loops, and cannot be expected to change sibling loops.
927 if (AR->getLoop() != L) {
928 // If the AddRec exists, consider it's register free and leave it alone.
Andrew Trick5df90962011-12-06 03:13:31 +0000929 if (isExistingPhi(AR, SE))
930 return;
931
Andrew Trickd97b83e2012-03-22 22:42:45 +0000932 // Otherwise, do not consider this formula at all.
Tim Northoverbc6659c2014-01-22 13:27:00 +0000933 Lose();
Andrew Trickd97b83e2012-03-22 22:42:45 +0000934 return;
Dan Gohman45774ce2010-02-12 10:34:29 +0000935 }
Andrew Trickd97b83e2012-03-22 22:42:45 +0000936 AddRecCost += 1; /// TODO: This should be a function of the stride.
Dan Gohman45774ce2010-02-12 10:34:29 +0000937
Dan Gohman5b18f032010-02-13 02:06:02 +0000938 // Add the step value register, if it needs one.
939 // TODO: The non-affine case isn't precisely modeled here.
Andrew Trick8868fae2011-09-26 23:35:25 +0000940 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) {
941 if (!Regs.count(AR->getOperand(1))) {
Dan Gohman5b18f032010-02-13 02:06:02 +0000942 RateRegister(AR->getOperand(1), Regs, L, SE, DT);
Andrew Trick8868fae2011-09-26 23:35:25 +0000943 if (isLoser())
944 return;
945 }
946 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000947 }
Dan Gohman5b18f032010-02-13 02:06:02 +0000948 ++NumRegs;
949
950 // Rough heuristic; favor registers which don't require extra setup
951 // instructions in the preheader.
952 if (!isa<SCEVUnknown>(Reg) &&
953 !isa<SCEVConstant>(Reg) &&
954 !(isa<SCEVAddRecExpr>(Reg) &&
955 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(Reg)->getStart()) ||
956 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
957 ++SetupCost;
Dan Gohman34f37e02010-10-07 23:41:58 +0000958
959 NumIVMuls += isa<SCEVMulExpr>(Reg) &&
Dan Gohmanafd6db92010-11-17 21:23:15 +0000960 SE.hasComputableLoopEvolution(Reg, L);
Dan Gohman5b18f032010-02-13 02:06:02 +0000961}
962
963/// RatePrimaryRegister - Record this register in the set. If we haven't seen it
Andrew Trick5df90962011-12-06 03:13:31 +0000964/// before, rate it. Optional LoserRegs provides a way to declare any formula
965/// that refers to one of those regs an instant loser.
Dan Gohman5b18f032010-02-13 02:06:02 +0000966void Cost::RatePrimaryRegister(const SCEV *Reg,
Craig Topper71b7b682014-08-21 05:55:13 +0000967 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman0849ed52010-02-16 19:42:34 +0000968 const Loop *L,
Andrew Trick5df90962011-12-06 03:13:31 +0000969 ScalarEvolution &SE, DominatorTree &DT,
Craig Topper71b7b682014-08-21 05:55:13 +0000970 SmallPtrSetImpl<const SCEV *> *LoserRegs) {
Andrew Trick5df90962011-12-06 03:13:31 +0000971 if (LoserRegs && LoserRegs->count(Reg)) {
Tim Northoverbc6659c2014-01-22 13:27:00 +0000972 Lose();
Andrew Trick5df90962011-12-06 03:13:31 +0000973 return;
974 }
David Blaikie70573dc2014-11-19 07:49:26 +0000975 if (Regs.insert(Reg).second) {
Dan Gohman5b18f032010-02-13 02:06:02 +0000976 RateRegister(Reg, Regs, L, SE, DT);
Andrew Tricka1c01ba2013-03-19 04:14:57 +0000977 if (LoserRegs && isLoser())
Andrew Trick5df90962011-12-06 03:13:31 +0000978 LoserRegs->insert(Reg);
979 }
Dan Gohman45774ce2010-02-12 10:34:29 +0000980}
981
Quentin Colombet8aa7abe2013-05-31 17:20:29 +0000982void Cost::RateFormula(const TargetTransformInfo &TTI,
983 const Formula &F,
Craig Topper71b7b682014-08-21 05:55:13 +0000984 SmallPtrSetImpl<const SCEV *> &Regs,
Dan Gohman45774ce2010-02-12 10:34:29 +0000985 const DenseSet<const SCEV *> &VisitedRegs,
986 const Loop *L,
987 const SmallVectorImpl<int64_t> &Offsets,
Andrew Trick5df90962011-12-06 03:13:31 +0000988 ScalarEvolution &SE, DominatorTree &DT,
Quentin Colombet8aa7abe2013-05-31 17:20:29 +0000989 const LSRUse &LU,
Craig Topper71b7b682014-08-21 05:55:13 +0000990 SmallPtrSetImpl<const SCEV *> *LoserRegs) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +0000991 assert(F.isCanonical() && "Cost is accurate only for canonical formula");
Dan Gohman45774ce2010-02-12 10:34:29 +0000992 // Tally up the registers.
993 if (const SCEV *ScaledReg = F.ScaledReg) {
994 if (VisitedRegs.count(ScaledReg)) {
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(ScaledReg, 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 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
1003 E = F.BaseRegs.end(); I != E; ++I) {
1004 const SCEV *BaseReg = *I;
1005 if (VisitedRegs.count(BaseReg)) {
Tim Northoverbc6659c2014-01-22 13:27:00 +00001006 Lose();
Dan Gohman45774ce2010-02-12 10:34:29 +00001007 return;
1008 }
Andrew Trick5df90962011-12-06 03:13:31 +00001009 RatePrimaryRegister(BaseReg, Regs, L, SE, DT, LoserRegs);
Andrew Trick784729d2011-09-26 23:11:04 +00001010 if (isLoser())
1011 return;
Dan Gohman45774ce2010-02-12 10:34:29 +00001012 }
1013
Dan Gohman6136e942011-05-03 00:46:49 +00001014 // Determine how many (unfolded) adds we'll need inside the loop.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001015 size_t NumBaseParts = F.getNumRegs();
Dan Gohman6136e942011-05-03 00:46:49 +00001016 if (NumBaseParts > 1)
Quentin Colombet8aa7abe2013-05-31 17:20:29 +00001017 // Do not count the base and a possible second register if the target
1018 // allows to fold 2 registers.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001019 NumBaseAdds +=
1020 NumBaseParts - (1 + (F.Scale && isAMCompletelyFolded(TTI, LU, F)));
1021 NumBaseAdds += (F.UnfoldedOffset != 0);
Dan Gohman45774ce2010-02-12 10:34:29 +00001022
Quentin Colombetbf490d42013-05-31 21:29:03 +00001023 // Accumulate non-free scaling amounts.
1024 ScaleCost += getScalingFactorCost(TTI, LU, F);
1025
Dan Gohman45774ce2010-02-12 10:34:29 +00001026 // Tally up the non-zero immediates.
1027 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
1028 E = Offsets.end(); I != E; ++I) {
Chandler Carruth6e479322013-01-07 15:04:40 +00001029 int64_t Offset = (uint64_t)*I + F.BaseOffset;
1030 if (F.BaseGV)
Dan Gohman45774ce2010-02-12 10:34:29 +00001031 ImmCost += 64; // Handle symbolic values conservatively.
1032 // TODO: This should probably be the pointer size.
1033 else if (Offset != 0)
1034 ImmCost += APInt(64, Offset, true).getMinSignedBits();
1035 }
Andrew Trick784729d2011-09-26 23:11:04 +00001036 assert(isValid() && "invalid cost");
Dan Gohman45774ce2010-02-12 10:34:29 +00001037}
1038
Tim Northoverbc6659c2014-01-22 13:27:00 +00001039/// Lose - Set this cost to a losing value.
1040void Cost::Lose() {
Dan Gohman45774ce2010-02-12 10:34:29 +00001041 NumRegs = ~0u;
1042 AddRecCost = ~0u;
1043 NumIVMuls = ~0u;
1044 NumBaseAdds = ~0u;
1045 ImmCost = ~0u;
1046 SetupCost = ~0u;
Quentin Colombetbf490d42013-05-31 21:29:03 +00001047 ScaleCost = ~0u;
Dan Gohman45774ce2010-02-12 10:34:29 +00001048}
1049
1050/// operator< - Choose the lower cost.
1051bool Cost::operator<(const Cost &Other) const {
Benjamin Kramerb2f034b2014-03-03 19:58:30 +00001052 return std::tie(NumRegs, AddRecCost, NumIVMuls, NumBaseAdds, ScaleCost,
1053 ImmCost, SetupCost) <
1054 std::tie(Other.NumRegs, Other.AddRecCost, Other.NumIVMuls,
1055 Other.NumBaseAdds, Other.ScaleCost, Other.ImmCost,
1056 Other.SetupCost);
Dan Gohman45774ce2010-02-12 10:34:29 +00001057}
1058
1059void Cost::print(raw_ostream &OS) const {
1060 OS << NumRegs << " reg" << (NumRegs == 1 ? "" : "s");
1061 if (AddRecCost != 0)
1062 OS << ", with addrec cost " << AddRecCost;
1063 if (NumIVMuls != 0)
1064 OS << ", plus " << NumIVMuls << " IV mul" << (NumIVMuls == 1 ? "" : "s");
1065 if (NumBaseAdds != 0)
1066 OS << ", plus " << NumBaseAdds << " base add"
1067 << (NumBaseAdds == 1 ? "" : "s");
Quentin Colombetbf490d42013-05-31 21:29:03 +00001068 if (ScaleCost != 0)
1069 OS << ", plus " << ScaleCost << " scale cost";
Dan Gohman45774ce2010-02-12 10:34:29 +00001070 if (ImmCost != 0)
1071 OS << ", plus " << ImmCost << " imm cost";
1072 if (SetupCost != 0)
1073 OS << ", plus " << SetupCost << " setup cost";
1074}
1075
Manman Ren49d684e2012-09-12 05:06:18 +00001076#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman45774ce2010-02-12 10:34:29 +00001077void Cost::dump() const {
1078 print(errs()); errs() << '\n';
1079}
Manman Renc3366cc2012-09-06 19:55:56 +00001080#endif
Dan Gohman45774ce2010-02-12 10:34:29 +00001081
1082namespace {
1083
1084/// LSRFixup - An operand value in an instruction which is to be replaced
1085/// with some equivalent, possibly strength-reduced, replacement.
1086struct LSRFixup {
1087 /// UserInst - The instruction which will be updated.
1088 Instruction *UserInst;
1089
1090 /// OperandValToReplace - The operand of the instruction which will
1091 /// be replaced. The operand may be used more than once; every instance
1092 /// will be replaced.
1093 Value *OperandValToReplace;
1094
Dan Gohmand006ab92010-04-07 22:27:08 +00001095 /// PostIncLoops - If this user is to use the post-incremented value of an
Dan Gohman45774ce2010-02-12 10:34:29 +00001096 /// induction variable, this variable is non-null and holds the loop
1097 /// associated with the induction variable.
Dan Gohmand006ab92010-04-07 22:27:08 +00001098 PostIncLoopSet PostIncLoops;
Dan Gohman45774ce2010-02-12 10:34:29 +00001099
1100 /// LUIdx - The index of the LSRUse describing the expression which
1101 /// this fixup needs, minus an offset (below).
1102 size_t LUIdx;
1103
1104 /// Offset - A constant offset to be added to the LSRUse expression.
1105 /// This allows multiple fixups to share the same LSRUse with different
1106 /// offsets, for example in an unrolled loop.
1107 int64_t Offset;
1108
Dan Gohmand006ab92010-04-07 22:27:08 +00001109 bool isUseFullyOutsideLoop(const Loop *L) const;
1110
Dan Gohman45774ce2010-02-12 10:34:29 +00001111 LSRFixup();
1112
1113 void print(raw_ostream &OS) const;
1114 void dump() const;
1115};
1116
1117}
1118
1119LSRFixup::LSRFixup()
Craig Topperf40110f2014-04-25 05:29:35 +00001120 : UserInst(nullptr), OperandValToReplace(nullptr), LUIdx(~size_t(0)),
1121 Offset(0) {}
Dan Gohman45774ce2010-02-12 10:34:29 +00001122
Dan Gohmand006ab92010-04-07 22:27:08 +00001123/// isUseFullyOutsideLoop - Test whether this fixup always uses its
1124/// value outside of the given loop.
1125bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
1126 // PHI nodes use their value in their incoming blocks.
1127 if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
1128 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1129 if (PN->getIncomingValue(i) == OperandValToReplace &&
1130 L->contains(PN->getIncomingBlock(i)))
1131 return false;
1132 return true;
1133 }
1134
1135 return !L->contains(UserInst);
1136}
1137
Dan Gohman45774ce2010-02-12 10:34:29 +00001138void LSRFixup::print(raw_ostream &OS) const {
1139 OS << "UserInst=";
1140 // Store is common and interesting enough to be worth special-casing.
1141 if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
1142 OS << "store ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001143 Store->getOperand(0)->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001144 } else if (UserInst->getType()->isVoidTy())
1145 OS << UserInst->getOpcodeName();
1146 else
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001147 UserInst->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001148
1149 OS << ", OperandValToReplace=";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001150 OperandValToReplace->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001151
Dan Gohmand006ab92010-04-07 22:27:08 +00001152 for (PostIncLoopSet::const_iterator I = PostIncLoops.begin(),
1153 E = PostIncLoops.end(); I != E; ++I) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001154 OS << ", PostIncLoop=";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001155 (*I)->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001156 }
1157
1158 if (LUIdx != ~size_t(0))
1159 OS << ", LUIdx=" << LUIdx;
1160
1161 if (Offset != 0)
1162 OS << ", Offset=" << Offset;
1163}
1164
Manman Ren49d684e2012-09-12 05:06:18 +00001165#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman45774ce2010-02-12 10:34:29 +00001166void LSRFixup::dump() const {
1167 print(errs()); errs() << '\n';
1168}
Manman Renc3366cc2012-09-06 19:55:56 +00001169#endif
Dan Gohman45774ce2010-02-12 10:34:29 +00001170
1171namespace {
1172
1173/// UniquifierDenseMapInfo - A DenseMapInfo implementation for holding
1174/// DenseMaps and DenseSets of sorted SmallVectors of const SCEV*.
1175struct UniquifierDenseMapInfo {
Preston Gurd25c3b6a2013-02-01 20:41:27 +00001176 static SmallVector<const SCEV *, 4> getEmptyKey() {
1177 SmallVector<const SCEV *, 4> V;
Dan Gohman45774ce2010-02-12 10:34:29 +00001178 V.push_back(reinterpret_cast<const SCEV *>(-1));
1179 return V;
1180 }
1181
Preston Gurd25c3b6a2013-02-01 20:41:27 +00001182 static SmallVector<const SCEV *, 4> getTombstoneKey() {
1183 SmallVector<const SCEV *, 4> V;
Dan Gohman45774ce2010-02-12 10:34:29 +00001184 V.push_back(reinterpret_cast<const SCEV *>(-2));
1185 return V;
1186 }
1187
Preston Gurd25c3b6a2013-02-01 20:41:27 +00001188 static unsigned getHashValue(const SmallVector<const SCEV *, 4> &V) {
Benjamin Kramer62fb0cf2014-03-15 17:17:48 +00001189 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
Dan Gohman45774ce2010-02-12 10:34:29 +00001190 }
1191
Preston Gurd25c3b6a2013-02-01 20:41:27 +00001192 static bool isEqual(const SmallVector<const SCEV *, 4> &LHS,
1193 const SmallVector<const SCEV *, 4> &RHS) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001194 return LHS == RHS;
1195 }
1196};
1197
1198/// LSRUse - This class holds the state that LSR keeps for each use in
1199/// IVUsers, as well as uses invented by LSR itself. It includes information
1200/// about what kinds of things can be folded into the user, information about
1201/// the user itself, and information about how the use may be satisfied.
1202/// TODO: Represent multiple users of the same expression in common?
1203class LSRUse {
Preston Gurd25c3b6a2013-02-01 20:41:27 +00001204 DenseSet<SmallVector<const SCEV *, 4>, UniquifierDenseMapInfo> Uniquifier;
Dan Gohman45774ce2010-02-12 10:34:29 +00001205
1206public:
1207 /// KindType - An enum for a kind of use, indicating what types of
1208 /// scaled and immediate operands it might support.
1209 enum KindType {
1210 Basic, ///< A normal use, with no folding.
1211 Special, ///< A special case of basic, allowing -1 scales.
Nadav Rotem4dc976f2012-10-19 21:28:43 +00001212 Address, ///< An address use; folding according to TargetLowering
Dan Gohman45774ce2010-02-12 10:34:29 +00001213 ICmpZero ///< An equality icmp with both operands folded into one.
1214 // TODO: Add a generic icmp too?
Dan Gohman045f8192010-01-22 00:46:49 +00001215 };
Dan Gohman45774ce2010-02-12 10:34:29 +00001216
Benjamin Kramer62fb0cf2014-03-15 17:17:48 +00001217 typedef PointerIntPair<const SCEV *, 2, KindType> SCEVUseKindPair;
1218
Dan Gohman45774ce2010-02-12 10:34:29 +00001219 KindType Kind;
Chris Lattner229907c2011-07-18 04:54:35 +00001220 Type *AccessTy;
Dan Gohman45774ce2010-02-12 10:34:29 +00001221
1222 SmallVector<int64_t, 8> Offsets;
1223 int64_t MinOffset;
1224 int64_t MaxOffset;
1225
1226 /// AllFixupsOutsideLoop - This records whether all of the fixups using this
1227 /// LSRUse are outside of the loop, in which case some special-case heuristics
1228 /// may be used.
1229 bool AllFixupsOutsideLoop;
1230
Andrew Trick57243da2013-10-25 21:35:56 +00001231 /// RigidFormula is set to true to guarantee that this use will be associated
1232 /// with a single formula--the one that initially matched. Some SCEV
1233 /// expressions cannot be expanded. This allows LSR to consider the registers
1234 /// used by those expressions without the need to expand them later after
1235 /// changing the formula.
1236 bool RigidFormula;
1237
Dan Gohman14152082010-07-15 20:24:58 +00001238 /// WidestFixupType - This records the widest use type for any fixup using
1239 /// this LSRUse. FindUseWithSimilarFormula can't consider uses with different
1240 /// max fixup widths to be equivalent, because the narrower one may be relying
1241 /// on the implicit truncation to truncate away bogus bits.
Chris Lattner229907c2011-07-18 04:54:35 +00001242 Type *WidestFixupType;
Dan Gohman14152082010-07-15 20:24:58 +00001243
Dan Gohman45774ce2010-02-12 10:34:29 +00001244 /// Formulae - A list of ways to build a value that can satisfy this user.
1245 /// After the list is populated, one of these is selected heuristically and
1246 /// used to formulate a replacement for OperandValToReplace in UserInst.
1247 SmallVector<Formula, 12> Formulae;
1248
1249 /// Regs - The set of register candidates used by all formulae in this LSRUse.
1250 SmallPtrSet<const SCEV *, 4> Regs;
1251
Chris Lattner229907c2011-07-18 04:54:35 +00001252 LSRUse(KindType K, Type *T) : Kind(K), AccessTy(T),
Dan Gohman45774ce2010-02-12 10:34:29 +00001253 MinOffset(INT64_MAX),
1254 MaxOffset(INT64_MIN),
Dan Gohman14152082010-07-15 20:24:58 +00001255 AllFixupsOutsideLoop(true),
Andrew Trick57243da2013-10-25 21:35:56 +00001256 RigidFormula(false),
Craig Topperf40110f2014-04-25 05:29:35 +00001257 WidestFixupType(nullptr) {}
Dan Gohman45774ce2010-02-12 10:34:29 +00001258
Dan Gohman20fab452010-05-19 23:43:12 +00001259 bool HasFormulaWithSameRegs(const Formula &F) const;
Dan Gohman8c16b382010-02-22 04:11:59 +00001260 bool InsertFormula(const Formula &F);
Dan Gohmanf1c7b1b2010-05-18 22:39:15 +00001261 void DeleteFormula(Formula &F);
Dan Gohman4cf99b52010-05-18 23:42:37 +00001262 void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
Dan Gohman45774ce2010-02-12 10:34:29 +00001263
Dan Gohman45774ce2010-02-12 10:34:29 +00001264 void print(raw_ostream &OS) const;
1265 void dump() const;
1266};
1267
Dan Gohman297fb8b2010-06-19 21:21:39 +00001268}
1269
Dan Gohman20fab452010-05-19 23:43:12 +00001270/// HasFormula - Test whether this use as a formula which has the same
1271/// registers as the given formula.
1272bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
Preston Gurd25c3b6a2013-02-01 20:41:27 +00001273 SmallVector<const SCEV *, 4> Key = F.BaseRegs;
Dan Gohman20fab452010-05-19 23:43:12 +00001274 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1275 // Unstable sort by host order ok, because this is only used for uniquifying.
1276 std::sort(Key.begin(), Key.end());
1277 return Uniquifier.count(Key);
1278}
1279
Dan Gohman45774ce2010-02-12 10:34:29 +00001280/// InsertFormula - If the given formula has not yet been inserted, add it to
1281/// the list, and return true. Return false otherwise.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001282/// The formula must be in canonical form.
Dan Gohman8c16b382010-02-22 04:11:59 +00001283bool LSRUse::InsertFormula(const Formula &F) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001284 assert(F.isCanonical() && "Invalid canonical representation");
1285
Andrew Trick57243da2013-10-25 21:35:56 +00001286 if (!Formulae.empty() && RigidFormula)
1287 return false;
1288
Preston Gurd25c3b6a2013-02-01 20:41:27 +00001289 SmallVector<const SCEV *, 4> Key = F.BaseRegs;
Dan Gohman45774ce2010-02-12 10:34:29 +00001290 if (F.ScaledReg) Key.push_back(F.ScaledReg);
1291 // Unstable sort by host order ok, because this is only used for uniquifying.
1292 std::sort(Key.begin(), Key.end());
1293
1294 if (!Uniquifier.insert(Key).second)
1295 return false;
1296
1297 // Using a register to hold the value of 0 is not profitable.
1298 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
1299 "Zero allocated in a scaled register!");
1300#ifndef NDEBUG
1301 for (SmallVectorImpl<const SCEV *>::const_iterator I =
1302 F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I)
1303 assert(!(*I)->isZero() && "Zero allocated in a base register!");
1304#endif
1305
1306 // Add the formula to the list.
1307 Formulae.push_back(F);
1308
1309 // Record registers now being used by this use.
Dan Gohman45774ce2010-02-12 10:34:29 +00001310 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001311 if (F.ScaledReg)
1312 Regs.insert(F.ScaledReg);
Dan Gohman45774ce2010-02-12 10:34:29 +00001313
1314 return true;
Dan Gohman045f8192010-01-22 00:46:49 +00001315}
1316
Dan Gohmanf1c7b1b2010-05-18 22:39:15 +00001317/// DeleteFormula - Remove the given formula from this use's list.
1318void LSRUse::DeleteFormula(Formula &F) {
Dan Gohman80a96082010-05-20 15:17:54 +00001319 if (&F != &Formulae.back())
1320 std::swap(F, Formulae.back());
Dan Gohmanf1c7b1b2010-05-18 22:39:15 +00001321 Formulae.pop_back();
1322}
1323
Dan Gohman4cf99b52010-05-18 23:42:37 +00001324/// RecomputeRegs - Recompute the Regs field, and update RegUses.
1325void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
1326 // Now that we've filtered out some formulae, recompute the Regs set.
Benjamin Kramer1c2beed2015-02-19 17:19:43 +00001327 SmallPtrSet<const SCEV *, 4> OldRegs = std::move(Regs);
Dan Gohman4cf99b52010-05-18 23:42:37 +00001328 Regs.clear();
Benjamin Kramer1c2beed2015-02-19 17:19:43 +00001329 for (const Formula &F : Formulae) {
Dan Gohman4cf99b52010-05-18 23:42:37 +00001330 if (F.ScaledReg) Regs.insert(F.ScaledReg);
1331 Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
1332 }
1333
1334 // Update the RegTracker.
Craig Topper46276792014-08-24 23:23:06 +00001335 for (const SCEV *S : OldRegs)
1336 if (!Regs.count(S))
1337 RegUses.DropRegister(S, LUIdx);
Dan Gohman4cf99b52010-05-18 23:42:37 +00001338}
1339
Dan Gohman45774ce2010-02-12 10:34:29 +00001340void LSRUse::print(raw_ostream &OS) const {
1341 OS << "LSR Use: Kind=";
1342 switch (Kind) {
1343 case Basic: OS << "Basic"; break;
1344 case Special: OS << "Special"; break;
1345 case ICmpZero: OS << "ICmpZero"; break;
1346 case Address:
1347 OS << "Address of ";
Duncan Sands19d0b472010-02-16 11:11:14 +00001348 if (AccessTy->isPointerTy())
Dan Gohman45774ce2010-02-12 10:34:29 +00001349 OS << "pointer"; // the full pointer type could be really verbose
1350 else
1351 OS << *AccessTy;
Evan Cheng133694d2007-10-25 09:11:16 +00001352 }
1353
Dan Gohman45774ce2010-02-12 10:34:29 +00001354 OS << ", Offsets={";
1355 for (SmallVectorImpl<int64_t>::const_iterator I = Offsets.begin(),
1356 E = Offsets.end(); I != E; ++I) {
1357 OS << *I;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001358 if (std::next(I) != E)
Dan Gohman45774ce2010-02-12 10:34:29 +00001359 OS << ',';
Dan Gohman045f8192010-01-22 00:46:49 +00001360 }
Dan Gohman45774ce2010-02-12 10:34:29 +00001361 OS << '}';
Dan Gohman045f8192010-01-22 00:46:49 +00001362
Dan Gohman45774ce2010-02-12 10:34:29 +00001363 if (AllFixupsOutsideLoop)
1364 OS << ", all-fixups-outside-loop";
Dan Gohman14152082010-07-15 20:24:58 +00001365
1366 if (WidestFixupType)
1367 OS << ", widest fixup type: " << *WidestFixupType;
Dan Gohman045f8192010-01-22 00:46:49 +00001368}
1369
Manman Ren49d684e2012-09-12 05:06:18 +00001370#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman45774ce2010-02-12 10:34:29 +00001371void LSRUse::dump() const {
1372 print(errs()); errs() << '\n';
1373}
Manman Renc3366cc2012-09-06 19:55:56 +00001374#endif
Dan Gohman045f8192010-01-22 00:46:49 +00001375
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001376static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1377 LSRUse::KindType Kind, Type *AccessTy,
1378 GlobalValue *BaseGV, int64_t BaseOffset,
1379 bool HasBaseReg, int64_t Scale) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001380 switch (Kind) {
1381 case LSRUse::Address:
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001382 return TTI.isLegalAddressingMode(AccessTy, BaseGV, BaseOffset, HasBaseReg, Scale);
Dan Gohman45774ce2010-02-12 10:34:29 +00001383
Dan Gohman45774ce2010-02-12 10:34:29 +00001384 case LSRUse::ICmpZero:
1385 // There's not even a target hook for querying whether it would be legal to
1386 // fold a GV into an ICmp.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001387 if (BaseGV)
Dan Gohman45774ce2010-02-12 10:34:29 +00001388 return false;
1389
1390 // ICmp only has two operands; don't allow more than two non-trivial parts.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001391 if (Scale != 0 && HasBaseReg && BaseOffset != 0)
Dan Gohman45774ce2010-02-12 10:34:29 +00001392 return false;
1393
1394 // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
1395 // putting the scaled register in the other operand of the icmp.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001396 if (Scale != 0 && Scale != -1)
Dan Gohman45774ce2010-02-12 10:34:29 +00001397 return false;
1398
1399 // If we have low-level target information, ask the target if it can fold an
1400 // integer immediate on an icmp.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001401 if (BaseOffset != 0) {
Jakob Stoklund Olesenf2390e82012-04-05 03:10:56 +00001402 // We have one of:
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001403 // ICmpZero BaseReg + BaseOffset => ICmp BaseReg, -BaseOffset
1404 // ICmpZero -1*ScaleReg + BaseOffset => ICmp ScaleReg, BaseOffset
Jakob Stoklund Olesenf2390e82012-04-05 03:10:56 +00001405 // Offs is the ICmp immediate.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001406 if (Scale == 0)
1407 // The cast does the right thing with INT64_MIN.
1408 BaseOffset = -(uint64_t)BaseOffset;
1409 return TTI.isLegalICmpImmediate(BaseOffset);
Dan Gohman045f8192010-01-22 00:46:49 +00001410 }
Dan Gohman45774ce2010-02-12 10:34:29 +00001411
Jakob Stoklund Olesenf2390e82012-04-05 03:10:56 +00001412 // ICmpZero BaseReg + -1*ScaleReg => ICmp BaseReg, ScaleReg
Dan Gohman45774ce2010-02-12 10:34:29 +00001413 return true;
1414
1415 case LSRUse::Basic:
1416 // Only handle single-register values.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001417 return !BaseGV && Scale == 0 && BaseOffset == 0;
Dan Gohman45774ce2010-02-12 10:34:29 +00001418
1419 case LSRUse::Special:
Andrew Trickaca8fb32012-06-15 20:07:26 +00001420 // Special case Basic to handle -1 scales.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001421 return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset == 0;
Dan Gohman045f8192010-01-22 00:46:49 +00001422 }
1423
David Blaikie46a9f012012-01-20 21:51:11 +00001424 llvm_unreachable("Invalid LSRUse Kind!");
Dan Gohman045f8192010-01-22 00:46:49 +00001425}
1426
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001427static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1428 int64_t MinOffset, int64_t MaxOffset,
1429 LSRUse::KindType Kind, Type *AccessTy,
1430 GlobalValue *BaseGV, int64_t BaseOffset,
1431 bool HasBaseReg, int64_t Scale) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001432 // Check for overflow.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001433 if (((int64_t)((uint64_t)BaseOffset + MinOffset) > BaseOffset) !=
Dan Gohman45774ce2010-02-12 10:34:29 +00001434 (MinOffset > 0))
1435 return false;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001436 MinOffset = (uint64_t)BaseOffset + MinOffset;
1437 if (((int64_t)((uint64_t)BaseOffset + MaxOffset) > BaseOffset) !=
1438 (MaxOffset > 0))
1439 return false;
1440 MaxOffset = (uint64_t)BaseOffset + MaxOffset;
1441
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001442 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MinOffset,
1443 HasBaseReg, Scale) &&
1444 isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MaxOffset,
1445 HasBaseReg, Scale);
1446}
1447
1448static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1449 int64_t MinOffset, int64_t MaxOffset,
1450 LSRUse::KindType Kind, Type *AccessTy,
1451 const Formula &F) {
1452 // For the purpose of isAMCompletelyFolded either having a canonical formula
1453 // or a scale not equal to zero is correct.
1454 // Problems may arise from non canonical formulae having a scale == 0.
1455 // Strictly speaking it would best to just rely on canonical formulae.
1456 // However, when we generate the scaled formulae, we first check that the
1457 // scaling factor is profitable before computing the actual ScaledReg for
1458 // compile time sake.
1459 assert((F.isCanonical() || F.Scale != 0));
1460 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1461 F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale);
1462}
1463
1464/// isLegalUse - Test whether we know how to expand the current formula.
1465static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
1466 int64_t MaxOffset, LSRUse::KindType Kind, Type *AccessTy,
1467 GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg,
1468 int64_t Scale) {
1469 // We know how to expand completely foldable formulae.
1470 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
1471 BaseOffset, HasBaseReg, Scale) ||
1472 // Or formulae that use a base register produced by a sum of base
1473 // registers.
1474 (Scale == 1 &&
1475 isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
1476 BaseGV, BaseOffset, true, 0));
Dan Gohman045f8192010-01-22 00:46:49 +00001477}
1478
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001479static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
1480 int64_t MaxOffset, LSRUse::KindType Kind, Type *AccessTy,
1481 const Formula &F) {
Chandler Carruth6e479322013-01-07 15:04:40 +00001482 return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV,
1483 F.BaseOffset, F.HasBaseReg, F.Scale);
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001484}
1485
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001486static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
1487 const LSRUse &LU, const Formula &F) {
1488 return isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
1489 LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg,
1490 F.Scale);
1491}
Quentin Colombet8aa7abe2013-05-31 17:20:29 +00001492
Quentin Colombetbf490d42013-05-31 21:29:03 +00001493static unsigned getScalingFactorCost(const TargetTransformInfo &TTI,
1494 const LSRUse &LU, const Formula &F) {
1495 if (!F.Scale)
1496 return 0;
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001497
1498 // If the use is not completely folded in that instruction, we will have to
1499 // pay an extra cost only for scale != 1.
1500 if (!isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
1501 LU.AccessTy, F))
1502 return F.Scale != 1;
Quentin Colombetbf490d42013-05-31 21:29:03 +00001503
1504 switch (LU.Kind) {
1505 case LSRUse::Address: {
Quentin Colombet145eb972013-06-19 19:59:41 +00001506 // Check the scaling factor cost with both the min and max offsets.
1507 int ScaleCostMinOffset =
1508 TTI.getScalingFactorCost(LU.AccessTy, F.BaseGV,
1509 F.BaseOffset + LU.MinOffset,
1510 F.HasBaseReg, F.Scale);
1511 int ScaleCostMaxOffset =
1512 TTI.getScalingFactorCost(LU.AccessTy, F.BaseGV,
1513 F.BaseOffset + LU.MaxOffset,
1514 F.HasBaseReg, F.Scale);
1515
1516 assert(ScaleCostMinOffset >= 0 && ScaleCostMaxOffset >= 0 &&
1517 "Legal addressing mode has an illegal cost!");
1518 return std::max(ScaleCostMinOffset, ScaleCostMaxOffset);
Quentin Colombetbf490d42013-05-31 21:29:03 +00001519 }
1520 case LSRUse::ICmpZero:
Quentin Colombetbf490d42013-05-31 21:29:03 +00001521 case LSRUse::Basic:
1522 case LSRUse::Special:
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001523 // The use is completely folded, i.e., everything is folded into the
1524 // instruction.
Quentin Colombetbf490d42013-05-31 21:29:03 +00001525 return 0;
1526 }
1527
1528 llvm_unreachable("Invalid LSRUse Kind!");
1529}
1530
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001531static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
Chris Lattner229907c2011-07-18 04:54:35 +00001532 LSRUse::KindType Kind, Type *AccessTy,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001533 GlobalValue *BaseGV, int64_t BaseOffset,
1534 bool HasBaseReg) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001535 // Fast-path: zero is always foldable.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001536 if (BaseOffset == 0 && !BaseGV) return true;
Dan Gohman045f8192010-01-22 00:46:49 +00001537
Dan Gohman45774ce2010-02-12 10:34:29 +00001538 // Conservatively, create an address with an immediate and a
1539 // base and a scale.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001540 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
Dan Gohman045f8192010-01-22 00:46:49 +00001541
Dan Gohman20fab452010-05-19 23:43:12 +00001542 // Canonicalize a scale of 1 to a base register if the formula doesn't
1543 // already have a base register.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001544 if (!HasBaseReg && Scale == 1) {
1545 Scale = 0;
1546 HasBaseReg = true;
Dan Gohman20fab452010-05-19 23:43:12 +00001547 }
1548
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001549 return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset,
1550 HasBaseReg, Scale);
Dan Gohman045f8192010-01-22 00:46:49 +00001551}
1552
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001553static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
1554 ScalarEvolution &SE, int64_t MinOffset,
1555 int64_t MaxOffset, LSRUse::KindType Kind,
1556 Type *AccessTy, const SCEV *S, bool HasBaseReg) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001557 // Fast-path: zero is always foldable.
1558 if (S->isZero()) return true;
1559
1560 // Conservatively, create an address with an immediate and a
1561 // base and a scale.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001562 int64_t BaseOffset = ExtractImmediate(S, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +00001563 GlobalValue *BaseGV = ExtractSymbol(S, SE);
1564
1565 // If there's anything else involved, it's not foldable.
1566 if (!S->isZero()) return false;
1567
1568 // Fast-path: zero is always foldable.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001569 if (BaseOffset == 0 && !BaseGV) return true;
Dan Gohman45774ce2010-02-12 10:34:29 +00001570
1571 // Conservatively, create an address with an immediate and a
1572 // base and a scale.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001573 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
Dan Gohman45774ce2010-02-12 10:34:29 +00001574
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001575 return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
1576 BaseOffset, HasBaseReg, Scale);
Dan Gohman045f8192010-01-22 00:46:49 +00001577}
1578
Dan Gohman297fb8b2010-06-19 21:21:39 +00001579namespace {
1580
Andrew Trick29fe5f02012-01-09 19:50:34 +00001581/// IVInc - An individual increment in a Chain of IV increments.
1582/// Relate an IV user to an expression that computes the IV it uses from the IV
1583/// used by the previous link in the Chain.
1584///
1585/// For the head of a chain, IncExpr holds the absolute SCEV expression for the
1586/// original IVOperand. The head of the chain's IVOperand is only valid during
1587/// chain collection, before LSR replaces IV users. During chain generation,
1588/// IncExpr can be used to find the new IVOperand that computes the same
1589/// expression.
1590struct IVInc {
1591 Instruction *UserInst;
1592 Value* IVOperand;
1593 const SCEV *IncExpr;
1594
1595 IVInc(Instruction *U, Value *O, const SCEV *E):
1596 UserInst(U), IVOperand(O), IncExpr(E) {}
1597};
1598
1599// IVChain - The list of IV increments in program order.
1600// We typically add the head of a chain without finding subsequent links.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001601struct IVChain {
1602 SmallVector<IVInc,1> Incs;
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00001603 const SCEV *ExprBase;
1604
Craig Topperf40110f2014-04-25 05:29:35 +00001605 IVChain() : ExprBase(nullptr) {}
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00001606
1607 IVChain(const IVInc &Head, const SCEV *Base)
1608 : Incs(1, Head), ExprBase(Base) {}
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001609
1610 typedef SmallVectorImpl<IVInc>::const_iterator const_iterator;
1611
1612 // begin - return the first increment in the chain.
1613 const_iterator begin() const {
1614 assert(!Incs.empty());
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001615 return std::next(Incs.begin());
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001616 }
1617 const_iterator end() const {
1618 return Incs.end();
1619 }
1620
1621 // hasIncs - Returns true if this chain contains any increments.
1622 bool hasIncs() const { return Incs.size() >= 2; }
1623
1624 // add - Add an IVInc to the end of this chain.
1625 void add(const IVInc &X) { Incs.push_back(X); }
1626
1627 // tailUserInst - Returns the last UserInst in the chain.
1628 Instruction *tailUserInst() const { return Incs.back().UserInst; }
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00001629
1630 // isProfitableIncrement - Returns true if IncExpr can be profitably added to
1631 // this chain.
1632 bool isProfitableIncrement(const SCEV *OperExpr,
1633 const SCEV *IncExpr,
1634 ScalarEvolution&);
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00001635};
Andrew Trick29fe5f02012-01-09 19:50:34 +00001636
1637/// ChainUsers - Helper for CollectChains to track multiple IV increment uses.
1638/// Distinguish between FarUsers that definitely cross IV increments and
1639/// NearUsers that may be used between IV increments.
1640struct ChainUsers {
1641 SmallPtrSet<Instruction*, 4> FarUsers;
1642 SmallPtrSet<Instruction*, 4> NearUsers;
1643};
1644
Dan Gohman45774ce2010-02-12 10:34:29 +00001645/// LSRInstance - This class holds state for the main loop strength reduction
1646/// logic.
1647class LSRInstance {
1648 IVUsers &IU;
1649 ScalarEvolution &SE;
1650 DominatorTree &DT;
Dan Gohman607e02b2010-04-09 22:07:05 +00001651 LoopInfo &LI;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001652 const TargetTransformInfo &TTI;
Dan Gohman45774ce2010-02-12 10:34:29 +00001653 Loop *const L;
1654 bool Changed;
1655
1656 /// IVIncInsertPos - This is the insert position that the current loop's
1657 /// induction variable increment should be placed. In simple loops, this is
1658 /// the latch block's terminator. But in more complicated cases, this is a
1659 /// position which will dominate all the in-loop post-increment users.
1660 Instruction *IVIncInsertPos;
1661
1662 /// Factors - Interesting factors between use strides.
1663 SmallSetVector<int64_t, 8> Factors;
1664
1665 /// Types - Interesting use types, to facilitate truncation reuse.
Chris Lattner229907c2011-07-18 04:54:35 +00001666 SmallSetVector<Type *, 4> Types;
Dan Gohman45774ce2010-02-12 10:34:29 +00001667
1668 /// Fixups - The list of operands which are to be replaced.
1669 SmallVector<LSRFixup, 16> Fixups;
1670
1671 /// Uses - The list of interesting uses.
1672 SmallVector<LSRUse, 16> Uses;
1673
1674 /// RegUses - Track which uses use which register candidates.
1675 RegUseTracker RegUses;
1676
Andrew Trick29fe5f02012-01-09 19:50:34 +00001677 // Limit the number of chains to avoid quadratic behavior. We don't expect to
1678 // have more than a few IV increment chains in a loop. Missing a Chain falls
1679 // back to normal LSR behavior for those uses.
1680 static const unsigned MaxChains = 8;
1681
1682 /// IVChainVec - IV users can form a chain of IV increments.
1683 SmallVector<IVChain, MaxChains> IVChainVec;
1684
Andrew Trick248d4102012-01-09 21:18:52 +00001685 /// IVIncSet - IV users that belong to profitable IVChains.
1686 SmallPtrSet<Use*, MaxChains> IVIncSet;
1687
Dan Gohman45774ce2010-02-12 10:34:29 +00001688 void OptimizeShadowIV();
1689 bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
1690 ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
Dan Gohman4c4043c2010-05-20 20:05:31 +00001691 void OptimizeLoopTermCond();
Dan Gohman45774ce2010-02-12 10:34:29 +00001692
Andrew Trick29fe5f02012-01-09 19:50:34 +00001693 void ChainInstruction(Instruction *UserInst, Instruction *IVOper,
1694 SmallVectorImpl<ChainUsers> &ChainUsersVec);
Andrew Trick248d4102012-01-09 21:18:52 +00001695 void FinalizeChain(IVChain &Chain);
Andrew Trick29fe5f02012-01-09 19:50:34 +00001696 void CollectChains();
Andrew Trick248d4102012-01-09 21:18:52 +00001697 void GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
1698 SmallVectorImpl<WeakVH> &DeadInsts);
Andrew Trick29fe5f02012-01-09 19:50:34 +00001699
Dan Gohman45774ce2010-02-12 10:34:29 +00001700 void CollectInterestingTypesAndFactors();
1701 void CollectFixupsAndInitialFormulae();
1702
1703 LSRFixup &getNewFixup() {
1704 Fixups.push_back(LSRFixup());
1705 return Fixups.back();
1706 }
1707
1708 // Support for sharing of LSRUses between LSRFixups.
Benjamin Kramer62fb0cf2014-03-15 17:17:48 +00001709 typedef DenseMap<LSRUse::SCEVUseKindPair, size_t> UseMapTy;
Dan Gohman45774ce2010-02-12 10:34:29 +00001710 UseMapTy UseMap;
1711
Dan Gohman110ed642010-09-01 01:45:53 +00001712 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
Chris Lattner229907c2011-07-18 04:54:35 +00001713 LSRUse::KindType Kind, Type *AccessTy);
Dan Gohman45774ce2010-02-12 10:34:29 +00001714
1715 std::pair<size_t, int64_t> getUse(const SCEV *&Expr,
1716 LSRUse::KindType Kind,
Chris Lattner229907c2011-07-18 04:54:35 +00001717 Type *AccessTy);
Dan Gohman45774ce2010-02-12 10:34:29 +00001718
Dan Gohmana7b68d62010-10-07 23:33:43 +00001719 void DeleteUse(LSRUse &LU, size_t LUIdx);
Dan Gohman80a96082010-05-20 15:17:54 +00001720
Dan Gohman110ed642010-09-01 01:45:53 +00001721 LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
Dan Gohman20fab452010-05-19 23:43:12 +00001722
Dan Gohman8c16b382010-02-22 04:11:59 +00001723 void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
Dan Gohman45774ce2010-02-12 10:34:29 +00001724 void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
1725 void CountRegisters(const Formula &F, size_t LUIdx);
1726 bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
1727
1728 void CollectLoopInvariantFixupsAndFormulae();
1729
1730 void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
1731 unsigned Depth = 0);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001732
1733 void GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
1734 const Formula &Base, unsigned Depth,
1735 size_t Idx, bool IsScaledReg = false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001736 void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001737 void GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
1738 const Formula &Base, size_t Idx,
1739 bool IsScaledReg = false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001740 void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00001741 void GenerateConstantOffsetsImpl(LSRUse &LU, unsigned LUIdx,
1742 const Formula &Base,
1743 const SmallVectorImpl<int64_t> &Worklist,
1744 size_t Idx, bool IsScaledReg = false);
Dan Gohman45774ce2010-02-12 10:34:29 +00001745 void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
1746 void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1747 void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
1748 void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
1749 void GenerateCrossUseConstantOffsets();
1750 void GenerateAllReuseFormulae();
1751
1752 void FilterOutUndesirableDedicatedRegisters();
Dan Gohmana4eca052010-05-18 22:51:59 +00001753
1754 size_t EstimateSearchSpaceComplexity() const;
Dan Gohmane9e08732010-08-29 16:09:42 +00001755 void NarrowSearchSpaceByDetectingSupersets();
1756 void NarrowSearchSpaceByCollapsingUnrolledCode();
Dan Gohman002ff892010-08-29 16:39:22 +00001757 void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
Dan Gohmane9e08732010-08-29 16:09:42 +00001758 void NarrowSearchSpaceByPickingWinnerRegs();
Dan Gohman45774ce2010-02-12 10:34:29 +00001759 void NarrowSearchSpaceUsingHeuristics();
1760
1761 void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
1762 Cost &SolutionCost,
1763 SmallVectorImpl<const Formula *> &Workspace,
1764 const Cost &CurCost,
1765 const SmallPtrSet<const SCEV *, 16> &CurRegs,
1766 DenseSet<const SCEV *> &VisitedRegs) const;
1767 void Solve(SmallVectorImpl<const Formula *> &Solution) const;
1768
Dan Gohman607e02b2010-04-09 22:07:05 +00001769 BasicBlock::iterator
1770 HoistInsertPosition(BasicBlock::iterator IP,
1771 const SmallVectorImpl<Instruction *> &Inputs) const;
Andrew Trickc908b432012-01-20 07:41:13 +00001772 BasicBlock::iterator
1773 AdjustInsertPositionForExpand(BasicBlock::iterator IP,
1774 const LSRFixup &LF,
1775 const LSRUse &LU,
1776 SCEVExpander &Rewriter) const;
Dan Gohmand2df6432010-04-09 02:00:38 +00001777
Dan Gohman45774ce2010-02-12 10:34:29 +00001778 Value *Expand(const LSRFixup &LF,
1779 const Formula &F,
Dan Gohman8c16b382010-02-22 04:11:59 +00001780 BasicBlock::iterator IP,
Dan Gohman45774ce2010-02-12 10:34:29 +00001781 SCEVExpander &Rewriter,
Dan Gohman8c16b382010-02-22 04:11:59 +00001782 SmallVectorImpl<WeakVH> &DeadInsts) const;
Dan Gohman6deab962010-02-16 20:25:07 +00001783 void RewriteForPHI(PHINode *PN, const LSRFixup &LF,
1784 const Formula &F,
Dan Gohman6deab962010-02-16 20:25:07 +00001785 SCEVExpander &Rewriter,
1786 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman6deab962010-02-16 20:25:07 +00001787 Pass *P) const;
Dan Gohman45774ce2010-02-12 10:34:29 +00001788 void Rewrite(const LSRFixup &LF,
1789 const Formula &F,
Dan Gohman45774ce2010-02-12 10:34:29 +00001790 SCEVExpander &Rewriter,
1791 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman45774ce2010-02-12 10:34:29 +00001792 Pass *P) const;
1793 void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
1794 Pass *P);
1795
Andrew Trickdc18e382011-12-13 00:55:33 +00001796public:
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001797 LSRInstance(Loop *L, Pass *P);
Dan Gohman45774ce2010-02-12 10:34:29 +00001798
1799 bool getChanged() const { return Changed; }
1800
1801 void print_factors_and_types(raw_ostream &OS) const;
1802 void print_fixups(raw_ostream &OS) const;
1803 void print_uses(raw_ostream &OS) const;
1804 void print(raw_ostream &OS) const;
1805 void dump() const;
1806};
1807
1808}
1809
1810/// OptimizeShadowIV - If IV is used in a int-to-float cast
Dan Gohman8b0a4192010-03-01 17:49:51 +00001811/// inside the loop then try to eliminate the cast operation.
Dan Gohman45774ce2010-02-12 10:34:29 +00001812void LSRInstance::OptimizeShadowIV() {
1813 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1814 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1815 return;
1816
1817 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
1818 UI != E; /* empty */) {
1819 IVUsers::const_iterator CandidateUI = UI;
1820 ++UI;
1821 Instruction *ShadowUse = CandidateUI->getUser();
Craig Topperf40110f2014-04-25 05:29:35 +00001822 Type *DestTy = nullptr;
Andrew Trick858e9f02011-07-21 01:05:01 +00001823 bool IsSigned = false;
Dan Gohman45774ce2010-02-12 10:34:29 +00001824
1825 /* If shadow use is a int->float cast then insert a second IV
1826 to eliminate this cast.
1827
1828 for (unsigned i = 0; i < n; ++i)
1829 foo((double)i);
1830
1831 is transformed into
1832
1833 double d = 0.0;
1834 for (unsigned i = 0; i < n; ++i, ++d)
1835 foo(d);
1836 */
Andrew Trick858e9f02011-07-21 01:05:01 +00001837 if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) {
1838 IsSigned = false;
Dan Gohman45774ce2010-02-12 10:34:29 +00001839 DestTy = UCast->getDestTy();
Andrew Trick858e9f02011-07-21 01:05:01 +00001840 }
1841 else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) {
1842 IsSigned = true;
Dan Gohman45774ce2010-02-12 10:34:29 +00001843 DestTy = SCast->getDestTy();
Andrew Trick858e9f02011-07-21 01:05:01 +00001844 }
Dan Gohman45774ce2010-02-12 10:34:29 +00001845 if (!DestTy) continue;
1846
Chandler Carruth26c59fa2013-01-07 14:41:08 +00001847 // If target does not support DestTy natively then do not apply
1848 // this transformation.
1849 if (!TTI.isTypeLegal(DestTy)) continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00001850
1851 PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
1852 if (!PH) continue;
1853 if (PH->getNumIncomingValues() != 2) continue;
1854
Chris Lattner229907c2011-07-18 04:54:35 +00001855 Type *SrcTy = PH->getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00001856 int Mantissa = DestTy->getFPMantissaWidth();
1857 if (Mantissa == -1) continue;
1858 if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
1859 continue;
1860
1861 unsigned Entry, Latch;
1862 if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
1863 Entry = 0;
1864 Latch = 1;
Dan Gohman045f8192010-01-22 00:46:49 +00001865 } else {
Dan Gohman45774ce2010-02-12 10:34:29 +00001866 Entry = 1;
1867 Latch = 0;
Dan Gohman045f8192010-01-22 00:46:49 +00001868 }
Dan Gohman045f8192010-01-22 00:46:49 +00001869
Dan Gohman45774ce2010-02-12 10:34:29 +00001870 ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
1871 if (!Init) continue;
Andrew Trick858e9f02011-07-21 01:05:01 +00001872 Constant *NewInit = ConstantFP::get(DestTy, IsSigned ?
Andrew Trickbd243d02011-07-21 01:45:54 +00001873 (double)Init->getSExtValue() :
1874 (double)Init->getZExtValue());
Dan Gohman045f8192010-01-22 00:46:49 +00001875
Dan Gohman45774ce2010-02-12 10:34:29 +00001876 BinaryOperator *Incr =
1877 dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
1878 if (!Incr) continue;
1879 if (Incr->getOpcode() != Instruction::Add
1880 && Incr->getOpcode() != Instruction::Sub)
Dan Gohman045f8192010-01-22 00:46:49 +00001881 continue;
Dan Gohman045f8192010-01-22 00:46:49 +00001882
Dan Gohman45774ce2010-02-12 10:34:29 +00001883 /* Initialize new IV, double d = 0.0 in above example. */
Craig Topperf40110f2014-04-25 05:29:35 +00001884 ConstantInt *C = nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +00001885 if (Incr->getOperand(0) == PH)
1886 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
1887 else if (Incr->getOperand(1) == PH)
1888 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
Dan Gohman045f8192010-01-22 00:46:49 +00001889 else
Dan Gohman045f8192010-01-22 00:46:49 +00001890 continue;
1891
Dan Gohman45774ce2010-02-12 10:34:29 +00001892 if (!C) continue;
Dan Gohman045f8192010-01-22 00:46:49 +00001893
Dan Gohman45774ce2010-02-12 10:34:29 +00001894 // Ignore negative constants, as the code below doesn't handle them
1895 // correctly. TODO: Remove this restriction.
1896 if (!C->getValue().isStrictlyPositive()) continue;
Dan Gohman045f8192010-01-22 00:46:49 +00001897
Dan Gohman45774ce2010-02-12 10:34:29 +00001898 /* Add new PHINode. */
Jay Foad52131342011-03-30 11:28:46 +00001899 PHINode *NewPH = PHINode::Create(DestTy, 2, "IV.S.", PH);
Dan Gohman045f8192010-01-22 00:46:49 +00001900
Dan Gohman45774ce2010-02-12 10:34:29 +00001901 /* create new increment. '++d' in above example. */
1902 Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
1903 BinaryOperator *NewIncr =
1904 BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
1905 Instruction::FAdd : Instruction::FSub,
1906 NewPH, CFP, "IV.S.next.", Incr);
Dan Gohman045f8192010-01-22 00:46:49 +00001907
Dan Gohman45774ce2010-02-12 10:34:29 +00001908 NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
1909 NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
Dan Gohman045f8192010-01-22 00:46:49 +00001910
Dan Gohman45774ce2010-02-12 10:34:29 +00001911 /* Remove cast operation */
1912 ShadowUse->replaceAllUsesWith(NewPH);
1913 ShadowUse->eraseFromParent();
Dan Gohman4c4043c2010-05-20 20:05:31 +00001914 Changed = true;
Dan Gohman45774ce2010-02-12 10:34:29 +00001915 break;
Dan Gohman045f8192010-01-22 00:46:49 +00001916 }
1917}
1918
1919/// FindIVUserForCond - If Cond has an operand that is an expression of an IV,
1920/// set the IV user and stride information and return true, otherwise return
1921/// false.
Dan Gohmanab5fb7f2010-05-20 19:44:23 +00001922bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) {
Dan Gohman45774ce2010-02-12 10:34:29 +00001923 for (IVUsers::iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
1924 if (UI->getUser() == Cond) {
1925 // NOTE: we could handle setcc instructions with multiple uses here, but
1926 // InstCombine does it as well for simple uses, it's not clear that it
1927 // occurs enough in real life to handle.
1928 CondUse = UI;
1929 return true;
1930 }
Dan Gohman045f8192010-01-22 00:46:49 +00001931 return false;
Evan Cheng133694d2007-10-25 09:11:16 +00001932}
1933
Dan Gohman045f8192010-01-22 00:46:49 +00001934/// OptimizeMax - Rewrite the loop's terminating condition if it uses
1935/// a max computation.
1936///
1937/// This is a narrow solution to a specific, but acute, problem. For loops
1938/// like this:
1939///
1940/// i = 0;
1941/// do {
1942/// p[i] = 0.0;
1943/// } while (++i < n);
1944///
1945/// the trip count isn't just 'n', because 'n' might not be positive. And
1946/// unfortunately this can come up even for loops where the user didn't use
1947/// a C do-while loop. For example, seemingly well-behaved top-test loops
1948/// will commonly be lowered like this:
1949//
1950/// if (n > 0) {
1951/// i = 0;
1952/// do {
1953/// p[i] = 0.0;
1954/// } while (++i < n);
1955/// }
1956///
1957/// and then it's possible for subsequent optimization to obscure the if
1958/// test in such a way that indvars can't find it.
1959///
1960/// When indvars can't find the if test in loops like this, it creates a
1961/// max expression, which allows it to give the loop a canonical
1962/// induction variable:
1963///
1964/// i = 0;
1965/// max = n < 1 ? 1 : n;
1966/// do {
1967/// p[i] = 0.0;
1968/// } while (++i != max);
1969///
1970/// Canonical induction variables are necessary because the loop passes
1971/// are designed around them. The most obvious example of this is the
1972/// LoopInfo analysis, which doesn't remember trip count values. It
1973/// expects to be able to rediscover the trip count each time it is
Dan Gohman45774ce2010-02-12 10:34:29 +00001974/// needed, and it does this using a simple analysis that only succeeds if
Dan Gohman045f8192010-01-22 00:46:49 +00001975/// the loop has a canonical induction variable.
1976///
1977/// However, when it comes time to generate code, the maximum operation
1978/// can be quite costly, especially if it's inside of an outer loop.
1979///
1980/// This function solves this problem by detecting this type of loop and
1981/// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
1982/// the instructions for the maximum computation.
1983///
Dan Gohman45774ce2010-02-12 10:34:29 +00001984ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
Dan Gohman045f8192010-01-22 00:46:49 +00001985 // Check that the loop matches the pattern we're looking for.
1986 if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
1987 Cond->getPredicate() != CmpInst::ICMP_NE)
1988 return Cond;
Dan Gohman51ad99d2010-01-21 02:09:26 +00001989
Dan Gohman045f8192010-01-22 00:46:49 +00001990 SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
1991 if (!Sel || !Sel->hasOneUse()) return Cond;
Dan Gohman51ad99d2010-01-21 02:09:26 +00001992
Dan Gohman45774ce2010-02-12 10:34:29 +00001993 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
Dan Gohman045f8192010-01-22 00:46:49 +00001994 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1995 return Cond;
Dan Gohman1d2ded72010-05-03 22:09:21 +00001996 const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001997
Dan Gohman045f8192010-01-22 00:46:49 +00001998 // Add one to the backedge-taken count to get the trip count.
Dan Gohman9b7632d2010-08-16 15:39:27 +00001999 const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount);
Dan Gohman534ba372010-04-24 03:13:44 +00002000 if (IterationCount != SE.getSCEV(Sel)) return Cond;
Dan Gohman045f8192010-01-22 00:46:49 +00002001
Dan Gohman534ba372010-04-24 03:13:44 +00002002 // Check for a max calculation that matches the pattern. There's no check
2003 // for ICMP_ULE here because the comparison would be with zero, which
2004 // isn't interesting.
2005 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
Craig Topperf40110f2014-04-25 05:29:35 +00002006 const SCEVNAryExpr *Max = nullptr;
Dan Gohman534ba372010-04-24 03:13:44 +00002007 if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
2008 Pred = ICmpInst::ICMP_SLE;
2009 Max = S;
2010 } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
2011 Pred = ICmpInst::ICMP_SLT;
2012 Max = S;
2013 } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
2014 Pred = ICmpInst::ICMP_ULT;
2015 Max = U;
2016 } else {
2017 // No match; bail.
Dan Gohman045f8192010-01-22 00:46:49 +00002018 return Cond;
Dan Gohman534ba372010-04-24 03:13:44 +00002019 }
Dan Gohman045f8192010-01-22 00:46:49 +00002020
2021 // To handle a max with more than two operands, this optimization would
2022 // require additional checking and setup.
2023 if (Max->getNumOperands() != 2)
2024 return Cond;
2025
2026 const SCEV *MaxLHS = Max->getOperand(0);
2027 const SCEV *MaxRHS = Max->getOperand(1);
Dan Gohman534ba372010-04-24 03:13:44 +00002028
2029 // ScalarEvolution canonicalizes constants to the left. For < and >, look
2030 // for a comparison with 1. For <= and >=, a comparison with zero.
2031 if (!MaxLHS ||
2032 (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
2033 return Cond;
2034
Dan Gohman045f8192010-01-22 00:46:49 +00002035 // Check the relevant induction variable for conformance to
2036 // the pattern.
Dan Gohman45774ce2010-02-12 10:34:29 +00002037 const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
Dan Gohman045f8192010-01-22 00:46:49 +00002038 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
2039 if (!AR || !AR->isAffine() ||
2040 AR->getStart() != One ||
Dan Gohman45774ce2010-02-12 10:34:29 +00002041 AR->getStepRecurrence(SE) != One)
Dan Gohman045f8192010-01-22 00:46:49 +00002042 return Cond;
2043
2044 assert(AR->getLoop() == L &&
2045 "Loop condition operand is an addrec in a different loop!");
2046
2047 // Check the right operand of the select, and remember it, as it will
2048 // be used in the new comparison instruction.
Craig Topperf40110f2014-04-25 05:29:35 +00002049 Value *NewRHS = nullptr;
Dan Gohman534ba372010-04-24 03:13:44 +00002050 if (ICmpInst::isTrueWhenEqual(Pred)) {
2051 // Look for n+1, and grab n.
2052 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
Jakub Staszakf6df1e32013-03-24 09:25:47 +00002053 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2054 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
2055 NewRHS = BO->getOperand(0);
Dan Gohman534ba372010-04-24 03:13:44 +00002056 if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
Jakub Staszakf6df1e32013-03-24 09:25:47 +00002057 if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2058 if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
2059 NewRHS = BO->getOperand(0);
Dan Gohman534ba372010-04-24 03:13:44 +00002060 if (!NewRHS)
2061 return Cond;
2062 } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
Dan Gohman045f8192010-01-22 00:46:49 +00002063 NewRHS = Sel->getOperand(1);
Dan Gohman45774ce2010-02-12 10:34:29 +00002064 else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
Dan Gohman045f8192010-01-22 00:46:49 +00002065 NewRHS = Sel->getOperand(2);
Dan Gohman1081f1a2010-06-22 23:07:13 +00002066 else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
2067 NewRHS = SU->getValue();
Dan Gohman534ba372010-04-24 03:13:44 +00002068 else
Dan Gohman1081f1a2010-06-22 23:07:13 +00002069 // Max doesn't match expected pattern.
2070 return Cond;
Dan Gohman045f8192010-01-22 00:46:49 +00002071
2072 // Determine the new comparison opcode. It may be signed or unsigned,
2073 // and the original comparison may be either equality or inequality.
Dan Gohman045f8192010-01-22 00:46:49 +00002074 if (Cond->getPredicate() == CmpInst::ICMP_EQ)
2075 Pred = CmpInst::getInversePredicate(Pred);
2076
2077 // Ok, everything looks ok to change the condition into an SLT or SGE and
2078 // delete the max calculation.
2079 ICmpInst *NewCond =
2080 new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
2081
2082 // Delete the max calculation instructions.
2083 Cond->replaceAllUsesWith(NewCond);
2084 CondUse->setUser(NewCond);
2085 Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
2086 Cond->eraseFromParent();
2087 Sel->eraseFromParent();
2088 if (Cmp->use_empty())
2089 Cmp->eraseFromParent();
2090 return NewCond;
Dan Gohman68e77352008-09-15 21:22:06 +00002091}
2092
Jim Grosbach60f48542009-11-17 17:53:56 +00002093/// OptimizeLoopTermCond - Change loop terminating condition to use the
Evan Cheng85a9f432009-11-12 07:35:05 +00002094/// postinc iv when possible.
Dan Gohman4c4043c2010-05-20 20:05:31 +00002095void
Dan Gohman45774ce2010-02-12 10:34:29 +00002096LSRInstance::OptimizeLoopTermCond() {
2097 SmallPtrSet<Instruction *, 4> PostIncs;
2098
Evan Cheng85a9f432009-11-12 07:35:05 +00002099 BasicBlock *LatchBlock = L->getLoopLatch();
Evan Chengba4e5da72009-11-17 18:10:11 +00002100 SmallVector<BasicBlock*, 8> ExitingBlocks;
2101 L->getExitingBlocks(ExitingBlocks);
Jim Grosbach60f48542009-11-17 17:53:56 +00002102
Evan Chengba4e5da72009-11-17 18:10:11 +00002103 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
2104 BasicBlock *ExitingBlock = ExitingBlocks[i];
Evan Cheng85a9f432009-11-12 07:35:05 +00002105
Dan Gohman45774ce2010-02-12 10:34:29 +00002106 // Get the terminating condition for the loop if possible. If we
Evan Chengba4e5da72009-11-17 18:10:11 +00002107 // can, we want to change it to use a post-incremented version of its
2108 // induction variable, to allow coalescing the live ranges for the IV into
2109 // one register value.
Evan Cheng85a9f432009-11-12 07:35:05 +00002110
Evan Chengba4e5da72009-11-17 18:10:11 +00002111 BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2112 if (!TermBr)
2113 continue;
2114 // FIXME: Overly conservative, termination condition could be an 'or' etc..
2115 if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
2116 continue;
Evan Cheng85a9f432009-11-12 07:35:05 +00002117
Evan Chengba4e5da72009-11-17 18:10:11 +00002118 // Search IVUsesByStride to find Cond's IVUse if there is one.
Craig Topperf40110f2014-04-25 05:29:35 +00002119 IVStrideUse *CondUse = nullptr;
Evan Chengba4e5da72009-11-17 18:10:11 +00002120 ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
Dan Gohman45774ce2010-02-12 10:34:29 +00002121 if (!FindIVUserForCond(Cond, CondUse))
Evan Chengba4e5da72009-11-17 18:10:11 +00002122 continue;
2123
Evan Chengba4e5da72009-11-17 18:10:11 +00002124 // If the trip count is computed in terms of a max (due to ScalarEvolution
2125 // being unable to find a sufficient guard, for example), change the loop
2126 // comparison to use SLT or ULT instead of NE.
Dan Gohman45774ce2010-02-12 10:34:29 +00002127 // One consequence of doing this now is that it disrupts the count-down
2128 // optimization. That's not always a bad thing though, because in such
2129 // cases it may still be worthwhile to avoid a max.
2130 Cond = OptimizeMax(Cond, CondUse);
Evan Chengba4e5da72009-11-17 18:10:11 +00002131
Dan Gohman45774ce2010-02-12 10:34:29 +00002132 // If this exiting block dominates the latch block, it may also use
2133 // the post-inc value if it won't be shared with other uses.
2134 // Check for dominance.
2135 if (!DT.dominates(ExitingBlock, LatchBlock))
Dan Gohman045f8192010-01-22 00:46:49 +00002136 continue;
Evan Chengba4e5da72009-11-17 18:10:11 +00002137
Dan Gohman45774ce2010-02-12 10:34:29 +00002138 // Conservatively avoid trying to use the post-inc value in non-latch
2139 // exits if there may be pre-inc users in intervening blocks.
Dan Gohman2d0f96d2010-02-14 03:21:49 +00002140 if (LatchBlock != ExitingBlock)
Dan Gohman45774ce2010-02-12 10:34:29 +00002141 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
2142 // Test if the use is reachable from the exiting block. This dominator
2143 // query is a conservative approximation of reachability.
2144 if (&*UI != CondUse &&
2145 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
2146 // Conservatively assume there may be reuse if the quotient of their
2147 // strides could be a legal scale.
Dan Gohmane637ff52010-04-19 21:48:58 +00002148 const SCEV *A = IU.getStride(*CondUse, L);
2149 const SCEV *B = IU.getStride(*UI, L);
Dan Gohmand006ab92010-04-07 22:27:08 +00002150 if (!A || !B) continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00002151 if (SE.getTypeSizeInBits(A->getType()) !=
2152 SE.getTypeSizeInBits(B->getType())) {
2153 if (SE.getTypeSizeInBits(A->getType()) >
2154 SE.getTypeSizeInBits(B->getType()))
2155 B = SE.getSignExtendExpr(B, A->getType());
2156 else
2157 A = SE.getSignExtendExpr(A, B->getType());
2158 }
2159 if (const SCEVConstant *D =
Dan Gohman4eebb942010-02-19 19:35:48 +00002160 dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
Dan Gohman86110fa2010-05-20 22:25:20 +00002161 const ConstantInt *C = D->getValue();
Dan Gohman45774ce2010-02-12 10:34:29 +00002162 // Stride of one or negative one can have reuse with non-addresses.
Dan Gohman86110fa2010-05-20 22:25:20 +00002163 if (C->isOne() || C->isAllOnesValue())
Dan Gohman45774ce2010-02-12 10:34:29 +00002164 goto decline_post_inc;
2165 // Avoid weird situations.
Dan Gohman86110fa2010-05-20 22:25:20 +00002166 if (C->getValue().getMinSignedBits() >= 64 ||
2167 C->getValue().isMinSignedValue())
Dan Gohman45774ce2010-02-12 10:34:29 +00002168 goto decline_post_inc;
2169 // Check for possible scaled-address reuse.
Chris Lattner229907c2011-07-18 04:54:35 +00002170 Type *AccessTy = getAccessType(UI->getUser());
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002171 int64_t Scale = C->getSExtValue();
Craig Topperf40110f2014-04-25 05:29:35 +00002172 if (TTI.isLegalAddressingMode(AccessTy, /*BaseGV=*/ nullptr,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002173 /*BaseOffset=*/ 0,
2174 /*HasBaseReg=*/ false, Scale))
Dan Gohman45774ce2010-02-12 10:34:29 +00002175 goto decline_post_inc;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002176 Scale = -Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00002177 if (TTI.isLegalAddressingMode(AccessTy, /*BaseGV=*/ nullptr,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002178 /*BaseOffset=*/ 0,
2179 /*HasBaseReg=*/ false, Scale))
Dan Gohman45774ce2010-02-12 10:34:29 +00002180 goto decline_post_inc;
2181 }
2182 }
2183
David Greene2330f782009-12-23 22:58:38 +00002184 DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
Dan Gohman45774ce2010-02-12 10:34:29 +00002185 << *Cond << '\n');
Evan Chengba4e5da72009-11-17 18:10:11 +00002186
2187 // It's possible for the setcc instruction to be anywhere in the loop, and
2188 // possible for it to have multiple users. If it is not immediately before
2189 // the exiting block branch, move it.
Dan Gohman45774ce2010-02-12 10:34:29 +00002190 if (&*++BasicBlock::iterator(Cond) != TermBr) {
2191 if (Cond->hasOneUse()) {
Evan Chengba4e5da72009-11-17 18:10:11 +00002192 Cond->moveBefore(TermBr);
2193 } else {
Dan Gohman45774ce2010-02-12 10:34:29 +00002194 // Clone the terminating condition and insert into the loopend.
2195 ICmpInst *OldCond = Cond;
Evan Chengba4e5da72009-11-17 18:10:11 +00002196 Cond = cast<ICmpInst>(Cond->clone());
2197 Cond->setName(L->getHeader()->getName() + ".termcond");
2198 ExitingBlock->getInstList().insert(TermBr, Cond);
2199
2200 // Clone the IVUse, as the old use still exists!
Andrew Trickfc4ccb22011-06-21 15:43:52 +00002201 CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
Dan Gohman45774ce2010-02-12 10:34:29 +00002202 TermBr->replaceUsesOfWith(OldCond, Cond);
Evan Chengba4e5da72009-11-17 18:10:11 +00002203 }
Evan Cheng85a9f432009-11-12 07:35:05 +00002204 }
2205
Evan Chengba4e5da72009-11-17 18:10:11 +00002206 // If we get to here, we know that we can transform the setcc instruction to
2207 // use the post-incremented version of the IV, allowing us to coalesce the
2208 // live ranges for the IV correctly.
Dan Gohmand006ab92010-04-07 22:27:08 +00002209 CondUse->transformToPostInc(L);
Evan Chengba4e5da72009-11-17 18:10:11 +00002210 Changed = true;
2211
Dan Gohman45774ce2010-02-12 10:34:29 +00002212 PostIncs.insert(Cond);
2213 decline_post_inc:;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002214 }
Dan Gohman45774ce2010-02-12 10:34:29 +00002215
2216 // Determine an insertion point for the loop induction variable increment. It
2217 // must dominate all the post-inc comparisons we just set up, and it must
2218 // dominate the loop latch edge.
2219 IVIncInsertPos = L->getLoopLatch()->getTerminator();
Craig Topper46276792014-08-24 23:23:06 +00002220 for (Instruction *Inst : PostIncs) {
Dan Gohman45774ce2010-02-12 10:34:29 +00002221 BasicBlock *BB =
2222 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
Craig Topper46276792014-08-24 23:23:06 +00002223 Inst->getParent());
2224 if (BB == Inst->getParent())
2225 IVIncInsertPos = Inst;
Dan Gohman45774ce2010-02-12 10:34:29 +00002226 else if (BB != IVIncInsertPos->getParent())
2227 IVIncInsertPos = BB->getTerminator();
2228 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00002229}
2230
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002231/// reconcileNewOffset - Determine if the given use can accommodate a fixup
Dan Gohmana4ca28a2010-05-20 20:52:00 +00002232/// at the given offset and other details. If so, update the use and
2233/// return true.
Dan Gohman45774ce2010-02-12 10:34:29 +00002234bool
Dan Gohman110ed642010-09-01 01:45:53 +00002235LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
Chris Lattner229907c2011-07-18 04:54:35 +00002236 LSRUse::KindType Kind, Type *AccessTy) {
Dan Gohman110ed642010-09-01 01:45:53 +00002237 int64_t NewMinOffset = LU.MinOffset;
2238 int64_t NewMaxOffset = LU.MaxOffset;
Chris Lattner229907c2011-07-18 04:54:35 +00002239 Type *NewAccessTy = AccessTy;
Dan Gohman045f8192010-01-22 00:46:49 +00002240
Dan Gohman45774ce2010-02-12 10:34:29 +00002241 // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
2242 // something conservative, however this can pessimize in the case that one of
2243 // the uses will have all its uses outside the loop, for example.
2244 if (LU.Kind != Kind)
Dan Gohman045f8192010-01-22 00:46:49 +00002245 return false;
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00002246
Dan Gohman45774ce2010-02-12 10:34:29 +00002247 // Check for a mismatched access type, and fall back conservatively as needed.
Dan Gohman32655902010-06-19 21:30:18 +00002248 // TODO: Be less conservative when the type is similar and can use the same
2249 // addressing modes.
Dan Gohman45774ce2010-02-12 10:34:29 +00002250 if (Kind == LSRUse::Address && AccessTy != LU.AccessTy)
Dan Gohman110ed642010-09-01 01:45:53 +00002251 NewAccessTy = Type::getVoidTy(AccessTy->getContext());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002252
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00002253 // Conservatively assume HasBaseReg is true for now.
2254 if (NewOffset < LU.MinOffset) {
2255 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
2256 LU.MaxOffset - NewOffset, HasBaseReg))
2257 return false;
2258 NewMinOffset = NewOffset;
2259 } else if (NewOffset > LU.MaxOffset) {
2260 if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
2261 NewOffset - LU.MinOffset, HasBaseReg))
2262 return false;
2263 NewMaxOffset = NewOffset;
2264 }
2265
Dan Gohman45774ce2010-02-12 10:34:29 +00002266 // Update the use.
Dan Gohman110ed642010-09-01 01:45:53 +00002267 LU.MinOffset = NewMinOffset;
2268 LU.MaxOffset = NewMaxOffset;
2269 LU.AccessTy = NewAccessTy;
2270 if (NewOffset != LU.Offsets.back())
2271 LU.Offsets.push_back(NewOffset);
Dan Gohman29916e02010-01-21 22:42:49 +00002272 return true;
2273}
2274
Dan Gohman45774ce2010-02-12 10:34:29 +00002275/// getUse - Return an LSRUse index and an offset value for a fixup which
2276/// needs the given expression, with the given kind and optional access type.
Dan Gohman8b0a4192010-03-01 17:49:51 +00002277/// Either reuse an existing use or create a new one, as needed.
Dan Gohman45774ce2010-02-12 10:34:29 +00002278std::pair<size_t, int64_t>
2279LSRInstance::getUse(const SCEV *&Expr,
Chris Lattner229907c2011-07-18 04:54:35 +00002280 LSRUse::KindType Kind, Type *AccessTy) {
Dan Gohman45774ce2010-02-12 10:34:29 +00002281 const SCEV *Copy = Expr;
2282 int64_t Offset = ExtractImmediate(Expr, SE);
Evan Cheng85a9f432009-11-12 07:35:05 +00002283
Dan Gohman45774ce2010-02-12 10:34:29 +00002284 // Basic uses can't accept any offset, for example.
Craig Topperf40110f2014-04-25 05:29:35 +00002285 if (!isAlwaysFoldable(TTI, Kind, AccessTy, /*BaseGV=*/ nullptr,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002286 Offset, /*HasBaseReg=*/ true)) {
Dan Gohman45774ce2010-02-12 10:34:29 +00002287 Expr = Copy;
2288 Offset = 0;
2289 }
2290
2291 std::pair<UseMapTy::iterator, bool> P =
Benjamin Kramer62fb0cf2014-03-15 17:17:48 +00002292 UseMap.insert(std::make_pair(LSRUse::SCEVUseKindPair(Expr, Kind), 0));
Dan Gohman45774ce2010-02-12 10:34:29 +00002293 if (!P.second) {
2294 // A use already existed with this base.
2295 size_t LUIdx = P.first->second;
2296 LSRUse &LU = Uses[LUIdx];
Dan Gohman110ed642010-09-01 01:45:53 +00002297 if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))
Dan Gohman45774ce2010-02-12 10:34:29 +00002298 // Reuse this use.
2299 return std::make_pair(LUIdx, Offset);
2300 }
2301
2302 // Create a new use.
2303 size_t LUIdx = Uses.size();
2304 P.first->second = LUIdx;
2305 Uses.push_back(LSRUse(Kind, AccessTy));
2306 LSRUse &LU = Uses[LUIdx];
2307
Dan Gohman110ed642010-09-01 01:45:53 +00002308 // We don't need to track redundant offsets, but we don't need to go out
2309 // of our way here to avoid them.
2310 if (LU.Offsets.empty() || Offset != LU.Offsets.back())
2311 LU.Offsets.push_back(Offset);
2312
Dan Gohman45774ce2010-02-12 10:34:29 +00002313 LU.MinOffset = Offset;
2314 LU.MaxOffset = Offset;
2315 return std::make_pair(LUIdx, Offset);
2316}
2317
Dan Gohman80a96082010-05-20 15:17:54 +00002318/// DeleteUse - Delete the given use from the Uses list.
Dan Gohmana7b68d62010-10-07 23:33:43 +00002319void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) {
Dan Gohman110ed642010-09-01 01:45:53 +00002320 if (&LU != &Uses.back())
Dan Gohman80a96082010-05-20 15:17:54 +00002321 std::swap(LU, Uses.back());
2322 Uses.pop_back();
Dan Gohmana7b68d62010-10-07 23:33:43 +00002323
2324 // Update RegUses.
2325 RegUses.SwapAndDropUse(LUIdx, Uses.size());
Dan Gohman80a96082010-05-20 15:17:54 +00002326}
2327
Dan Gohman20fab452010-05-19 23:43:12 +00002328/// FindUseWithFormula - Look for a use distinct from OrigLU which is has
2329/// a formula that has the same registers as the given formula.
2330LSRUse *
2331LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
Dan Gohman110ed642010-09-01 01:45:53 +00002332 const LSRUse &OrigLU) {
2333 // Search all uses for the formula. This could be more clever.
Dan Gohman20fab452010-05-19 23:43:12 +00002334 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2335 LSRUse &LU = Uses[LUIdx];
Dan Gohmanb6a520d2010-08-29 15:27:08 +00002336 // Check whether this use is close enough to OrigLU, to see whether it's
2337 // worthwhile looking through its formulae.
2338 // Ignore ICmpZero uses because they may contain formulae generated by
2339 // GenerateICmpZeroScales, in which case adding fixup offsets may
2340 // be invalid.
Dan Gohman20fab452010-05-19 23:43:12 +00002341 if (&LU != &OrigLU &&
2342 LU.Kind != LSRUse::ICmpZero &&
2343 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
Dan Gohman14152082010-07-15 20:24:58 +00002344 LU.WidestFixupType == OrigLU.WidestFixupType &&
Dan Gohman20fab452010-05-19 23:43:12 +00002345 LU.HasFormulaWithSameRegs(OrigF)) {
Dan Gohmanb6a520d2010-08-29 15:27:08 +00002346 // Scan through this use's formulae.
Dan Gohman927bcaa2010-05-20 20:33:18 +00002347 for (SmallVectorImpl<Formula>::const_iterator I = LU.Formulae.begin(),
2348 E = LU.Formulae.end(); I != E; ++I) {
2349 const Formula &F = *I;
Dan Gohmanb6a520d2010-08-29 15:27:08 +00002350 // Check to see if this formula has the same registers and symbols
2351 // as OrigF.
Dan Gohman20fab452010-05-19 23:43:12 +00002352 if (F.BaseRegs == OrigF.BaseRegs &&
2353 F.ScaledReg == OrigF.ScaledReg &&
Chandler Carruth6e479322013-01-07 15:04:40 +00002354 F.BaseGV == OrigF.BaseGV &&
2355 F.Scale == OrigF.Scale &&
Dan Gohman6136e942011-05-03 00:46:49 +00002356 F.UnfoldedOffset == OrigF.UnfoldedOffset) {
Chandler Carruth6e479322013-01-07 15:04:40 +00002357 if (F.BaseOffset == 0)
Dan Gohman20fab452010-05-19 23:43:12 +00002358 return &LU;
Dan Gohmanb6a520d2010-08-29 15:27:08 +00002359 // This is the formula where all the registers and symbols matched;
2360 // there aren't going to be any others. Since we declined it, we
Benjamin Kramerbde91762012-06-02 10:20:22 +00002361 // can skip the rest of the formulae and proceed to the next LSRUse.
Dan Gohman20fab452010-05-19 23:43:12 +00002362 break;
2363 }
2364 }
2365 }
2366 }
2367
Dan Gohmanb6a520d2010-08-29 15:27:08 +00002368 // Nothing looked good.
Craig Topperf40110f2014-04-25 05:29:35 +00002369 return nullptr;
Dan Gohman20fab452010-05-19 23:43:12 +00002370}
2371
Dan Gohman45774ce2010-02-12 10:34:29 +00002372void LSRInstance::CollectInterestingTypesAndFactors() {
2373 SmallSetVector<const SCEV *, 4> Strides;
2374
Dan Gohman2446f572010-02-19 00:05:23 +00002375 // Collect interesting types and strides.
Dan Gohmand006ab92010-04-07 22:27:08 +00002376 SmallVector<const SCEV *, 4> Worklist;
Dan Gohman45774ce2010-02-12 10:34:29 +00002377 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
Dan Gohmane637ff52010-04-19 21:48:58 +00002378 const SCEV *Expr = IU.getExpr(*UI);
Dan Gohman45774ce2010-02-12 10:34:29 +00002379
2380 // Collect interesting types.
Dan Gohmand006ab92010-04-07 22:27:08 +00002381 Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
Dan Gohman45774ce2010-02-12 10:34:29 +00002382
Dan Gohmand006ab92010-04-07 22:27:08 +00002383 // Add strides for mentioned loops.
2384 Worklist.push_back(Expr);
2385 do {
2386 const SCEV *S = Worklist.pop_back_val();
2387 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
Andrew Trickd97b83e2012-03-22 22:42:45 +00002388 if (AR->getLoop() == L)
Andrew Tricke8b4f402011-12-10 00:25:00 +00002389 Strides.insert(AR->getStepRecurrence(SE));
Dan Gohmand006ab92010-04-07 22:27:08 +00002390 Worklist.push_back(AR->getStart());
2391 } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00002392 Worklist.append(Add->op_begin(), Add->op_end());
Dan Gohmand006ab92010-04-07 22:27:08 +00002393 }
2394 } while (!Worklist.empty());
Dan Gohman2446f572010-02-19 00:05:23 +00002395 }
2396
2397 // Compute interesting factors from the set of interesting strides.
2398 for (SmallSetVector<const SCEV *, 4>::const_iterator
2399 I = Strides.begin(), E = Strides.end(); I != E; ++I)
Dan Gohman45774ce2010-02-12 10:34:29 +00002400 for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002401 std::next(I); NewStrideIter != E; ++NewStrideIter) {
Dan Gohman2446f572010-02-19 00:05:23 +00002402 const SCEV *OldStride = *I;
Dan Gohman45774ce2010-02-12 10:34:29 +00002403 const SCEV *NewStride = *NewStrideIter;
Dan Gohman45774ce2010-02-12 10:34:29 +00002404
2405 if (SE.getTypeSizeInBits(OldStride->getType()) !=
2406 SE.getTypeSizeInBits(NewStride->getType())) {
2407 if (SE.getTypeSizeInBits(OldStride->getType()) >
2408 SE.getTypeSizeInBits(NewStride->getType()))
2409 NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
2410 else
2411 OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
2412 }
2413 if (const SCEVConstant *Factor =
Dan Gohman4eebb942010-02-19 19:35:48 +00002414 dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
2415 SE, true))) {
Dan Gohman45774ce2010-02-12 10:34:29 +00002416 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
2417 Factors.insert(Factor->getValue()->getValue().getSExtValue());
2418 } else if (const SCEVConstant *Factor =
Dan Gohman8c16b382010-02-22 04:11:59 +00002419 dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
2420 NewStride,
Dan Gohman4eebb942010-02-19 19:35:48 +00002421 SE, true))) {
Dan Gohman45774ce2010-02-12 10:34:29 +00002422 if (Factor->getValue()->getValue().getMinSignedBits() <= 64)
2423 Factors.insert(Factor->getValue()->getValue().getSExtValue());
2424 }
2425 }
Dan Gohman45774ce2010-02-12 10:34:29 +00002426
2427 // If all uses use the same type, don't bother looking for truncation-based
2428 // reuse.
2429 if (Types.size() == 1)
2430 Types.clear();
2431
2432 DEBUG(print_factors_and_types(dbgs()));
2433}
2434
Andrew Trick29fe5f02012-01-09 19:50:34 +00002435/// findIVOperand - Helper for CollectChains that finds an IV operand (computed
2436/// by an AddRec in this loop) within [OI,OE) or returns OE. If IVUsers mapped
2437/// Instructions to IVStrideUses, we could partially skip this.
2438static User::op_iterator
2439findIVOperand(User::op_iterator OI, User::op_iterator OE,
2440 Loop *L, ScalarEvolution &SE) {
2441 for(; OI != OE; ++OI) {
2442 if (Instruction *Oper = dyn_cast<Instruction>(*OI)) {
2443 if (!SE.isSCEVable(Oper->getType()))
2444 continue;
2445
2446 if (const SCEVAddRecExpr *AR =
2447 dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Oper))) {
2448 if (AR->getLoop() == L)
2449 break;
2450 }
2451 }
2452 }
2453 return OI;
2454}
2455
2456/// getWideOperand - IVChain logic must consistenctly peek base TruncInst
2457/// operands, so wrap it in a convenient helper.
2458static Value *getWideOperand(Value *Oper) {
2459 if (TruncInst *Trunc = dyn_cast<TruncInst>(Oper))
2460 return Trunc->getOperand(0);
2461 return Oper;
2462}
2463
2464/// isCompatibleIVType - Return true if we allow an IV chain to include both
2465/// types.
2466static bool isCompatibleIVType(Value *LVal, Value *RVal) {
2467 Type *LType = LVal->getType();
2468 Type *RType = RVal->getType();
2469 return (LType == RType) || (LType->isPointerTy() && RType->isPointerTy());
2470}
2471
Andrew Trickd5d2db92012-01-10 01:45:08 +00002472/// getExprBase - Return an approximation of this SCEV expression's "base", or
2473/// NULL for any constant. Returning the expression itself is
2474/// conservative. Returning a deeper subexpression is more precise and valid as
2475/// long as it isn't less complex than another subexpression. For expressions
2476/// involving multiple unscaled values, we need to return the pointer-type
2477/// SCEVUnknown. This avoids forming chains across objects, such as:
2478/// PrevOper==a[i], IVOper==b[i], IVInc==b-a.
2479///
2480/// Since SCEVUnknown is the rightmost type, and pointers are the rightmost
2481/// SCEVUnknown, we simply return the rightmost SCEV operand.
2482static const SCEV *getExprBase(const SCEV *S) {
2483 switch (S->getSCEVType()) {
2484 default: // uncluding scUnknown.
2485 return S;
2486 case scConstant:
Craig Topperf40110f2014-04-25 05:29:35 +00002487 return nullptr;
Andrew Trickd5d2db92012-01-10 01:45:08 +00002488 case scTruncate:
2489 return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand());
2490 case scZeroExtend:
2491 return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand());
2492 case scSignExtend:
2493 return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand());
2494 case scAddExpr: {
2495 // Skip over scaled operands (scMulExpr) to follow add operands as long as
2496 // there's nothing more complex.
2497 // FIXME: not sure if we want to recognize negation.
2498 const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
2499 for (std::reverse_iterator<SCEVAddExpr::op_iterator> I(Add->op_end()),
2500 E(Add->op_begin()); I != E; ++I) {
2501 const SCEV *SubExpr = *I;
2502 if (SubExpr->getSCEVType() == scAddExpr)
2503 return getExprBase(SubExpr);
2504
2505 if (SubExpr->getSCEVType() != scMulExpr)
2506 return SubExpr;
2507 }
2508 return S; // all operands are scaled, be conservative.
2509 }
2510 case scAddRecExpr:
2511 return getExprBase(cast<SCEVAddRecExpr>(S)->getStart());
2512 }
2513}
2514
Andrew Trick248d4102012-01-09 21:18:52 +00002515/// Return true if the chain increment is profitable to expand into a loop
2516/// invariant value, which may require its own register. A profitable chain
2517/// increment will be an offset relative to the same base. We allow such offsets
2518/// to potentially be used as chain increment as long as it's not obviously
2519/// expensive to expand using real instructions.
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002520bool IVChain::isProfitableIncrement(const SCEV *OperExpr,
2521 const SCEV *IncExpr,
2522 ScalarEvolution &SE) {
2523 // Aggressively form chains when -stress-ivchain.
Andrew Trick248d4102012-01-09 21:18:52 +00002524 if (StressIVChain)
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002525 return true;
Andrew Trick248d4102012-01-09 21:18:52 +00002526
Andrew Trickd5d2db92012-01-10 01:45:08 +00002527 // Do not replace a constant offset from IV head with a nonconstant IV
2528 // increment.
2529 if (!isa<SCEVConstant>(IncExpr)) {
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002530 const SCEV *HeadExpr = SE.getSCEV(getWideOperand(Incs[0].IVOperand));
Andrew Trickd5d2db92012-01-10 01:45:08 +00002531 if (isa<SCEVConstant>(SE.getMinusSCEV(OperExpr, HeadExpr)))
2532 return 0;
2533 }
2534
2535 SmallPtrSet<const SCEV*, 8> Processed;
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002536 return !isHighCostExpansion(IncExpr, Processed, SE);
Andrew Trick248d4102012-01-09 21:18:52 +00002537}
2538
2539/// Return true if the number of registers needed for the chain is estimated to
2540/// be less than the number required for the individual IV users. First prohibit
2541/// any IV users that keep the IV live across increments (the Users set should
2542/// be empty). Next count the number and type of increments in the chain.
2543///
2544/// Chaining IVs can lead to considerable code bloat if ISEL doesn't
2545/// effectively use postinc addressing modes. Only consider it profitable it the
2546/// increments can be computed in fewer registers when chained.
2547///
2548/// TODO: Consider IVInc free if it's already used in another chains.
2549static bool
Craig Topper71b7b682014-08-21 05:55:13 +00002550isProfitableChain(IVChain &Chain, SmallPtrSetImpl<Instruction*> &Users,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002551 ScalarEvolution &SE, const TargetTransformInfo &TTI) {
Andrew Trick248d4102012-01-09 21:18:52 +00002552 if (StressIVChain)
2553 return true;
2554
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002555 if (!Chain.hasIncs())
Andrew Trickd5d2db92012-01-10 01:45:08 +00002556 return false;
2557
2558 if (!Users.empty()) {
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002559 DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " users:\n";
Craig Topper46276792014-08-24 23:23:06 +00002560 for (Instruction *Inst : Users) {
2561 dbgs() << " " << *Inst << "\n";
Andrew Trickd5d2db92012-01-10 01:45:08 +00002562 });
2563 return false;
2564 }
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002565 assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
Andrew Trickd5d2db92012-01-10 01:45:08 +00002566
2567 // The chain itself may require a register, so intialize cost to 1.
2568 int cost = 1;
2569
2570 // A complete chain likely eliminates the need for keeping the original IV in
2571 // a register. LSR does not currently know how to form a complete chain unless
2572 // the header phi already exists.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002573 if (isa<PHINode>(Chain.tailUserInst())
2574 && SE.getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) {
Andrew Trickd5d2db92012-01-10 01:45:08 +00002575 --cost;
2576 }
Craig Topperf40110f2014-04-25 05:29:35 +00002577 const SCEV *LastIncExpr = nullptr;
Andrew Trickd5d2db92012-01-10 01:45:08 +00002578 unsigned NumConstIncrements = 0;
2579 unsigned NumVarIncrements = 0;
2580 unsigned NumReusedIncrements = 0;
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002581 for (IVChain::const_iterator I = Chain.begin(), E = Chain.end();
Andrew Trickd5d2db92012-01-10 01:45:08 +00002582 I != E; ++I) {
2583
2584 if (I->IncExpr->isZero())
2585 continue;
2586
2587 // Incrementing by zero or some constant is neutral. We assume constants can
2588 // be folded into an addressing mode or an add's immediate operand.
2589 if (isa<SCEVConstant>(I->IncExpr)) {
2590 ++NumConstIncrements;
2591 continue;
2592 }
2593
2594 if (I->IncExpr == LastIncExpr)
2595 ++NumReusedIncrements;
2596 else
2597 ++NumVarIncrements;
2598
2599 LastIncExpr = I->IncExpr;
2600 }
2601 // An IV chain with a single increment is handled by LSR's postinc
2602 // uses. However, a chain with multiple increments requires keeping the IV's
2603 // value live longer than it needs to be if chained.
2604 if (NumConstIncrements > 1)
2605 --cost;
2606
2607 // Materializing increment expressions in the preheader that didn't exist in
2608 // the original code may cost a register. For example, sign-extended array
2609 // indices can produce ridiculous increments like this:
2610 // IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64)))
2611 cost += NumVarIncrements;
2612
2613 // Reusing variable increments likely saves a register to hold the multiple of
2614 // the stride.
2615 cost -= NumReusedIncrements;
2616
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002617 DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " Cost: " << cost
2618 << "\n");
Andrew Trickd5d2db92012-01-10 01:45:08 +00002619
2620 return cost < 0;
Andrew Trick248d4102012-01-09 21:18:52 +00002621}
2622
Andrew Trick29fe5f02012-01-09 19:50:34 +00002623/// ChainInstruction - Add this IV user to an existing chain or make it the head
2624/// of a new chain.
2625void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVOper,
2626 SmallVectorImpl<ChainUsers> &ChainUsersVec) {
2627 // When IVs are used as types of varying widths, they are generally converted
2628 // to a wider type with some uses remaining narrow under a (free) trunc.
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002629 Value *const NextIV = getWideOperand(IVOper);
2630 const SCEV *const OperExpr = SE.getSCEV(NextIV);
2631 const SCEV *const OperExprBase = getExprBase(OperExpr);
Andrew Trick29fe5f02012-01-09 19:50:34 +00002632
2633 // Visit all existing chains. Check if its IVOper can be computed as a
2634 // profitable loop invariant increment from the last link in the Chain.
2635 unsigned ChainIdx = 0, NChains = IVChainVec.size();
Craig Topperf40110f2014-04-25 05:29:35 +00002636 const SCEV *LastIncExpr = nullptr;
Andrew Trick29fe5f02012-01-09 19:50:34 +00002637 for (; ChainIdx < NChains; ++ChainIdx) {
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002638 IVChain &Chain = IVChainVec[ChainIdx];
2639
2640 // Prune the solution space aggressively by checking that both IV operands
2641 // are expressions that operate on the same unscaled SCEVUnknown. This
2642 // "base" will be canceled by the subsequent getMinusSCEV call. Checking
2643 // first avoids creating extra SCEV expressions.
2644 if (!StressIVChain && Chain.ExprBase != OperExprBase)
2645 continue;
2646
2647 Value *PrevIV = getWideOperand(Chain.Incs.back().IVOperand);
Andrew Trick29fe5f02012-01-09 19:50:34 +00002648 if (!isCompatibleIVType(PrevIV, NextIV))
2649 continue;
2650
Andrew Trick356a8962012-03-26 20:28:35 +00002651 // A phi node terminates a chain.
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002652 if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst()))
Andrew Trick29fe5f02012-01-09 19:50:34 +00002653 continue;
2654
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002655 // The increment must be loop-invariant so it can be kept in a register.
2656 const SCEV *PrevExpr = SE.getSCEV(PrevIV);
2657 const SCEV *IncExpr = SE.getMinusSCEV(OperExpr, PrevExpr);
2658 if (!SE.isLoopInvariant(IncExpr, L))
2659 continue;
2660
2661 if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) {
Andrew Trick29fe5f02012-01-09 19:50:34 +00002662 LastIncExpr = IncExpr;
2663 break;
2664 }
2665 }
2666 // If we haven't found a chain, create a new one, unless we hit the max. Don't
2667 // bother for phi nodes, because they must be last in the chain.
2668 if (ChainIdx == NChains) {
2669 if (isa<PHINode>(UserInst))
2670 return;
Andrew Trick248d4102012-01-09 21:18:52 +00002671 if (NChains >= MaxChains && !StressIVChain) {
Andrew Trick29fe5f02012-01-09 19:50:34 +00002672 DEBUG(dbgs() << "IV Chain Limit\n");
2673 return;
2674 }
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002675 LastIncExpr = OperExpr;
Andrew Trickb9c822a2012-01-20 21:23:40 +00002676 // IVUsers may have skipped over sign/zero extensions. We don't currently
2677 // attempt to form chains involving extensions unless they can be hoisted
2678 // into this loop's AddRec.
2679 if (!isa<SCEVAddRecExpr>(LastIncExpr))
2680 return;
Andrew Trick29fe5f02012-01-09 19:50:34 +00002681 ++NChains;
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002682 IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr),
2683 OperExprBase));
Andrew Trick29fe5f02012-01-09 19:50:34 +00002684 ChainUsersVec.resize(NChains);
Jakob Stoklund Olesen293673d2012-04-25 18:01:32 +00002685 DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInst
2686 << ") IV=" << *LastIncExpr << "\n");
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002687 } else {
Jakob Stoklund Olesen293673d2012-04-25 18:01:32 +00002688 DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Inc: (" << *UserInst
2689 << ") IV+" << *LastIncExpr << "\n");
Jakob Stoklund Olesenc90abc82012-04-26 23:33:11 +00002690 // Add this IV user to the end of the chain.
2691 IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr));
2692 }
Andrew Trickbc705902013-02-09 01:11:01 +00002693 IVChain &Chain = IVChainVec[ChainIdx];
Andrew Trick29fe5f02012-01-09 19:50:34 +00002694
2695 SmallPtrSet<Instruction*,4> &NearUsers = ChainUsersVec[ChainIdx].NearUsers;
2696 // This chain's NearUsers become FarUsers.
2697 if (!LastIncExpr->isZero()) {
2698 ChainUsersVec[ChainIdx].FarUsers.insert(NearUsers.begin(),
2699 NearUsers.end());
2700 NearUsers.clear();
2701 }
2702
2703 // All other uses of IVOperand become near uses of the chain.
2704 // We currently ignore intermediate values within SCEV expressions, assuming
2705 // they will eventually be used be the current chain, or can be computed
2706 // from one of the chain increments. To be more precise we could
2707 // transitively follow its user and only add leaf IV users to the set.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002708 for (User *U : IVOper->users()) {
2709 Instruction *OtherUse = dyn_cast<Instruction>(U);
Andrew Trickbc705902013-02-09 01:11:01 +00002710 if (!OtherUse)
Andrew Tricke51feea2012-03-26 18:03:16 +00002711 continue;
Andrew Trickbc705902013-02-09 01:11:01 +00002712 // Uses in the chain will no longer be uses if the chain is formed.
2713 // Include the head of the chain in this iteration (not Chain.begin()).
2714 IVChain::const_iterator IncIter = Chain.Incs.begin();
2715 IVChain::const_iterator IncEnd = Chain.Incs.end();
2716 for( ; IncIter != IncEnd; ++IncIter) {
2717 if (IncIter->UserInst == OtherUse)
2718 break;
2719 }
2720 if (IncIter != IncEnd)
2721 continue;
2722
Andrew Trick29fe5f02012-01-09 19:50:34 +00002723 if (SE.isSCEVable(OtherUse->getType())
2724 && !isa<SCEVUnknown>(SE.getSCEV(OtherUse))
2725 && IU.isIVUserOrOperand(OtherUse)) {
2726 continue;
2727 }
Andrew Tricke51feea2012-03-26 18:03:16 +00002728 NearUsers.insert(OtherUse);
Andrew Trick29fe5f02012-01-09 19:50:34 +00002729 }
2730
2731 // Since this user is part of the chain, it's no longer considered a use
2732 // of the chain.
2733 ChainUsersVec[ChainIdx].FarUsers.erase(UserInst);
2734}
2735
2736/// CollectChains - Populate the vector of Chains.
2737///
2738/// This decreases ILP at the architecture level. Targets with ample registers,
2739/// multiple memory ports, and no register renaming probably don't want
2740/// this. However, such targets should probably disable LSR altogether.
2741///
2742/// The job of LSR is to make a reasonable choice of induction variables across
2743/// the loop. Subsequent passes can easily "unchain" computation exposing more
2744/// ILP *within the loop* if the target wants it.
2745///
2746/// Finding the best IV chain is potentially a scheduling problem. Since LSR
2747/// will not reorder memory operations, it will recognize this as a chain, but
2748/// will generate redundant IV increments. Ideally this would be corrected later
2749/// by a smart scheduler:
2750/// = A[i]
2751/// = A[i+x]
2752/// A[i] =
2753/// A[i+x] =
2754///
2755/// TODO: Walk the entire domtree within this loop, not just the path to the
2756/// loop latch. This will discover chains on side paths, but requires
2757/// maintaining multiple copies of the Chains state.
2758void LSRInstance::CollectChains() {
Jakob Stoklund Olesen293673d2012-04-25 18:01:32 +00002759 DEBUG(dbgs() << "Collecting IV Chains.\n");
Andrew Trick29fe5f02012-01-09 19:50:34 +00002760 SmallVector<ChainUsers, 8> ChainUsersVec;
2761
2762 SmallVector<BasicBlock *,8> LatchPath;
2763 BasicBlock *LoopHeader = L->getHeader();
2764 for (DomTreeNode *Rung = DT.getNode(L->getLoopLatch());
2765 Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) {
2766 LatchPath.push_back(Rung->getBlock());
2767 }
2768 LatchPath.push_back(LoopHeader);
2769
2770 // Walk the instruction stream from the loop header to the loop latch.
2771 for (SmallVectorImpl<BasicBlock *>::reverse_iterator
2772 BBIter = LatchPath.rbegin(), BBEnd = LatchPath.rend();
2773 BBIter != BBEnd; ++BBIter) {
2774 for (BasicBlock::iterator I = (*BBIter)->begin(), E = (*BBIter)->end();
2775 I != E; ++I) {
2776 // Skip instructions that weren't seen by IVUsers analysis.
2777 if (isa<PHINode>(I) || !IU.isIVUserOrOperand(I))
2778 continue;
2779
2780 // Ignore users that are part of a SCEV expression. This way we only
2781 // consider leaf IV Users. This effectively rediscovers a portion of
2782 // IVUsers analysis but in program order this time.
2783 if (SE.isSCEVable(I->getType()) && !isa<SCEVUnknown>(SE.getSCEV(I)))
2784 continue;
2785
2786 // Remove this instruction from any NearUsers set it may be in.
2787 for (unsigned ChainIdx = 0, NChains = IVChainVec.size();
2788 ChainIdx < NChains; ++ChainIdx) {
2789 ChainUsersVec[ChainIdx].NearUsers.erase(I);
2790 }
2791 // Search for operands that can be chained.
2792 SmallPtrSet<Instruction*, 4> UniqueOperands;
2793 User::op_iterator IVOpEnd = I->op_end();
2794 User::op_iterator IVOpIter = findIVOperand(I->op_begin(), IVOpEnd, L, SE);
2795 while (IVOpIter != IVOpEnd) {
2796 Instruction *IVOpInst = cast<Instruction>(*IVOpIter);
David Blaikie70573dc2014-11-19 07:49:26 +00002797 if (UniqueOperands.insert(IVOpInst).second)
Andrew Trick29fe5f02012-01-09 19:50:34 +00002798 ChainInstruction(I, IVOpInst, ChainUsersVec);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002799 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
Andrew Trick29fe5f02012-01-09 19:50:34 +00002800 }
2801 } // Continue walking down the instructions.
2802 } // Continue walking down the domtree.
2803 // Visit phi backedges to determine if the chain can generate the IV postinc.
2804 for (BasicBlock::iterator I = L->getHeader()->begin();
2805 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2806 if (!SE.isSCEVable(PN->getType()))
2807 continue;
2808
2809 Instruction *IncV =
2810 dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
2811 if (IncV)
2812 ChainInstruction(PN, IncV, ChainUsersVec);
2813 }
Andrew Trick248d4102012-01-09 21:18:52 +00002814 // Remove any unprofitable chains.
2815 unsigned ChainIdx = 0;
2816 for (unsigned UsersIdx = 0, NChains = IVChainVec.size();
2817 UsersIdx < NChains; ++UsersIdx) {
2818 if (!isProfitableChain(IVChainVec[UsersIdx],
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002819 ChainUsersVec[UsersIdx].FarUsers, SE, TTI))
Andrew Trick248d4102012-01-09 21:18:52 +00002820 continue;
2821 // Preserve the chain at UsesIdx.
2822 if (ChainIdx != UsersIdx)
2823 IVChainVec[ChainIdx] = IVChainVec[UsersIdx];
2824 FinalizeChain(IVChainVec[ChainIdx]);
2825 ++ChainIdx;
2826 }
2827 IVChainVec.resize(ChainIdx);
2828}
2829
2830void LSRInstance::FinalizeChain(IVChain &Chain) {
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002831 assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
2832 DEBUG(dbgs() << "Final Chain: " << *Chain.Incs[0].UserInst << "\n");
Andrew Trick248d4102012-01-09 21:18:52 +00002833
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002834 for (IVChain::const_iterator I = Chain.begin(), E = Chain.end();
Andrew Trick248d4102012-01-09 21:18:52 +00002835 I != E; ++I) {
2836 DEBUG(dbgs() << " Inc: " << *I->UserInst << "\n");
2837 User::op_iterator UseI =
2838 std::find(I->UserInst->op_begin(), I->UserInst->op_end(), I->IVOperand);
2839 assert(UseI != I->UserInst->op_end() && "cannot find IV operand");
2840 IVIncSet.insert(UseI);
2841 }
2842}
2843
2844/// Return true if the IVInc can be folded into an addressing mode.
2845static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002846 Value *Operand, const TargetTransformInfo &TTI) {
Andrew Trick248d4102012-01-09 21:18:52 +00002847 const SCEVConstant *IncConst = dyn_cast<SCEVConstant>(IncExpr);
2848 if (!IncConst || !isAddressUse(UserInst, Operand))
2849 return false;
2850
2851 if (IncConst->getValue()->getValue().getMinSignedBits() > 64)
2852 return false;
2853
2854 int64_t IncOffset = IncConst->getValue()->getSExtValue();
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002855 if (!isAlwaysFoldable(TTI, LSRUse::Address,
Craig Topperf40110f2014-04-25 05:29:35 +00002856 getAccessType(UserInst), /*BaseGV=*/ nullptr,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002857 IncOffset, /*HaseBaseReg=*/ false))
Andrew Trick248d4102012-01-09 21:18:52 +00002858 return false;
2859
2860 return true;
2861}
2862
2863/// GenerateIVChains - Generate an add or subtract for each IVInc in a chain to
2864/// materialize the IV user's operand from the previous IV user's operand.
2865void LSRInstance::GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
2866 SmallVectorImpl<WeakVH> &DeadInsts) {
2867 // Find the new IVOperand for the head of the chain. It may have been replaced
2868 // by LSR.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002869 const IVInc &Head = Chain.Incs[0];
Andrew Trick248d4102012-01-09 21:18:52 +00002870 User::op_iterator IVOpEnd = Head.UserInst->op_end();
Andrew Trickf3a25442013-03-19 05:10:27 +00002871 // findIVOperand returns IVOpEnd if it can no longer find a valid IV user.
Andrew Trick248d4102012-01-09 21:18:52 +00002872 User::op_iterator IVOpIter = findIVOperand(Head.UserInst->op_begin(),
2873 IVOpEnd, L, SE);
Craig Topperf40110f2014-04-25 05:29:35 +00002874 Value *IVSrc = nullptr;
Andrew Trickf3a25442013-03-19 05:10:27 +00002875 while (IVOpIter != IVOpEnd) {
Andrew Trick248d4102012-01-09 21:18:52 +00002876 IVSrc = getWideOperand(*IVOpIter);
2877
2878 // If this operand computes the expression that the chain needs, we may use
2879 // it. (Check this after setting IVSrc which is used below.)
2880 //
2881 // Note that if Head.IncExpr is wider than IVSrc, then this phi is too
2882 // narrow for the chain, so we can no longer use it. We do allow using a
2883 // wider phi, assuming the LSR checked for free truncation. In that case we
2884 // should already have a truncate on this operand such that
2885 // getSCEV(IVSrc) == IncExpr.
2886 if (SE.getSCEV(*IVOpIter) == Head.IncExpr
2887 || SE.getSCEV(IVSrc) == Head.IncExpr) {
2888 break;
2889 }
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00002890 IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
Andrew Trickf3a25442013-03-19 05:10:27 +00002891 }
Andrew Trick248d4102012-01-09 21:18:52 +00002892 if (IVOpIter == IVOpEnd) {
2893 // Gracefully give up on this chain.
2894 DEBUG(dbgs() << "Concealed chain head: " << *Head.UserInst << "\n");
2895 return;
2896 }
2897
2898 DEBUG(dbgs() << "Generate chain at: " << *IVSrc << "\n");
2899 Type *IVTy = IVSrc->getType();
2900 Type *IntTy = SE.getEffectiveSCEVType(IVTy);
Craig Topperf40110f2014-04-25 05:29:35 +00002901 const SCEV *LeftOverExpr = nullptr;
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002902 for (IVChain::const_iterator IncI = Chain.begin(),
Andrew Trick248d4102012-01-09 21:18:52 +00002903 IncE = Chain.end(); IncI != IncE; ++IncI) {
2904
2905 Instruction *InsertPt = IncI->UserInst;
2906 if (isa<PHINode>(InsertPt))
2907 InsertPt = L->getLoopLatch()->getTerminator();
2908
2909 // IVOper will replace the current IV User's operand. IVSrc is the IV
2910 // value currently held in a register.
2911 Value *IVOper = IVSrc;
2912 if (!IncI->IncExpr->isZero()) {
2913 // IncExpr was the result of subtraction of two narrow values, so must
2914 // be signed.
2915 const SCEV *IncExpr = SE.getNoopOrSignExtend(IncI->IncExpr, IntTy);
2916 LeftOverExpr = LeftOverExpr ?
2917 SE.getAddExpr(LeftOverExpr, IncExpr) : IncExpr;
2918 }
2919 if (LeftOverExpr && !LeftOverExpr->isZero()) {
2920 // Expand the IV increment.
2921 Rewriter.clearPostInc();
2922 Value *IncV = Rewriter.expandCodeFor(LeftOverExpr, IntTy, InsertPt);
2923 const SCEV *IVOperExpr = SE.getAddExpr(SE.getUnknown(IVSrc),
2924 SE.getUnknown(IncV));
2925 IVOper = Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt);
2926
2927 // If an IV increment can't be folded, use it as the next IV value.
2928 if (!canFoldIVIncExpr(LeftOverExpr, IncI->UserInst, IncI->IVOperand,
Chandler Carruth26c59fa2013-01-07 14:41:08 +00002929 TTI)) {
Andrew Trick248d4102012-01-09 21:18:52 +00002930 assert(IVTy == IVOper->getType() && "inconsistent IV increment type");
2931 IVSrc = IVOper;
Craig Topperf40110f2014-04-25 05:29:35 +00002932 LeftOverExpr = nullptr;
Andrew Trick248d4102012-01-09 21:18:52 +00002933 }
2934 }
2935 Type *OperTy = IncI->IVOperand->getType();
2936 if (IVTy != OperTy) {
2937 assert(SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) &&
2938 "cannot extend a chained IV");
2939 IRBuilder<> Builder(InsertPt);
2940 IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy, "lsr.chain");
2941 }
2942 IncI->UserInst->replaceUsesOfWith(IncI->IVOperand, IVOper);
2943 DeadInsts.push_back(IncI->IVOperand);
2944 }
2945 // If LSR created a new, wider phi, we may also replace its postinc. We only
2946 // do this if we also found a wide value for the head of the chain.
Jakob Stoklund Olesena0337d72012-04-26 23:33:09 +00002947 if (isa<PHINode>(Chain.tailUserInst())) {
Andrew Trick248d4102012-01-09 21:18:52 +00002948 for (BasicBlock::iterator I = L->getHeader()->begin();
2949 PHINode *Phi = dyn_cast<PHINode>(I); ++I) {
2950 if (!isCompatibleIVType(Phi, IVSrc))
2951 continue;
2952 Instruction *PostIncV = dyn_cast<Instruction>(
2953 Phi->getIncomingValueForBlock(L->getLoopLatch()));
2954 if (!PostIncV || (SE.getSCEV(PostIncV) != SE.getSCEV(IVSrc)))
2955 continue;
2956 Value *IVOper = IVSrc;
2957 Type *PostIncTy = PostIncV->getType();
2958 if (IVTy != PostIncTy) {
2959 assert(PostIncTy->isPointerTy() && "mixing int/ptr IV types");
2960 IRBuilder<> Builder(L->getLoopLatch()->getTerminator());
2961 Builder.SetCurrentDebugLocation(PostIncV->getDebugLoc());
2962 IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy, "lsr.chain");
2963 }
2964 Phi->replaceUsesOfWith(PostIncV, IVOper);
2965 DeadInsts.push_back(PostIncV);
2966 }
2967 }
Andrew Trick29fe5f02012-01-09 19:50:34 +00002968}
2969
Dan Gohman45774ce2010-02-12 10:34:29 +00002970void LSRInstance::CollectFixupsAndInitialFormulae() {
2971 for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI) {
Andrew Trick248d4102012-01-09 21:18:52 +00002972 Instruction *UserInst = UI->getUser();
2973 // Skip IV users that are part of profitable IV Chains.
2974 User::op_iterator UseI = std::find(UserInst->op_begin(), UserInst->op_end(),
2975 UI->getOperandValToReplace());
2976 assert(UseI != UserInst->op_end() && "cannot find IV operand");
2977 if (IVIncSet.count(UseI))
2978 continue;
2979
Dan Gohman45774ce2010-02-12 10:34:29 +00002980 // Record the uses.
2981 LSRFixup &LF = getNewFixup();
Andrew Trick248d4102012-01-09 21:18:52 +00002982 LF.UserInst = UserInst;
Dan Gohman45774ce2010-02-12 10:34:29 +00002983 LF.OperandValToReplace = UI->getOperandValToReplace();
Dan Gohmand006ab92010-04-07 22:27:08 +00002984 LF.PostIncLoops = UI->getPostIncLoops();
Dan Gohman45774ce2010-02-12 10:34:29 +00002985
2986 LSRUse::KindType Kind = LSRUse::Basic;
Craig Topperf40110f2014-04-25 05:29:35 +00002987 Type *AccessTy = nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +00002988 if (isAddressUse(LF.UserInst, LF.OperandValToReplace)) {
2989 Kind = LSRUse::Address;
2990 AccessTy = getAccessType(LF.UserInst);
2991 }
2992
Dan Gohmane637ff52010-04-19 21:48:58 +00002993 const SCEV *S = IU.getExpr(*UI);
Dan Gohman45774ce2010-02-12 10:34:29 +00002994
2995 // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
2996 // (N - i == 0), and this allows (N - i) to be the expression that we work
2997 // with rather than just N or i, so we can consider the register
2998 // requirements for both N and i at the same time. Limiting this code to
2999 // equality icmps is not a problem because all interesting loops use
3000 // equality icmps, thanks to IndVarSimplify.
3001 if (ICmpInst *CI = dyn_cast<ICmpInst>(LF.UserInst))
3002 if (CI->isEquality()) {
3003 // Swap the operands if needed to put the OperandValToReplace on the
3004 // left, for consistency.
3005 Value *NV = CI->getOperand(1);
3006 if (NV == LF.OperandValToReplace) {
3007 CI->setOperand(1, CI->getOperand(0));
3008 CI->setOperand(0, NV);
Dan Gohmanee2fea32010-05-20 19:26:52 +00003009 NV = CI->getOperand(1);
Dan Gohmanfdf98742010-05-20 19:16:03 +00003010 Changed = true;
Dan Gohman45774ce2010-02-12 10:34:29 +00003011 }
3012
3013 // x == y --> x - y == 0
3014 const SCEV *N = SE.getSCEV(NV);
Andrew Trick57243da2013-10-25 21:35:56 +00003015 if (SE.isLoopInvariant(N, L) && isSafeToExpand(N, SE)) {
Dan Gohman3268e4d2011-05-18 21:02:18 +00003016 // S is normalized, so normalize N before folding it into S
3017 // to keep the result normalized.
Craig Topperf40110f2014-04-25 05:29:35 +00003018 N = TransformForPostIncUse(Normalize, N, CI, nullptr,
Dan Gohman3268e4d2011-05-18 21:02:18 +00003019 LF.PostIncLoops, SE, DT);
Dan Gohman45774ce2010-02-12 10:34:29 +00003020 Kind = LSRUse::ICmpZero;
3021 S = SE.getMinusSCEV(N, S);
3022 }
3023
3024 // -1 and the negations of all interesting strides (except the negation
3025 // of -1) are now also interesting.
3026 for (size_t i = 0, e = Factors.size(); i != e; ++i)
3027 if (Factors[i] != -1)
3028 Factors.insert(-(uint64_t)Factors[i]);
3029 Factors.insert(-1);
3030 }
3031
3032 // Set up the initial formula for this use.
3033 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
3034 LF.LUIdx = P.first;
3035 LF.Offset = P.second;
3036 LSRUse &LU = Uses[LF.LUIdx];
Dan Gohmand006ab92010-04-07 22:27:08 +00003037 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Dan Gohman14152082010-07-15 20:24:58 +00003038 if (!LU.WidestFixupType ||
3039 SE.getTypeSizeInBits(LU.WidestFixupType) <
3040 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
3041 LU.WidestFixupType = LF.OperandValToReplace->getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00003042
3043 // If this is the first use of this LSRUse, give it a formula.
3044 if (LU.Formulae.empty()) {
Dan Gohman8c16b382010-02-22 04:11:59 +00003045 InsertInitialFormula(S, LU, LF.LUIdx);
Dan Gohman45774ce2010-02-12 10:34:29 +00003046 CountRegisters(LU.Formulae.back(), LF.LUIdx);
3047 }
3048 }
3049
3050 DEBUG(print_fixups(dbgs()));
3051}
3052
Dan Gohmana4ca28a2010-05-20 20:52:00 +00003053/// InsertInitialFormula - Insert a formula for the given expression into
3054/// the given use, separating out loop-variant portions from loop-invariant
3055/// and loop-computable portions.
Dan Gohman45774ce2010-02-12 10:34:29 +00003056void
Dan Gohman8c16b382010-02-22 04:11:59 +00003057LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
Andrew Trick57243da2013-10-25 21:35:56 +00003058 // Mark uses whose expressions cannot be expanded.
3059 if (!isSafeToExpand(S, SE))
3060 LU.RigidFormula = true;
3061
Dan Gohman45774ce2010-02-12 10:34:29 +00003062 Formula F;
Dan Gohman20d9ce22010-11-17 21:41:58 +00003063 F.InitialMatch(S, L, SE);
Dan Gohman45774ce2010-02-12 10:34:29 +00003064 bool Inserted = InsertFormula(LU, LUIdx, F);
3065 assert(Inserted && "Initial formula already exists!"); (void)Inserted;
3066}
3067
Dan Gohmana4ca28a2010-05-20 20:52:00 +00003068/// InsertSupplementalFormula - Insert a simple single-register formula for
3069/// the given expression into the given use.
Dan Gohman45774ce2010-02-12 10:34:29 +00003070void
3071LSRInstance::InsertSupplementalFormula(const SCEV *S,
3072 LSRUse &LU, size_t LUIdx) {
3073 Formula F;
3074 F.BaseRegs.push_back(S);
Chandler Carruth7e31c8f2013-01-12 23:46:04 +00003075 F.HasBaseReg = true;
Dan Gohman45774ce2010-02-12 10:34:29 +00003076 bool Inserted = InsertFormula(LU, LUIdx, F);
3077 assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
3078}
3079
3080/// CountRegisters - Note which registers are used by the given formula,
3081/// updating RegUses.
3082void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
3083 if (F.ScaledReg)
3084 RegUses.CountRegister(F.ScaledReg, LUIdx);
3085 for (SmallVectorImpl<const SCEV *>::const_iterator I = F.BaseRegs.begin(),
3086 E = F.BaseRegs.end(); I != E; ++I)
3087 RegUses.CountRegister(*I, LUIdx);
3088}
3089
3090/// InsertFormula - If the given formula has not yet been inserted, add it to
3091/// the list, and return true. Return false otherwise.
3092bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003093 // Do not insert formula that we will not be able to expand.
3094 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) &&
3095 "Formula is illegal");
Dan Gohman8c16b382010-02-22 04:11:59 +00003096 if (!LU.InsertFormula(F))
Dan Gohman45774ce2010-02-12 10:34:29 +00003097 return false;
3098
3099 CountRegisters(F, LUIdx);
3100 return true;
3101}
3102
3103/// CollectLoopInvariantFixupsAndFormulae - Check for other uses of
3104/// loop-invariant values which we're tracking. These other uses will pin these
3105/// values in registers, making them less profitable for elimination.
3106/// TODO: This currently misses non-constant addrec step registers.
3107/// TODO: Should this give more weight to users inside the loop?
3108void
3109LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
3110 SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
Andrew Trickdd925ad2014-10-25 19:59:30 +00003111 SmallPtrSet<const SCEV *, 32> Visited;
Dan Gohman45774ce2010-02-12 10:34:29 +00003112
3113 while (!Worklist.empty()) {
3114 const SCEV *S = Worklist.pop_back_val();
3115
Andrew Trick9ccbed52014-10-25 19:42:07 +00003116 // Don't process the same SCEV twice
David Blaikie70573dc2014-11-19 07:49:26 +00003117 if (!Visited.insert(S).second)
Andrew Trick9ccbed52014-10-25 19:42:07 +00003118 continue;
3119
Dan Gohman45774ce2010-02-12 10:34:29 +00003120 if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
Dan Gohmandd41bba2010-06-21 19:47:52 +00003121 Worklist.append(N->op_begin(), N->op_end());
Dan Gohman45774ce2010-02-12 10:34:29 +00003122 else if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
3123 Worklist.push_back(C->getOperand());
3124 else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
3125 Worklist.push_back(D->getLHS());
3126 Worklist.push_back(D->getRHS());
Chandler Carruthcdf47882014-03-09 03:16:01 +00003127 } else if (const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003128 const Value *V = US->getValue();
Dan Gohman67b44032010-06-04 23:16:05 +00003129 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
3130 // Look for instructions defined outside the loop.
Dan Gohman45774ce2010-02-12 10:34:29 +00003131 if (L->contains(Inst)) continue;
Dan Gohman67b44032010-06-04 23:16:05 +00003132 } else if (isa<UndefValue>(V))
3133 // Undef doesn't have a live range, so it doesn't matter.
3134 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003135 for (const Use &U : V->uses()) {
3136 const Instruction *UserInst = dyn_cast<Instruction>(U.getUser());
Dan Gohman45774ce2010-02-12 10:34:29 +00003137 // Ignore non-instructions.
3138 if (!UserInst)
Dan Gohman045f8192010-01-22 00:46:49 +00003139 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003140 // Ignore instructions in other functions (as can happen with
3141 // Constants).
3142 if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
Dan Gohman045f8192010-01-22 00:46:49 +00003143 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003144 // Ignore instructions not dominated by the loop.
3145 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
3146 UserInst->getParent() :
3147 cast<PHINode>(UserInst)->getIncomingBlock(
Chandler Carruthcdf47882014-03-09 03:16:01 +00003148 PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
Dan Gohman45774ce2010-02-12 10:34:29 +00003149 if (!DT.dominates(L->getHeader(), UseBB))
3150 continue;
3151 // Ignore uses which are part of other SCEV expressions, to avoid
3152 // analyzing them multiple times.
Dan Gohman42ec4eb2010-04-09 19:12:34 +00003153 if (SE.isSCEVable(UserInst->getType())) {
3154 const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
3155 // If the user is a no-op, look through to its uses.
3156 if (!isa<SCEVUnknown>(UserS))
3157 continue;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003158 if (UserS == US) {
Dan Gohman42ec4eb2010-04-09 19:12:34 +00003159 Worklist.push_back(
3160 SE.getUnknown(const_cast<Instruction *>(UserInst)));
3161 continue;
3162 }
3163 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003164 // Ignore icmp instructions which are already being analyzed.
3165 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003166 unsigned OtherIdx = !U.getOperandNo();
Dan Gohman45774ce2010-02-12 10:34:29 +00003167 Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
Dan Gohmanafd6db92010-11-17 21:23:15 +00003168 if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L))
Dan Gohman45774ce2010-02-12 10:34:29 +00003169 continue;
3170 }
3171
3172 LSRFixup &LF = getNewFixup();
3173 LF.UserInst = const_cast<Instruction *>(UserInst);
Chandler Carruthcdf47882014-03-09 03:16:01 +00003174 LF.OperandValToReplace = U;
Craig Topperf40110f2014-04-25 05:29:35 +00003175 std::pair<size_t, int64_t> P = getUse(S, LSRUse::Basic, nullptr);
Dan Gohman45774ce2010-02-12 10:34:29 +00003176 LF.LUIdx = P.first;
3177 LF.Offset = P.second;
3178 LSRUse &LU = Uses[LF.LUIdx];
Dan Gohmand006ab92010-04-07 22:27:08 +00003179 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
Dan Gohman14152082010-07-15 20:24:58 +00003180 if (!LU.WidestFixupType ||
3181 SE.getTypeSizeInBits(LU.WidestFixupType) <
3182 SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
3183 LU.WidestFixupType = LF.OperandValToReplace->getType();
Chandler Carruthcdf47882014-03-09 03:16:01 +00003184 InsertSupplementalFormula(US, LU, LF.LUIdx);
Dan Gohman45774ce2010-02-12 10:34:29 +00003185 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
3186 break;
3187 }
3188 }
3189 }
3190}
3191
3192/// CollectSubexprs - Split S into subexpressions which can be pulled out into
3193/// separate registers. If C is non-null, multiply each subexpression by C.
Andrew Trickc8037062012-07-17 05:30:37 +00003194///
3195/// Return remainder expression after factoring the subexpressions captured by
3196/// Ops. If Ops is complete, return NULL.
3197static const SCEV *CollectSubexprs(const SCEV *S, const SCEVConstant *C,
3198 SmallVectorImpl<const SCEV *> &Ops,
3199 const Loop *L,
3200 ScalarEvolution &SE,
3201 unsigned Depth = 0) {
3202 // Arbitrarily cap recursion to protect compile time.
3203 if (Depth >= 3)
3204 return S;
3205
Dan Gohman45774ce2010-02-12 10:34:29 +00003206 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3207 // Break out add operands.
3208 for (SCEVAddExpr::op_iterator I = Add->op_begin(), E = Add->op_end();
Andrew Trickc8037062012-07-17 05:30:37 +00003209 I != E; ++I) {
3210 const SCEV *Remainder = CollectSubexprs(*I, C, Ops, L, SE, Depth+1);
3211 if (Remainder)
3212 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
3213 }
Craig Topperf40110f2014-04-25 05:29:35 +00003214 return nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +00003215 } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
3216 // Split a non-zero base out of an addrec.
Andrew Trickc8037062012-07-17 05:30:37 +00003217 if (AR->getStart()->isZero())
3218 return S;
3219
3220 const SCEV *Remainder = CollectSubexprs(AR->getStart(),
3221 C, Ops, L, SE, Depth+1);
3222 // Split the non-zero AddRec unless it is part of a nested recurrence that
3223 // does not pertain to this loop.
3224 if (Remainder && (AR->getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) {
3225 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
Craig Topperf40110f2014-04-25 05:29:35 +00003226 Remainder = nullptr;
Andrew Trickc8037062012-07-17 05:30:37 +00003227 }
3228 if (Remainder != AR->getStart()) {
3229 if (!Remainder)
3230 Remainder = SE.getConstant(AR->getType(), 0);
3231 return SE.getAddRecExpr(Remainder,
3232 AR->getStepRecurrence(SE),
3233 AR->getLoop(),
3234 //FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
3235 SCEV::FlagAnyWrap);
Dan Gohman45774ce2010-02-12 10:34:29 +00003236 }
3237 } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3238 // Break (C * (a + b + c)) into C*a + C*b + C*c.
Andrew Trickc8037062012-07-17 05:30:37 +00003239 if (Mul->getNumOperands() != 2)
3240 return S;
3241 if (const SCEVConstant *Op0 =
3242 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3243 C = C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0;
3244 const SCEV *Remainder =
3245 CollectSubexprs(Mul->getOperand(1), C, Ops, L, SE, Depth+1);
3246 if (Remainder)
3247 Ops.push_back(SE.getMulExpr(C, Remainder));
Craig Topperf40110f2014-04-25 05:29:35 +00003248 return nullptr;
Andrew Trickc8037062012-07-17 05:30:37 +00003249 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003250 }
Andrew Trickc8037062012-07-17 05:30:37 +00003251 return S;
Dan Gohman45774ce2010-02-12 10:34:29 +00003252}
3253
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003254/// \brief Helper function for LSRInstance::GenerateReassociations.
3255void LSRInstance::GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
3256 const Formula &Base,
3257 unsigned Depth, size_t Idx,
3258 bool IsScaledReg) {
3259 const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3260 SmallVector<const SCEV *, 8> AddOps;
3261 const SCEV *Remainder = CollectSubexprs(BaseReg, nullptr, AddOps, L, SE);
3262 if (Remainder)
3263 AddOps.push_back(Remainder);
3264
3265 if (AddOps.size() == 1)
3266 return;
3267
3268 for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
3269 JE = AddOps.end();
3270 J != JE; ++J) {
3271
3272 // Loop-variant "unknown" values are uninteresting; we won't be able to
3273 // do anything meaningful with them.
3274 if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L))
3275 continue;
3276
3277 // Don't pull a constant into a register if the constant could be folded
3278 // into an immediate field.
3279 if (isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
3280 LU.AccessTy, *J, Base.getNumRegs() > 1))
3281 continue;
3282
3283 // Collect all operands except *J.
3284 SmallVector<const SCEV *, 8> InnerAddOps(
3285 ((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J);
3286 InnerAddOps.append(std::next(J),
3287 ((const SmallVector<const SCEV *, 8> &)AddOps).end());
3288
3289 // Don't leave just a constant behind in a register if the constant could
3290 // be folded into an immediate field.
3291 if (InnerAddOps.size() == 1 &&
3292 isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
3293 LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1))
3294 continue;
3295
3296 const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
3297 if (InnerSum->isZero())
3298 continue;
3299 Formula F = Base;
3300
3301 // Add the remaining pieces of the add back into the new formula.
3302 const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(InnerSum);
3303 if (InnerSumSC && SE.getTypeSizeInBits(InnerSumSC->getType()) <= 64 &&
3304 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
3305 InnerSumSC->getValue()->getZExtValue())) {
3306 F.UnfoldedOffset =
3307 (uint64_t)F.UnfoldedOffset + InnerSumSC->getValue()->getZExtValue();
3308 if (IsScaledReg)
3309 F.ScaledReg = nullptr;
3310 else
3311 F.BaseRegs.erase(F.BaseRegs.begin() + Idx);
3312 } else if (IsScaledReg)
3313 F.ScaledReg = InnerSum;
3314 else
3315 F.BaseRegs[Idx] = InnerSum;
3316
3317 // Add J as its own register, or an unfolded immediate.
3318 const SCEVConstant *SC = dyn_cast<SCEVConstant>(*J);
3319 if (SC && SE.getTypeSizeInBits(SC->getType()) <= 64 &&
3320 TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
3321 SC->getValue()->getZExtValue()))
3322 F.UnfoldedOffset =
3323 (uint64_t)F.UnfoldedOffset + SC->getValue()->getZExtValue();
3324 else
3325 F.BaseRegs.push_back(*J);
3326 // We may have changed the number of register in base regs, adjust the
3327 // formula accordingly.
3328 F.Canonicalize();
3329
3330 if (InsertFormula(LU, LUIdx, F))
3331 // If that formula hadn't been seen before, recurse to find more like
3332 // it.
3333 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth + 1);
3334 }
3335}
3336
Dan Gohman45774ce2010-02-12 10:34:29 +00003337/// GenerateReassociations - Split out subexpressions from adds and the bases of
3338/// addrecs.
3339void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003340 Formula Base, unsigned Depth) {
3341 assert(Base.isCanonical() && "Input must be in the canonical form");
Dan Gohman45774ce2010-02-12 10:34:29 +00003342 // Arbitrarily cap recursion to protect compile time.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003343 if (Depth >= 3)
3344 return;
Dan Gohman45774ce2010-02-12 10:34:29 +00003345
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003346 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3347 GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i);
Dan Gohman45774ce2010-02-12 10:34:29 +00003348
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003349 if (Base.Scale == 1)
3350 GenerateReassociationsImpl(LU, LUIdx, Base, Depth,
3351 /* Idx */ -1, /* IsScaledReg */ true);
Dan Gohman45774ce2010-02-12 10:34:29 +00003352}
3353
3354/// GenerateCombinations - Generate a formula consisting of all of the
3355/// loop-dominating registers added into a single register.
3356void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
Dan Gohmane4e51a62010-02-14 18:51:39 +00003357 Formula Base) {
Dan Gohman8b0a4192010-03-01 17:49:51 +00003358 // This method is only interesting on a plurality of registers.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003359 if (Base.BaseRegs.size() + (Base.Scale == 1) <= 1)
3360 return;
Dan Gohman45774ce2010-02-12 10:34:29 +00003361
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003362 // Flatten the representation, i.e., reg1 + 1*reg2 => reg1 + reg2, before
3363 // processing the formula.
3364 Base.Unscale();
Dan Gohman45774ce2010-02-12 10:34:29 +00003365 Formula F = Base;
3366 F.BaseRegs.clear();
3367 SmallVector<const SCEV *, 4> Ops;
3368 for (SmallVectorImpl<const SCEV *>::const_iterator
3369 I = Base.BaseRegs.begin(), E = Base.BaseRegs.end(); I != E; ++I) {
3370 const SCEV *BaseReg = *I;
Dan Gohman20d9ce22010-11-17 21:41:58 +00003371 if (SE.properlyDominates(BaseReg, L->getHeader()) &&
Dan Gohmanafd6db92010-11-17 21:23:15 +00003372 !SE.hasComputableLoopEvolution(BaseReg, L))
Dan Gohman45774ce2010-02-12 10:34:29 +00003373 Ops.push_back(BaseReg);
3374 else
3375 F.BaseRegs.push_back(BaseReg);
3376 }
3377 if (Ops.size() > 1) {
Dan Gohmanbb7d5222010-02-14 18:50:49 +00003378 const SCEV *Sum = SE.getAddExpr(Ops);
3379 // TODO: If Sum is zero, it probably means ScalarEvolution missed an
3380 // opportunity to fold something. For now, just ignore such cases
Dan Gohman8b0a4192010-03-01 17:49:51 +00003381 // rather than proceed with zero in a register.
Dan Gohmanbb7d5222010-02-14 18:50:49 +00003382 if (!Sum->isZero()) {
3383 F.BaseRegs.push_back(Sum);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003384 F.Canonicalize();
Dan Gohmanbb7d5222010-02-14 18:50:49 +00003385 (void)InsertFormula(LU, LUIdx, F);
3386 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003387 }
3388}
3389
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003390/// \brief Helper function for LSRInstance::GenerateSymbolicOffsets.
3391void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
3392 const Formula &Base, size_t Idx,
3393 bool IsScaledReg) {
3394 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3395 GlobalValue *GV = ExtractSymbol(G, SE);
3396 if (G->isZero() || !GV)
3397 return;
3398 Formula F = Base;
3399 F.BaseGV = GV;
3400 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3401 return;
3402 if (IsScaledReg)
3403 F.ScaledReg = G;
3404 else
3405 F.BaseRegs[Idx] = G;
3406 (void)InsertFormula(LU, LUIdx, F);
3407}
3408
Dan Gohman45774ce2010-02-12 10:34:29 +00003409/// GenerateSymbolicOffsets - Generate reuse formulae using symbolic offsets.
3410void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
3411 Formula Base) {
3412 // We can't add a symbolic offset if the address already contains one.
Chandler Carruth6e479322013-01-07 15:04:40 +00003413 if (Base.BaseGV) return;
Dan Gohman45774ce2010-02-12 10:34:29 +00003414
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003415 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3416 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i);
3417 if (Base.Scale == 1)
3418 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, /* Idx */ -1,
3419 /* IsScaledReg */ true);
3420}
3421
3422/// \brief Helper function for LSRInstance::GenerateConstantOffsets.
3423void LSRInstance::GenerateConstantOffsetsImpl(
3424 LSRUse &LU, unsigned LUIdx, const Formula &Base,
3425 const SmallVectorImpl<int64_t> &Worklist, size_t Idx, bool IsScaledReg) {
3426 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3427 for (SmallVectorImpl<int64_t>::const_iterator I = Worklist.begin(),
3428 E = Worklist.end();
3429 I != E; ++I) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003430 Formula F = Base;
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003431 F.BaseOffset = (uint64_t)Base.BaseOffset - *I;
3432 if (isLegalUse(TTI, LU.MinOffset - *I, LU.MaxOffset - *I, LU.Kind,
3433 LU.AccessTy, F)) {
3434 // Add the offset to the base register.
3435 const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), *I), G);
3436 // If it cancelled out, drop the base register, otherwise update it.
3437 if (NewG->isZero()) {
3438 if (IsScaledReg) {
3439 F.Scale = 0;
3440 F.ScaledReg = nullptr;
3441 } else
3442 F.DeleteBaseReg(F.BaseRegs[Idx]);
3443 F.Canonicalize();
3444 } else if (IsScaledReg)
3445 F.ScaledReg = NewG;
3446 else
3447 F.BaseRegs[Idx] = NewG;
3448
3449 (void)InsertFormula(LU, LUIdx, F);
3450 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003451 }
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003452
3453 int64_t Imm = ExtractImmediate(G, SE);
3454 if (G->isZero() || Imm == 0)
3455 return;
3456 Formula F = Base;
3457 F.BaseOffset = (uint64_t)F.BaseOffset + Imm;
3458 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3459 return;
3460 if (IsScaledReg)
3461 F.ScaledReg = G;
3462 else
3463 F.BaseRegs[Idx] = G;
3464 (void)InsertFormula(LU, LUIdx, F);
Dan Gohman45774ce2010-02-12 10:34:29 +00003465}
3466
3467/// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
3468void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
3469 Formula Base) {
3470 // TODO: For now, just add the min and max offset, because it usually isn't
3471 // worthwhile looking at everything inbetween.
Dan Gohman4afd4122010-07-15 15:14:45 +00003472 SmallVector<int64_t, 2> Worklist;
Dan Gohman45774ce2010-02-12 10:34:29 +00003473 Worklist.push_back(LU.MinOffset);
3474 if (LU.MaxOffset != LU.MinOffset)
3475 Worklist.push_back(LU.MaxOffset);
3476
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003477 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3478 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i);
3479 if (Base.Scale == 1)
3480 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, /* Idx */ -1,
3481 /* IsScaledReg */ true);
Dan Gohman45774ce2010-02-12 10:34:29 +00003482}
3483
3484/// GenerateICmpZeroScales - For ICmpZero, check to see if we can scale up
3485/// the comparison. For example, x == y -> x*c == y*c.
3486void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
3487 Formula Base) {
3488 if (LU.Kind != LSRUse::ICmpZero) return;
3489
3490 // Determine the integer type for the base formula.
Chris Lattner229907c2011-07-18 04:54:35 +00003491 Type *IntTy = Base.getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00003492 if (!IntTy) return;
3493 if (SE.getTypeSizeInBits(IntTy) > 64) return;
3494
3495 // Don't do this if there is more than one offset.
3496 if (LU.MinOffset != LU.MaxOffset) return;
3497
Chandler Carruth6e479322013-01-07 15:04:40 +00003498 assert(!Base.BaseGV && "ICmpZero use is not legal!");
Dan Gohman45774ce2010-02-12 10:34:29 +00003499
3500 // Check each interesting stride.
3501 for (SmallSetVector<int64_t, 8>::const_iterator
3502 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
3503 int64_t Factor = *I;
Dan Gohman45774ce2010-02-12 10:34:29 +00003504
3505 // Check that the multiplication doesn't overflow.
Chandler Carruth6e479322013-01-07 15:04:40 +00003506 if (Base.BaseOffset == INT64_MIN && Factor == -1)
Dan Gohman5f10d6c2010-02-17 00:41:53 +00003507 continue;
Chandler Carruth6e479322013-01-07 15:04:40 +00003508 int64_t NewBaseOffset = (uint64_t)Base.BaseOffset * Factor;
3509 if (NewBaseOffset / Factor != Base.BaseOffset)
Dan Gohman45774ce2010-02-12 10:34:29 +00003510 continue;
Andrew Trick429e9ed2014-02-26 16:31:56 +00003511 // If the offset will be truncated at this use, check that it is in bounds.
3512 if (!IntTy->isPointerTy() &&
3513 !ConstantInt::isValueValidForType(IntTy, NewBaseOffset))
3514 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003515
3516 // Check that multiplying with the use offset doesn't overflow.
3517 int64_t Offset = LU.MinOffset;
Dan Gohman5f10d6c2010-02-17 00:41:53 +00003518 if (Offset == INT64_MIN && Factor == -1)
3519 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003520 Offset = (uint64_t)Offset * Factor;
Dan Gohman13ac3b22010-02-17 00:42:19 +00003521 if (Offset / Factor != LU.MinOffset)
Dan Gohman45774ce2010-02-12 10:34:29 +00003522 continue;
Andrew Trick429e9ed2014-02-26 16:31:56 +00003523 // If the offset will be truncated at this use, check that it is in bounds.
3524 if (!IntTy->isPointerTy() &&
3525 !ConstantInt::isValueValidForType(IntTy, Offset))
3526 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003527
Dan Gohman963b1c12010-06-24 16:57:52 +00003528 Formula F = Base;
Chandler Carruth6e479322013-01-07 15:04:40 +00003529 F.BaseOffset = NewBaseOffset;
Dan Gohman963b1c12010-06-24 16:57:52 +00003530
Dan Gohman45774ce2010-02-12 10:34:29 +00003531 // Check that this scale is legal.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003532 if (!isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F))
Dan Gohman45774ce2010-02-12 10:34:29 +00003533 continue;
3534
3535 // Compensate for the use having MinOffset built into it.
Chandler Carruth6e479322013-01-07 15:04:40 +00003536 F.BaseOffset = (uint64_t)F.BaseOffset + Offset - LU.MinOffset;
Dan Gohman45774ce2010-02-12 10:34:29 +00003537
Dan Gohman1d2ded72010-05-03 22:09:21 +00003538 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
Dan Gohman45774ce2010-02-12 10:34:29 +00003539
3540 // Check that multiplying with each base register doesn't overflow.
3541 for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
3542 F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
Dan Gohman4eebb942010-02-19 19:35:48 +00003543 if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
Dan Gohman45774ce2010-02-12 10:34:29 +00003544 goto next;
3545 }
3546
3547 // Check that multiplying with the scaled register doesn't overflow.
3548 if (F.ScaledReg) {
3549 F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
Dan Gohman4eebb942010-02-19 19:35:48 +00003550 if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
Dan Gohman45774ce2010-02-12 10:34:29 +00003551 continue;
3552 }
3553
Dan Gohman6136e942011-05-03 00:46:49 +00003554 // Check that multiplying with the unfolded offset doesn't overflow.
3555 if (F.UnfoldedOffset != 0) {
Dan Gohman6c4a3192011-05-23 21:07:39 +00003556 if (F.UnfoldedOffset == INT64_MIN && Factor == -1)
3557 continue;
Dan Gohman6136e942011-05-03 00:46:49 +00003558 F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor;
3559 if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset)
3560 continue;
Andrew Trick429e9ed2014-02-26 16:31:56 +00003561 // If the offset will be truncated, check that it is in bounds.
3562 if (!IntTy->isPointerTy() &&
3563 !ConstantInt::isValueValidForType(IntTy, F.UnfoldedOffset))
3564 continue;
Dan Gohman6136e942011-05-03 00:46:49 +00003565 }
3566
Dan Gohman45774ce2010-02-12 10:34:29 +00003567 // If we make it here and it's legal, add it.
3568 (void)InsertFormula(LU, LUIdx, F);
3569 next:;
3570 }
3571}
3572
3573/// GenerateScales - Generate stride factor reuse formulae by making use of
3574/// scaled-offset address modes, for example.
Dan Gohmanab5fb7f2010-05-20 19:44:23 +00003575void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003576 // Determine the integer type for the base formula.
Chris Lattner229907c2011-07-18 04:54:35 +00003577 Type *IntTy = Base.getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00003578 if (!IntTy) return;
3579
3580 // If this Formula already has a scaled register, we can't add another one.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003581 // Try to unscale the formula to generate a better scale.
3582 if (Base.Scale != 0 && !Base.Unscale())
3583 return;
3584
3585 assert(Base.Scale == 0 && "Unscale did not did its job!");
Dan Gohman45774ce2010-02-12 10:34:29 +00003586
3587 // Check each interesting stride.
3588 for (SmallSetVector<int64_t, 8>::const_iterator
3589 I = Factors.begin(), E = Factors.end(); I != E; ++I) {
3590 int64_t Factor = *I;
3591
Chandler Carruth6e479322013-01-07 15:04:40 +00003592 Base.Scale = Factor;
3593 Base.HasBaseReg = Base.BaseRegs.size() > 1;
Dan Gohman45774ce2010-02-12 10:34:29 +00003594 // Check whether this scale is going to be legal.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003595 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
3596 Base)) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003597 // As a special-case, handle special out-of-loop Basic users specially.
3598 // TODO: Reconsider this special case.
3599 if (LU.Kind == LSRUse::Basic &&
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003600 isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special,
3601 LU.AccessTy, Base) &&
Dan Gohman45774ce2010-02-12 10:34:29 +00003602 LU.AllFixupsOutsideLoop)
3603 LU.Kind = LSRUse::Special;
3604 else
3605 continue;
3606 }
3607 // For an ICmpZero, negating a solitary base register won't lead to
3608 // new solutions.
3609 if (LU.Kind == LSRUse::ICmpZero &&
Chandler Carruth6e479322013-01-07 15:04:40 +00003610 !Base.HasBaseReg && Base.BaseOffset == 0 && !Base.BaseGV)
Dan Gohman45774ce2010-02-12 10:34:29 +00003611 continue;
3612 // For each addrec base reg, apply the scale, if possible.
3613 for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3614 if (const SCEVAddRecExpr *AR =
3615 dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i])) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00003616 const SCEV *FactorS = SE.getConstant(IntTy, Factor);
Dan Gohman45774ce2010-02-12 10:34:29 +00003617 if (FactorS->isZero())
3618 continue;
3619 // Divide out the factor, ignoring high bits, since we'll be
3620 // scaling the value back up in the end.
Dan Gohman4eebb942010-02-19 19:35:48 +00003621 if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003622 // TODO: This could be optimized to avoid all the copying.
3623 Formula F = Base;
3624 F.ScaledReg = Quotient;
Dan Gohman80a96082010-05-20 15:17:54 +00003625 F.DeleteBaseReg(F.BaseRegs[i]);
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003626 // The canonical representation of 1*reg is reg, which is already in
3627 // Base. In that case, do not try to insert the formula, it will be
3628 // rejected anyway.
3629 if (F.Scale == 1 && F.BaseRegs.empty())
3630 continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003631 (void)InsertFormula(LU, LUIdx, F);
3632 }
3633 }
3634 }
3635}
3636
3637/// GenerateTruncates - Generate reuse formulae from different IV types.
Dan Gohmanab5fb7f2010-05-20 19:44:23 +00003638void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003639 // Don't bother truncating symbolic values.
Chandler Carruth6e479322013-01-07 15:04:40 +00003640 if (Base.BaseGV) return;
Dan Gohman45774ce2010-02-12 10:34:29 +00003641
3642 // Determine the integer type for the base formula.
Chris Lattner229907c2011-07-18 04:54:35 +00003643 Type *DstTy = Base.getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00003644 if (!DstTy) return;
3645 DstTy = SE.getEffectiveSCEVType(DstTy);
3646
Chris Lattner229907c2011-07-18 04:54:35 +00003647 for (SmallSetVector<Type *, 4>::const_iterator
Dan Gohman45774ce2010-02-12 10:34:29 +00003648 I = Types.begin(), E = Types.end(); I != E; ++I) {
Chris Lattner229907c2011-07-18 04:54:35 +00003649 Type *SrcTy = *I;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003650 if (SrcTy != DstTy && TTI.isTruncateFree(SrcTy, DstTy)) {
Dan Gohman45774ce2010-02-12 10:34:29 +00003651 Formula F = Base;
3652
3653 if (F.ScaledReg) F.ScaledReg = SE.getAnyExtendExpr(F.ScaledReg, *I);
3654 for (SmallVectorImpl<const SCEV *>::iterator J = F.BaseRegs.begin(),
3655 JE = F.BaseRegs.end(); J != JE; ++J)
3656 *J = SE.getAnyExtendExpr(*J, SrcTy);
3657
3658 // TODO: This assumes we've done basic processing on all uses and
3659 // have an idea what the register usage is.
3660 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
3661 continue;
3662
3663 (void)InsertFormula(LU, LUIdx, F);
3664 }
3665 }
3666}
3667
3668namespace {
3669
Dan Gohmane7f74bb2010-02-14 18:51:20 +00003670/// WorkItem - Helper class for GenerateCrossUseConstantOffsets. It's used to
Dan Gohman45774ce2010-02-12 10:34:29 +00003671/// defer modifications so that the search phase doesn't have to worry about
3672/// the data structures moving underneath it.
3673struct WorkItem {
3674 size_t LUIdx;
3675 int64_t Imm;
3676 const SCEV *OrigReg;
3677
3678 WorkItem(size_t LI, int64_t I, const SCEV *R)
3679 : LUIdx(LI), Imm(I), OrigReg(R) {}
3680
3681 void print(raw_ostream &OS) const;
3682 void dump() const;
3683};
3684
3685}
3686
3687void WorkItem::print(raw_ostream &OS) const {
3688 OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
3689 << " , add offset " << Imm;
3690}
3691
Manman Ren49d684e2012-09-12 05:06:18 +00003692#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman45774ce2010-02-12 10:34:29 +00003693void WorkItem::dump() const {
3694 print(errs()); errs() << '\n';
3695}
Manman Renc3366cc2012-09-06 19:55:56 +00003696#endif
Dan Gohman45774ce2010-02-12 10:34:29 +00003697
3698/// GenerateCrossUseConstantOffsets - Look for registers which are a constant
3699/// distance apart and try to form reuse opportunities between them.
3700void LSRInstance::GenerateCrossUseConstantOffsets() {
3701 // Group the registers by their value without any added constant offset.
3702 typedef std::map<int64_t, const SCEV *> ImmMapTy;
3703 typedef DenseMap<const SCEV *, ImmMapTy> RegMapTy;
3704 RegMapTy Map;
3705 DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
3706 SmallVector<const SCEV *, 8> Sequence;
3707 for (RegUseTracker::const_iterator I = RegUses.begin(), E = RegUses.end();
3708 I != E; ++I) {
3709 const SCEV *Reg = *I;
3710 int64_t Imm = ExtractImmediate(Reg, SE);
3711 std::pair<RegMapTy::iterator, bool> Pair =
3712 Map.insert(std::make_pair(Reg, ImmMapTy()));
3713 if (Pair.second)
3714 Sequence.push_back(Reg);
3715 Pair.first->second.insert(std::make_pair(Imm, *I));
3716 UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(*I);
3717 }
3718
3719 // Now examine each set of registers with the same base value. Build up
3720 // a list of work to do and do the work in a separate step so that we're
3721 // not adding formulae and register counts while we're searching.
Dan Gohman110ed642010-09-01 01:45:53 +00003722 SmallVector<WorkItem, 32> WorkItems;
3723 SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
Dan Gohman45774ce2010-02-12 10:34:29 +00003724 for (SmallVectorImpl<const SCEV *>::const_iterator I = Sequence.begin(),
3725 E = Sequence.end(); I != E; ++I) {
3726 const SCEV *Reg = *I;
3727 const ImmMapTy &Imms = Map.find(Reg)->second;
3728
Dan Gohman363f8472010-02-12 19:20:37 +00003729 // It's not worthwhile looking for reuse if there's only one offset.
3730 if (Imms.size() == 1)
3731 continue;
3732
Dan Gohman45774ce2010-02-12 10:34:29 +00003733 DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
3734 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
3735 J != JE; ++J)
3736 dbgs() << ' ' << J->first;
3737 dbgs() << '\n');
3738
3739 // Examine each offset.
3740 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
3741 J != JE; ++J) {
3742 const SCEV *OrigReg = J->second;
3743
3744 int64_t JImm = J->first;
3745 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
3746
3747 if (!isa<SCEVConstant>(OrigReg) &&
3748 UsedByIndicesMap[Reg].count() == 1) {
3749 DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg << '\n');
3750 continue;
3751 }
3752
3753 // Conservatively examine offsets between this orig reg a few selected
3754 // other orig regs.
3755 ImmMapTy::const_iterator OtherImms[] = {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00003756 Imms.begin(), std::prev(Imms.end()),
3757 Imms.lower_bound((Imms.begin()->first + std::prev(Imms.end())->first) /
3758 2)
Dan Gohman45774ce2010-02-12 10:34:29 +00003759 };
3760 for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
3761 ImmMapTy::const_iterator M = OtherImms[i];
Dan Gohman363f8472010-02-12 19:20:37 +00003762 if (M == J || M == JE) continue;
Dan Gohman45774ce2010-02-12 10:34:29 +00003763
3764 // Compute the difference between the two.
3765 int64_t Imm = (uint64_t)JImm - M->first;
3766 for (int LUIdx = UsedByIndices.find_first(); LUIdx != -1;
Dan Gohman110ed642010-09-01 01:45:53 +00003767 LUIdx = UsedByIndices.find_next(LUIdx))
Dan Gohman45774ce2010-02-12 10:34:29 +00003768 // Make a memo of this use, offset, and register tuple.
David Blaikie70573dc2014-11-19 07:49:26 +00003769 if (UniqueItems.insert(std::make_pair(LUIdx, Imm)).second)
Dan Gohman110ed642010-09-01 01:45:53 +00003770 WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
Evan Cheng85a9f432009-11-12 07:35:05 +00003771 }
3772 }
3773 }
3774
Dan Gohman45774ce2010-02-12 10:34:29 +00003775 Map.clear();
3776 Sequence.clear();
3777 UsedByIndicesMap.clear();
Dan Gohman110ed642010-09-01 01:45:53 +00003778 UniqueItems.clear();
Dan Gohman45774ce2010-02-12 10:34:29 +00003779
3780 // Now iterate through the worklist and add new formulae.
3781 for (SmallVectorImpl<WorkItem>::const_iterator I = WorkItems.begin(),
3782 E = WorkItems.end(); I != E; ++I) {
3783 const WorkItem &WI = *I;
3784 size_t LUIdx = WI.LUIdx;
3785 LSRUse &LU = Uses[LUIdx];
3786 int64_t Imm = WI.Imm;
3787 const SCEV *OrigReg = WI.OrigReg;
3788
Chris Lattner229907c2011-07-18 04:54:35 +00003789 Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
Dan Gohman45774ce2010-02-12 10:34:29 +00003790 const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
3791 unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
3792
Dan Gohman8b0a4192010-03-01 17:49:51 +00003793 // TODO: Use a more targeted data structure.
Dan Gohman45774ce2010-02-12 10:34:29 +00003794 for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003795 Formula F = LU.Formulae[L];
3796 // FIXME: The code for the scaled and unscaled registers looks
3797 // very similar but slightly different. Investigate if they
3798 // could be merged. That way, we would not have to unscale the
3799 // Formula.
3800 F.Unscale();
Dan Gohman45774ce2010-02-12 10:34:29 +00003801 // Use the immediate in the scaled register.
3802 if (F.ScaledReg == OrigReg) {
Chandler Carruth6e479322013-01-07 15:04:40 +00003803 int64_t Offset = (uint64_t)F.BaseOffset + Imm * (uint64_t)F.Scale;
Dan Gohman45774ce2010-02-12 10:34:29 +00003804 // Don't create 50 + reg(-50).
3805 if (F.referencesReg(SE.getSCEV(
Chandler Carruth6e479322013-01-07 15:04:40 +00003806 ConstantInt::get(IntTy, -(uint64_t)Offset))))
Dan Gohman45774ce2010-02-12 10:34:29 +00003807 continue;
3808 Formula NewF = F;
Chandler Carruth6e479322013-01-07 15:04:40 +00003809 NewF.BaseOffset = Offset;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003810 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
3811 NewF))
Dan Gohman45774ce2010-02-12 10:34:29 +00003812 continue;
3813 NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
3814
3815 // If the new scale is a constant in a register, and adding the constant
3816 // value to the immediate would produce a value closer to zero than the
3817 // immediate itself, then the formula isn't worthwhile.
3818 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
Chris Lattnerb1a15122011-07-15 06:08:15 +00003819 if (C->getValue()->isNegative() !=
Chandler Carruth6e479322013-01-07 15:04:40 +00003820 (NewF.BaseOffset < 0) &&
3821 (C->getValue()->getValue().abs() * APInt(BitWidth, F.Scale))
Benjamin Kramer7bd1f7c2015-03-09 20:20:16 +00003822 .ule(std::abs(NewF.BaseOffset)))
Dan Gohman45774ce2010-02-12 10:34:29 +00003823 continue;
3824
3825 // OK, looks good.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003826 NewF.Canonicalize();
Dan Gohman45774ce2010-02-12 10:34:29 +00003827 (void)InsertFormula(LU, LUIdx, NewF);
3828 } else {
3829 // Use the immediate in a base register.
3830 for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
3831 const SCEV *BaseReg = F.BaseRegs[N];
3832 if (BaseReg != OrigReg)
3833 continue;
3834 Formula NewF = F;
Chandler Carruth6e479322013-01-07 15:04:40 +00003835 NewF.BaseOffset = (uint64_t)NewF.BaseOffset + Imm;
Chandler Carruth26c59fa2013-01-07 14:41:08 +00003836 if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset,
3837 LU.Kind, LU.AccessTy, NewF)) {
3838 if (!TTI.isLegalAddImmediate((uint64_t)NewF.UnfoldedOffset + Imm))
Dan Gohman6136e942011-05-03 00:46:49 +00003839 continue;
3840 NewF = F;
3841 NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm;
3842 }
Dan Gohman45774ce2010-02-12 10:34:29 +00003843 NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
3844
3845 // If the new formula has a constant in a register, and adding the
3846 // constant value to the immediate would produce a value closer to
3847 // zero than the immediate itself, then the formula isn't worthwhile.
Craig Topper77b99412015-05-23 08:01:41 +00003848 for (const SCEV *J : NewF.BaseRegs)
3849 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(J))
Chandler Carruth6e479322013-01-07 15:04:40 +00003850 if ((C->getValue()->getValue() + NewF.BaseOffset).abs().slt(
Benjamin Kramer7bd1f7c2015-03-09 20:20:16 +00003851 std::abs(NewF.BaseOffset)) &&
Dan Gohman50f8f2c2010-05-18 23:48:08 +00003852 (C->getValue()->getValue() +
Chandler Carruth6e479322013-01-07 15:04:40 +00003853 NewF.BaseOffset).countTrailingZeros() >=
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00003854 countTrailingZeros<uint64_t>(NewF.BaseOffset))
Dan Gohman45774ce2010-02-12 10:34:29 +00003855 goto skip_formula;
3856
3857 // Ok, looks good.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00003858 NewF.Canonicalize();
Dan Gohman45774ce2010-02-12 10:34:29 +00003859 (void)InsertFormula(LU, LUIdx, NewF);
3860 break;
3861 skip_formula:;
3862 }
3863 }
3864 }
3865 }
Dale Johannesen02cb2bf2009-05-11 17:15:42 +00003866}
3867
Dan Gohman45774ce2010-02-12 10:34:29 +00003868/// GenerateAllReuseFormulae - Generate formulae for each use.
3869void
3870LSRInstance::GenerateAllReuseFormulae() {
Dan Gohman521efe62010-02-16 01:42:53 +00003871 // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
Dan Gohman45774ce2010-02-12 10:34:29 +00003872 // queries are more precise.
3873 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3874 LSRUse &LU = Uses[LUIdx];
3875 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3876 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
3877 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3878 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
3879 }
3880 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3881 LSRUse &LU = Uses[LUIdx];
3882 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3883 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
3884 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3885 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
3886 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3887 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
3888 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3889 GenerateScales(LU, LUIdx, LU.Formulae[i]);
Dan Gohman521efe62010-02-16 01:42:53 +00003890 }
3891 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3892 LSRUse &LU = Uses[LUIdx];
Dan Gohman45774ce2010-02-12 10:34:29 +00003893 for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
3894 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
3895 }
3896
3897 GenerateCrossUseConstantOffsets();
Dan Gohmanbf673e02010-08-29 15:21:38 +00003898
3899 DEBUG(dbgs() << "\n"
3900 "After generating reuse formulae:\n";
3901 print_uses(dbgs()));
Dan Gohman45774ce2010-02-12 10:34:29 +00003902}
3903
Dan Gohman1b61fd92010-10-07 23:43:09 +00003904/// If there are multiple formulae with the same set of registers used
Dan Gohman45774ce2010-02-12 10:34:29 +00003905/// by other uses, pick the best one and delete the others.
3906void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
Dan Gohman5947e162010-10-07 23:52:18 +00003907 DenseSet<const SCEV *> VisitedRegs;
3908 SmallPtrSet<const SCEV *, 16> Regs;
Andrew Trick5df90962011-12-06 03:13:31 +00003909 SmallPtrSet<const SCEV *, 16> LoserRegs;
Dan Gohman45774ce2010-02-12 10:34:29 +00003910#ifndef NDEBUG
Dan Gohman4c4043c2010-05-20 20:05:31 +00003911 bool ChangedFormulae = false;
Dan Gohman45774ce2010-02-12 10:34:29 +00003912#endif
3913
3914 // Collect the best formula for each unique set of shared registers. This
3915 // is reset for each use.
Preston Gurd25c3b6a2013-02-01 20:41:27 +00003916 typedef DenseMap<SmallVector<const SCEV *, 4>, size_t, UniquifierDenseMapInfo>
Dan Gohman45774ce2010-02-12 10:34:29 +00003917 BestFormulaeTy;
3918 BestFormulaeTy BestFormulae;
3919
3920 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
3921 LSRUse &LU = Uses[LUIdx];
Dan Gohmanab5fb7f2010-05-20 19:44:23 +00003922 DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs()); dbgs() << '\n');
Dan Gohman45774ce2010-02-12 10:34:29 +00003923
Dan Gohman4cf99b52010-05-18 23:42:37 +00003924 bool Any = false;
Dan Gohman45774ce2010-02-12 10:34:29 +00003925 for (size_t FIdx = 0, NumForms = LU.Formulae.size();
3926 FIdx != NumForms; ++FIdx) {
3927 Formula &F = LU.Formulae[FIdx];
3928
Andrew Trick5df90962011-12-06 03:13:31 +00003929 // Some formulas are instant losers. For example, they may depend on
3930 // nonexistent AddRecs from other loops. These need to be filtered
3931 // immediately, otherwise heuristics could choose them over others leading
3932 // to an unsatisfactory solution. Passing LoserRegs into RateFormula here
3933 // avoids the need to recompute this information across formulae using the
3934 // same bad AddRec. Passing LoserRegs is also essential unless we remove
3935 // the corresponding bad register from the Regs set.
3936 Cost CostF;
3937 Regs.clear();
Quentin Colombet8aa7abe2013-05-31 17:20:29 +00003938 CostF.RateFormula(TTI, F, Regs, VisitedRegs, L, LU.Offsets, SE, DT, LU,
Andrew Trick5df90962011-12-06 03:13:31 +00003939 &LoserRegs);
3940 if (CostF.isLoser()) {
3941 // During initial formula generation, undesirable formulae are generated
3942 // by uses within other loops that have some non-trivial address mode or
3943 // use the postinc form of the IV. LSR needs to provide these formulae
3944 // as the basis of rediscovering the desired formula that uses an AddRec
3945 // corresponding to the existing phi. Once all formulae have been
3946 // generated, these initial losers may be pruned.
3947 DEBUG(dbgs() << " Filtering loser "; F.print(dbgs());
3948 dbgs() << "\n");
Dan Gohman45774ce2010-02-12 10:34:29 +00003949 }
Andrew Trick5df90962011-12-06 03:13:31 +00003950 else {
Preston Gurd25c3b6a2013-02-01 20:41:27 +00003951 SmallVector<const SCEV *, 4> Key;
Craig Topper77b99412015-05-23 08:01:41 +00003952 for (const SCEV *Reg : F.BaseRegs) {
Andrew Trick5df90962011-12-06 03:13:31 +00003953 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
3954 Key.push_back(Reg);
3955 }
3956 if (F.ScaledReg &&
3957 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
3958 Key.push_back(F.ScaledReg);
3959 // Unstable sort by host order ok, because this is only used for
3960 // uniquifying.
3961 std::sort(Key.begin(), Key.end());
Dan Gohman45774ce2010-02-12 10:34:29 +00003962
Andrew Trick5df90962011-12-06 03:13:31 +00003963 std::pair<BestFormulaeTy::const_iterator, bool> P =
3964 BestFormulae.insert(std::make_pair(Key, FIdx));
3965 if (P.second)
3966 continue;
3967
Dan Gohman45774ce2010-02-12 10:34:29 +00003968 Formula &Best = LU.Formulae[P.first->second];
Dan Gohman5947e162010-10-07 23:52:18 +00003969
Dan Gohman5947e162010-10-07 23:52:18 +00003970 Cost CostBest;
Dan Gohman5947e162010-10-07 23:52:18 +00003971 Regs.clear();
Quentin Colombet8aa7abe2013-05-31 17:20:29 +00003972 CostBest.RateFormula(TTI, Best, Regs, VisitedRegs, L, LU.Offsets, SE,
3973 DT, LU);
Dan Gohman5947e162010-10-07 23:52:18 +00003974 if (CostF < CostBest)
Dan Gohman45774ce2010-02-12 10:34:29 +00003975 std::swap(F, Best);
Dan Gohman8aca7ef2010-05-18 22:37:37 +00003976 DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
Dan Gohman45774ce2010-02-12 10:34:29 +00003977 dbgs() << "\n"
Dan Gohman8aca7ef2010-05-18 22:37:37 +00003978 " in favor of formula "; Best.print(dbgs());
Dan Gohman45774ce2010-02-12 10:34:29 +00003979 dbgs() << '\n');
Dan Gohman45774ce2010-02-12 10:34:29 +00003980 }
Andrew Trick5df90962011-12-06 03:13:31 +00003981#ifndef NDEBUG
3982 ChangedFormulae = true;
3983#endif
3984 LU.DeleteFormula(F);
3985 --FIdx;
3986 --NumForms;
3987 Any = true;
Dan Gohmand0800242010-05-07 23:36:59 +00003988 }
3989
Dan Gohmanbeebef42010-05-18 23:55:57 +00003990 // Now that we've filtered out some formulae, recompute the Regs set.
Dan Gohman4cf99b52010-05-18 23:42:37 +00003991 if (Any)
3992 LU.RecomputeRegs(LUIdx, RegUses);
Dan Gohmand0800242010-05-07 23:36:59 +00003993
3994 // Reset this to prepare for the next use.
Dan Gohman45774ce2010-02-12 10:34:29 +00003995 BestFormulae.clear();
3996 }
3997
Dan Gohman4c4043c2010-05-20 20:05:31 +00003998 DEBUG(if (ChangedFormulae) {
Dan Gohman5b18f032010-02-13 02:06:02 +00003999 dbgs() << "\n"
4000 "After filtering out undesirable candidates:\n";
Dan Gohman45774ce2010-02-12 10:34:29 +00004001 print_uses(dbgs());
4002 });
4003}
4004
Dan Gohmana4eca052010-05-18 22:51:59 +00004005// This is a rough guess that seems to work fairly well.
4006static const size_t ComplexityLimit = UINT16_MAX;
4007
4008/// EstimateSearchSpaceComplexity - Estimate the worst-case number of
4009/// solutions the solver might have to consider. It almost never considers
4010/// this many solutions because it prune the search space, but the pruning
4011/// isn't always sufficient.
4012size_t LSRInstance::EstimateSearchSpaceComplexity() const {
Dan Gohman49d638b2010-10-07 23:37:58 +00004013 size_t Power = 1;
Craig Topper77b99412015-05-23 08:01:41 +00004014 for (const LSRUse &I : Uses) {
4015 size_t FSize = I.Formulae.size();
Dan Gohmana4eca052010-05-18 22:51:59 +00004016 if (FSize >= ComplexityLimit) {
4017 Power = ComplexityLimit;
4018 break;
4019 }
4020 Power *= FSize;
4021 if (Power >= ComplexityLimit)
4022 break;
4023 }
4024 return Power;
4025}
4026
Dan Gohmane9e08732010-08-29 16:09:42 +00004027/// NarrowSearchSpaceByDetectingSupersets - When one formula uses a superset
4028/// of the registers of another formula, it won't help reduce register
4029/// pressure (though it may not necessarily hurt register pressure); remove
4030/// it to simplify the system.
4031void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
Dan Gohman20fab452010-05-19 23:43:12 +00004032 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4033 DEBUG(dbgs() << "The search space is too complex.\n");
4034
4035 DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
4036 "which use a superset of registers used by other "
4037 "formulae.\n");
4038
4039 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4040 LSRUse &LU = Uses[LUIdx];
4041 bool Any = false;
4042 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4043 Formula &F = LU.Formulae[i];
Dan Gohman8ec018c2010-05-20 20:00:41 +00004044 // Look for a formula with a constant or GV in a register. If the use
4045 // also has a formula with that same value in an immediate field,
4046 // delete the one that uses a register.
Dan Gohman20fab452010-05-19 23:43:12 +00004047 for (SmallVectorImpl<const SCEV *>::const_iterator
4048 I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
4049 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
4050 Formula NewF = F;
Chandler Carruth6e479322013-01-07 15:04:40 +00004051 NewF.BaseOffset += C->getValue()->getSExtValue();
Dan Gohman20fab452010-05-19 23:43:12 +00004052 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4053 (I - F.BaseRegs.begin()));
4054 if (LU.HasFormulaWithSameRegs(NewF)) {
4055 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
4056 LU.DeleteFormula(F);
4057 --i;
4058 --e;
4059 Any = true;
4060 break;
4061 }
4062 } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
4063 if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
Chandler Carruth6e479322013-01-07 15:04:40 +00004064 if (!F.BaseGV) {
Dan Gohman20fab452010-05-19 23:43:12 +00004065 Formula NewF = F;
Chandler Carruth6e479322013-01-07 15:04:40 +00004066 NewF.BaseGV = GV;
Dan Gohman20fab452010-05-19 23:43:12 +00004067 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4068 (I - F.BaseRegs.begin()));
4069 if (LU.HasFormulaWithSameRegs(NewF)) {
4070 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
4071 dbgs() << '\n');
4072 LU.DeleteFormula(F);
4073 --i;
4074 --e;
4075 Any = true;
4076 break;
4077 }
4078 }
4079 }
4080 }
4081 }
4082 if (Any)
4083 LU.RecomputeRegs(LUIdx, RegUses);
4084 }
4085
4086 DEBUG(dbgs() << "After pre-selection:\n";
4087 print_uses(dbgs()));
4088 }
Dan Gohmane9e08732010-08-29 16:09:42 +00004089}
Dan Gohman20fab452010-05-19 23:43:12 +00004090
Dan Gohmane9e08732010-08-29 16:09:42 +00004091/// NarrowSearchSpaceByCollapsingUnrolledCode - When there are many registers
4092/// for expressions like A, A+1, A+2, etc., allocate a single register for
4093/// them.
4094void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
Jakub Staszak11bd8352013-02-16 16:08:15 +00004095 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4096 return;
Dan Gohman20fab452010-05-19 23:43:12 +00004097
Jakub Staszak11bd8352013-02-16 16:08:15 +00004098 DEBUG(dbgs() << "The search space is too complex.\n"
4099 "Narrowing the search space by assuming that uses separated "
4100 "by a constant offset will use the same registers.\n");
Dan Gohman20fab452010-05-19 23:43:12 +00004101
Jakub Staszak11bd8352013-02-16 16:08:15 +00004102 // This is especially useful for unrolled loops.
Dan Gohman8ec018c2010-05-20 20:00:41 +00004103
Jakub Staszak11bd8352013-02-16 16:08:15 +00004104 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4105 LSRUse &LU = Uses[LUIdx];
Craig Topper77b99412015-05-23 08:01:41 +00004106 for (const Formula &F : LU.Formulae) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004107 if (F.BaseOffset == 0 || (F.Scale != 0 && F.Scale != 1))
Jakub Staszak11bd8352013-02-16 16:08:15 +00004108 continue;
Dan Gohman20fab452010-05-19 23:43:12 +00004109
Jakub Staszak11bd8352013-02-16 16:08:15 +00004110 LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU);
4111 if (!LUThatHas)
4112 continue;
Dan Gohman20fab452010-05-19 23:43:12 +00004113
Jakub Staszak11bd8352013-02-16 16:08:15 +00004114 if (!reconcileNewOffset(*LUThatHas, F.BaseOffset, /*HasBaseReg=*/ false,
4115 LU.Kind, LU.AccessTy))
4116 continue;
Dan Gohman110ed642010-09-01 01:45:53 +00004117
Jakub Staszak11bd8352013-02-16 16:08:15 +00004118 DEBUG(dbgs() << " Deleting use "; LU.print(dbgs()); dbgs() << '\n');
Dan Gohman2fd85d72010-10-08 19:33:26 +00004119
Jakub Staszak11bd8352013-02-16 16:08:15 +00004120 LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
4121
4122 // Update the relocs to reference the new use.
Craig Topper77b99412015-05-23 08:01:41 +00004123 for (LSRFixup &Fixup : Fixups) {
Jakub Staszak11bd8352013-02-16 16:08:15 +00004124 if (Fixup.LUIdx == LUIdx) {
4125 Fixup.LUIdx = LUThatHas - &Uses.front();
4126 Fixup.Offset += F.BaseOffset;
4127 // Add the new offset to LUThatHas' offset list.
4128 if (LUThatHas->Offsets.back() != Fixup.Offset) {
4129 LUThatHas->Offsets.push_back(Fixup.Offset);
4130 if (Fixup.Offset > LUThatHas->MaxOffset)
4131 LUThatHas->MaxOffset = Fixup.Offset;
4132 if (Fixup.Offset < LUThatHas->MinOffset)
4133 LUThatHas->MinOffset = Fixup.Offset;
Dan Gohman20fab452010-05-19 23:43:12 +00004134 }
Jakub Staszak11bd8352013-02-16 16:08:15 +00004135 DEBUG(dbgs() << "New fixup has offset " << Fixup.Offset << '\n');
4136 }
4137 if (Fixup.LUIdx == NumUses-1)
4138 Fixup.LUIdx = LUIdx;
4139 }
4140
4141 // Delete formulae from the new use which are no longer legal.
4142 bool Any = false;
4143 for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
4144 Formula &F = LUThatHas->Formulae[i];
4145 if (!isLegalUse(TTI, LUThatHas->MinOffset, LUThatHas->MaxOffset,
4146 LUThatHas->Kind, LUThatHas->AccessTy, F)) {
4147 DEBUG(dbgs() << " Deleting "; F.print(dbgs());
4148 dbgs() << '\n');
4149 LUThatHas->DeleteFormula(F);
4150 --i;
4151 --e;
4152 Any = true;
Dan Gohman20fab452010-05-19 23:43:12 +00004153 }
4154 }
Dan Gohman20fab452010-05-19 23:43:12 +00004155
Jakub Staszak11bd8352013-02-16 16:08:15 +00004156 if (Any)
4157 LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
4158
4159 // Delete the old use.
4160 DeleteUse(LU, LUIdx);
4161 --LUIdx;
4162 --NumUses;
4163 break;
4164 }
Dan Gohman20fab452010-05-19 23:43:12 +00004165 }
Jakub Staszak11bd8352013-02-16 16:08:15 +00004166
4167 DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
Dan Gohmane9e08732010-08-29 16:09:42 +00004168}
Dan Gohman20fab452010-05-19 23:43:12 +00004169
Andrew Trick8b55b732011-03-14 16:50:06 +00004170/// NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters - Call
Dan Gohman002ff892010-08-29 16:39:22 +00004171/// FilterOutUndesirableDedicatedRegisters again, if necessary, now that
4172/// we've done more filtering, as it may be able to find more formulae to
4173/// eliminate.
4174void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
4175 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4176 DEBUG(dbgs() << "The search space is too complex.\n");
4177
4178 DEBUG(dbgs() << "Narrowing the search space by re-filtering out "
4179 "undesirable dedicated registers.\n");
4180
4181 FilterOutUndesirableDedicatedRegisters();
4182
4183 DEBUG(dbgs() << "After pre-selection:\n";
4184 print_uses(dbgs()));
4185 }
4186}
4187
Dan Gohmane9e08732010-08-29 16:09:42 +00004188/// NarrowSearchSpaceByPickingWinnerRegs - Pick a register which seems likely
4189/// to be profitable, and then in any use which has any reference to that
4190/// register, delete all formulae which do not reference that register.
4191void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
Dan Gohmana4ca28a2010-05-20 20:52:00 +00004192 // With all other options exhausted, loop until the system is simple
4193 // enough to handle.
Dan Gohman45774ce2010-02-12 10:34:29 +00004194 SmallPtrSet<const SCEV *, 4> Taken;
Dan Gohmana4eca052010-05-18 22:51:59 +00004195 while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004196 // Ok, we have too many of formulae on our hands to conveniently handle.
4197 // Use a rough heuristic to thin out the list.
Dan Gohman63e90152010-05-18 22:41:32 +00004198 DEBUG(dbgs() << "The search space is too complex.\n");
Dan Gohman45774ce2010-02-12 10:34:29 +00004199
4200 // Pick the register which is used by the most LSRUses, which is likely
4201 // to be a good reuse register candidate.
Craig Topperf40110f2014-04-25 05:29:35 +00004202 const SCEV *Best = nullptr;
Dan Gohman45774ce2010-02-12 10:34:29 +00004203 unsigned BestNum = 0;
Craig Topper77b99412015-05-23 08:01:41 +00004204 for (const SCEV *Reg : RegUses) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004205 if (Taken.count(Reg))
4206 continue;
4207 if (!Best)
4208 Best = Reg;
4209 else {
4210 unsigned Count = RegUses.getUsedByIndices(Reg).count();
4211 if (Count > BestNum) {
4212 Best = Reg;
4213 BestNum = Count;
4214 }
4215 }
4216 }
4217
4218 DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
Dan Gohman8b0a4192010-03-01 17:49:51 +00004219 << " will yield profitable reuse.\n");
Dan Gohman45774ce2010-02-12 10:34:29 +00004220 Taken.insert(Best);
4221
4222 // In any use with formulae which references this register, delete formulae
4223 // which don't reference it.
Dan Gohman4cf99b52010-05-18 23:42:37 +00004224 for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4225 LSRUse &LU = Uses[LUIdx];
Dan Gohman45774ce2010-02-12 10:34:29 +00004226 if (!LU.Regs.count(Best)) continue;
4227
Dan Gohman4cf99b52010-05-18 23:42:37 +00004228 bool Any = false;
Dan Gohman45774ce2010-02-12 10:34:29 +00004229 for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4230 Formula &F = LU.Formulae[i];
4231 if (!F.referencesReg(Best)) {
4232 DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
Dan Gohmanf1c7b1b2010-05-18 22:39:15 +00004233 LU.DeleteFormula(F);
Dan Gohman45774ce2010-02-12 10:34:29 +00004234 --e;
4235 --i;
Dan Gohman4cf99b52010-05-18 23:42:37 +00004236 Any = true;
Dan Gohmand0800242010-05-07 23:36:59 +00004237 assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
Dan Gohman45774ce2010-02-12 10:34:29 +00004238 continue;
4239 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004240 }
Dan Gohman4cf99b52010-05-18 23:42:37 +00004241
4242 if (Any)
4243 LU.RecomputeRegs(LUIdx, RegUses);
Dan Gohman45774ce2010-02-12 10:34:29 +00004244 }
4245
4246 DEBUG(dbgs() << "After pre-selection:\n";
4247 print_uses(dbgs()));
4248 }
4249}
4250
Dan Gohmane9e08732010-08-29 16:09:42 +00004251/// NarrowSearchSpaceUsingHeuristics - If there are an extraordinary number of
4252/// formulae to choose from, use some rough heuristics to prune down the number
4253/// of formulae. This keeps the main solver from taking an extraordinary amount
4254/// of time in some worst-case scenarios.
4255void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
4256 NarrowSearchSpaceByDetectingSupersets();
4257 NarrowSearchSpaceByCollapsingUnrolledCode();
Dan Gohman002ff892010-08-29 16:39:22 +00004258 NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
Dan Gohmane9e08732010-08-29 16:09:42 +00004259 NarrowSearchSpaceByPickingWinnerRegs();
4260}
4261
Dan Gohman45774ce2010-02-12 10:34:29 +00004262/// SolveRecurse - This is the recursive solver.
4263void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
4264 Cost &SolutionCost,
4265 SmallVectorImpl<const Formula *> &Workspace,
4266 const Cost &CurCost,
4267 const SmallPtrSet<const SCEV *, 16> &CurRegs,
4268 DenseSet<const SCEV *> &VisitedRegs) const {
4269 // Some ideas:
4270 // - prune more:
4271 // - use more aggressive filtering
4272 // - sort the formula so that the most profitable solutions are found first
4273 // - sort the uses too
4274 // - search faster:
Dan Gohman8b0a4192010-03-01 17:49:51 +00004275 // - don't compute a cost, and then compare. compare while computing a cost
Dan Gohman45774ce2010-02-12 10:34:29 +00004276 // and bail early.
4277 // - track register sets with SmallBitVector
4278
4279 const LSRUse &LU = Uses[Workspace.size()];
4280
4281 // If this use references any register that's already a part of the
4282 // in-progress solution, consider it a requirement that a formula must
4283 // reference that register in order to be considered. This prunes out
4284 // unprofitable searching.
4285 SmallSetVector<const SCEV *, 4> ReqRegs;
Craig Topper46276792014-08-24 23:23:06 +00004286 for (const SCEV *S : CurRegs)
4287 if (LU.Regs.count(S))
4288 ReqRegs.insert(S);
Dan Gohman45774ce2010-02-12 10:34:29 +00004289
4290 SmallPtrSet<const SCEV *, 16> NewRegs;
4291 Cost NewCost;
Craig Topper77b99412015-05-23 08:01:41 +00004292 for (const Formula &F : LU.Formulae) {
Adam Nemetdeab6f92014-04-29 18:25:28 +00004293 // Ignore formulae which may not be ideal in terms of register reuse of
4294 // ReqRegs. The formula should use all required registers before
4295 // introducing new ones.
4296 int NumReqRegsToFind = std::min(F.getNumRegs(), ReqRegs.size());
Craig Topper77b99412015-05-23 08:01:41 +00004297 for (const SCEV *Reg : ReqRegs) {
Adam Nemetdeab6f92014-04-29 18:25:28 +00004298 if ((F.ScaledReg && F.ScaledReg == Reg) ||
4299 std::find(F.BaseRegs.begin(), F.BaseRegs.end(), Reg) !=
Andrew Tricke3502cb2012-03-22 22:42:51 +00004300 F.BaseRegs.end()) {
Adam Nemetdeab6f92014-04-29 18:25:28 +00004301 --NumReqRegsToFind;
4302 if (NumReqRegsToFind == 0)
4303 break;
Andrew Tricke3502cb2012-03-22 22:42:51 +00004304 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004305 }
Adam Nemetdeab6f92014-04-29 18:25:28 +00004306 if (NumReqRegsToFind != 0) {
Andrew Tricke3502cb2012-03-22 22:42:51 +00004307 // If none of the formulae satisfied the required registers, then we could
4308 // clear ReqRegs and try again. Currently, we simply give up in this case.
4309 continue;
4310 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004311
4312 // Evaluate the cost of the current formula. If it's already worse than
4313 // the current best, prune the search at that point.
4314 NewCost = CurCost;
4315 NewRegs = CurRegs;
Quentin Colombet8aa7abe2013-05-31 17:20:29 +00004316 NewCost.RateFormula(TTI, F, NewRegs, VisitedRegs, L, LU.Offsets, SE, DT,
4317 LU);
Dan Gohman45774ce2010-02-12 10:34:29 +00004318 if (NewCost < SolutionCost) {
4319 Workspace.push_back(&F);
4320 if (Workspace.size() != Uses.size()) {
4321 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
4322 NewRegs, VisitedRegs);
4323 if (F.getNumRegs() == 1 && Workspace.size() == 1)
4324 VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
4325 } else {
4326 DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
Andrew Trick4dc3eff2012-01-09 18:58:16 +00004327 dbgs() << ".\n Regs:";
Craig Topper46276792014-08-24 23:23:06 +00004328 for (const SCEV *S : NewRegs)
4329 dbgs() << ' ' << *S;
Dan Gohman45774ce2010-02-12 10:34:29 +00004330 dbgs() << '\n');
4331
4332 SolutionCost = NewCost;
4333 Solution = Workspace;
4334 }
4335 Workspace.pop_back();
4336 }
Dan Gohman5b18f032010-02-13 02:06:02 +00004337 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004338}
4339
Dan Gohmana4ca28a2010-05-20 20:52:00 +00004340/// Solve - Choose one formula from each use. Return the results in the given
4341/// Solution vector.
Dan Gohman45774ce2010-02-12 10:34:29 +00004342void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
4343 SmallVector<const Formula *, 8> Workspace;
4344 Cost SolutionCost;
Tim Northoverbc6659c2014-01-22 13:27:00 +00004345 SolutionCost.Lose();
Dan Gohman45774ce2010-02-12 10:34:29 +00004346 Cost CurCost;
4347 SmallPtrSet<const SCEV *, 16> CurRegs;
4348 DenseSet<const SCEV *> VisitedRegs;
4349 Workspace.reserve(Uses.size());
4350
Dan Gohman8ec018c2010-05-20 20:00:41 +00004351 // SolveRecurse does all the work.
Dan Gohman45774ce2010-02-12 10:34:29 +00004352 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
4353 CurRegs, VisitedRegs);
Andrew Trick58124392011-09-27 00:44:14 +00004354 if (Solution.empty()) {
4355 DEBUG(dbgs() << "\nNo Satisfactory Solution\n");
4356 return;
4357 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004358
4359 // Ok, we've now made all our decisions.
4360 DEBUG(dbgs() << "\n"
4361 "The chosen solution requires "; SolutionCost.print(dbgs());
4362 dbgs() << ":\n";
4363 for (size_t i = 0, e = Uses.size(); i != e; ++i) {
4364 dbgs() << " ";
4365 Uses[i].print(dbgs());
4366 dbgs() << "\n"
4367 " ";
4368 Solution[i]->print(dbgs());
4369 dbgs() << '\n';
4370 });
Dan Gohman6295f2e2010-05-20 20:59:23 +00004371
4372 assert(Solution.size() == Uses.size() && "Malformed solution!");
Dan Gohman45774ce2010-02-12 10:34:29 +00004373}
4374
Dan Gohman607e02b2010-04-09 22:07:05 +00004375/// HoistInsertPosition - Helper for AdjustInsertPositionForExpand. Climb up
4376/// the dominator tree far as we can go while still being dominated by the
4377/// input positions. This helps canonicalize the insert position, which
4378/// encourages sharing.
4379BasicBlock::iterator
4380LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
4381 const SmallVectorImpl<Instruction *> &Inputs)
4382 const {
4383 for (;;) {
4384 const Loop *IPLoop = LI.getLoopFor(IP->getParent());
4385 unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
4386
4387 BasicBlock *IDom;
Dan Gohman8ce95cc2010-05-20 20:00:25 +00004388 for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) {
Dan Gohman9b48b852010-05-20 22:46:54 +00004389 if (!Rung) return IP;
Dan Gohman8ce95cc2010-05-20 20:00:25 +00004390 Rung = Rung->getIDom();
4391 if (!Rung) return IP;
4392 IDom = Rung->getBlock();
Dan Gohman607e02b2010-04-09 22:07:05 +00004393
4394 // Don't climb into a loop though.
4395 const Loop *IDomLoop = LI.getLoopFor(IDom);
4396 unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
4397 if (IDomDepth <= IPLoopDepth &&
4398 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
4399 break;
4400 }
4401
4402 bool AllDominate = true;
Craig Topperf40110f2014-04-25 05:29:35 +00004403 Instruction *BetterPos = nullptr;
Dan Gohman607e02b2010-04-09 22:07:05 +00004404 Instruction *Tentative = IDom->getTerminator();
Craig Topper77b99412015-05-23 08:01:41 +00004405 for (Instruction *Inst : Inputs) {
Dan Gohman607e02b2010-04-09 22:07:05 +00004406 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
4407 AllDominate = false;
4408 break;
4409 }
4410 // Attempt to find an insert position in the middle of the block,
4411 // instead of at the end, so that it can be used for other expansions.
4412 if (IDom == Inst->getParent() &&
Rafael Espindoladd489312012-04-30 03:53:06 +00004413 (!BetterPos || !DT.dominates(Inst, BetterPos)))
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00004414 BetterPos = std::next(BasicBlock::iterator(Inst));
Dan Gohman607e02b2010-04-09 22:07:05 +00004415 }
4416 if (!AllDominate)
4417 break;
4418 if (BetterPos)
4419 IP = BetterPos;
4420 else
4421 IP = Tentative;
4422 }
4423
4424 return IP;
4425}
4426
4427/// AdjustInsertPositionForExpand - Determine an input position which will be
Dan Gohmand2df6432010-04-09 02:00:38 +00004428/// dominated by the operands and which will dominate the result.
4429BasicBlock::iterator
Andrew Trickc908b432012-01-20 07:41:13 +00004430LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator LowestIP,
Dan Gohman607e02b2010-04-09 22:07:05 +00004431 const LSRFixup &LF,
Andrew Trickc908b432012-01-20 07:41:13 +00004432 const LSRUse &LU,
4433 SCEVExpander &Rewriter) const {
Dan Gohmand2df6432010-04-09 02:00:38 +00004434 // Collect some instructions which must be dominated by the
Dan Gohmand006ab92010-04-07 22:27:08 +00004435 // expanding replacement. These must be dominated by any operands that
Dan Gohman45774ce2010-02-12 10:34:29 +00004436 // will be required in the expansion.
4437 SmallVector<Instruction *, 4> Inputs;
4438 if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
4439 Inputs.push_back(I);
4440 if (LU.Kind == LSRUse::ICmpZero)
4441 if (Instruction *I =
4442 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
4443 Inputs.push_back(I);
Dan Gohmand006ab92010-04-07 22:27:08 +00004444 if (LF.PostIncLoops.count(L)) {
4445 if (LF.isUseFullyOutsideLoop(L))
Dan Gohman52f55632010-03-02 01:59:21 +00004446 Inputs.push_back(L->getLoopLatch()->getTerminator());
4447 else
4448 Inputs.push_back(IVIncInsertPos);
4449 }
Dan Gohman45065392010-04-08 05:57:57 +00004450 // The expansion must also be dominated by the increment positions of any
4451 // loops it for which it is using post-inc mode.
Craig Topper77b99412015-05-23 08:01:41 +00004452 for (const Loop *PIL : LF.PostIncLoops) {
Dan Gohman45065392010-04-08 05:57:57 +00004453 if (PIL == L) continue;
4454
Dan Gohman607e02b2010-04-09 22:07:05 +00004455 // Be dominated by the loop exit.
Dan Gohman45065392010-04-08 05:57:57 +00004456 SmallVector<BasicBlock *, 4> ExitingBlocks;
4457 PIL->getExitingBlocks(ExitingBlocks);
4458 if (!ExitingBlocks.empty()) {
4459 BasicBlock *BB = ExitingBlocks[0];
4460 for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
4461 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
4462 Inputs.push_back(BB->getTerminator());
4463 }
4464 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004465
Andrew Trickc908b432012-01-20 07:41:13 +00004466 assert(!isa<PHINode>(LowestIP) && !isa<LandingPadInst>(LowestIP)
4467 && !isa<DbgInfoIntrinsic>(LowestIP) &&
4468 "Insertion point must be a normal instruction");
4469
Dan Gohman45774ce2010-02-12 10:34:29 +00004470 // Then, climb up the immediate dominator tree as far as we can go while
4471 // still being dominated by the input positions.
Andrew Trickc908b432012-01-20 07:41:13 +00004472 BasicBlock::iterator IP = HoistInsertPosition(LowestIP, Inputs);
Dan Gohmand2df6432010-04-09 02:00:38 +00004473
4474 // Don't insert instructions before PHI nodes.
Dan Gohman45774ce2010-02-12 10:34:29 +00004475 while (isa<PHINode>(IP)) ++IP;
Dan Gohmand2df6432010-04-09 02:00:38 +00004476
Bill Wendling86c5cbe2011-08-24 21:06:46 +00004477 // Ignore landingpad instructions.
4478 while (isa<LandingPadInst>(IP)) ++IP;
4479
Dan Gohmand2df6432010-04-09 02:00:38 +00004480 // Ignore debug intrinsics.
Dan Gohmand42e09d2010-03-26 00:33:27 +00004481 while (isa<DbgInfoIntrinsic>(IP)) ++IP;
Dan Gohman45774ce2010-02-12 10:34:29 +00004482
Andrew Trickc908b432012-01-20 07:41:13 +00004483 // Set IP below instructions recently inserted by SCEVExpander. This keeps the
4484 // IP consistent across expansions and allows the previously inserted
4485 // instructions to be reused by subsequent expansion.
4486 while (Rewriter.isInsertedInstruction(IP) && IP != LowestIP) ++IP;
4487
Dan Gohmand2df6432010-04-09 02:00:38 +00004488 return IP;
4489}
4490
Dan Gohmana4ca28a2010-05-20 20:52:00 +00004491/// Expand - Emit instructions for the leading candidate expression for this
4492/// LSRUse (this is called "expanding").
Dan Gohmand2df6432010-04-09 02:00:38 +00004493Value *LSRInstance::Expand(const LSRFixup &LF,
4494 const Formula &F,
4495 BasicBlock::iterator IP,
4496 SCEVExpander &Rewriter,
4497 SmallVectorImpl<WeakVH> &DeadInsts) const {
4498 const LSRUse &LU = Uses[LF.LUIdx];
Andrew Trick57243da2013-10-25 21:35:56 +00004499 if (LU.RigidFormula)
4500 return LF.OperandValToReplace;
Dan Gohmand2df6432010-04-09 02:00:38 +00004501
4502 // Determine an input position which will be dominated by the operands and
4503 // which will dominate the result.
Andrew Trickc908b432012-01-20 07:41:13 +00004504 IP = AdjustInsertPositionForExpand(IP, LF, LU, Rewriter);
Dan Gohmand2df6432010-04-09 02:00:38 +00004505
Dan Gohman45774ce2010-02-12 10:34:29 +00004506 // Inform the Rewriter if we have a post-increment use, so that it can
4507 // perform an advantageous expansion.
Dan Gohmand006ab92010-04-07 22:27:08 +00004508 Rewriter.setPostInc(LF.PostIncLoops);
Dan Gohman45774ce2010-02-12 10:34:29 +00004509
4510 // This is the type that the user actually needs.
Chris Lattner229907c2011-07-18 04:54:35 +00004511 Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00004512 // This will be the type that we'll initially expand to.
Chris Lattner229907c2011-07-18 04:54:35 +00004513 Type *Ty = F.getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00004514 if (!Ty)
4515 // No type known; just expand directly to the ultimate type.
4516 Ty = OpTy;
4517 else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
4518 // Expand directly to the ultimate type if it's the right size.
4519 Ty = OpTy;
4520 // This is the type to do integer arithmetic in.
Chris Lattner229907c2011-07-18 04:54:35 +00004521 Type *IntTy = SE.getEffectiveSCEVType(Ty);
Dan Gohman45774ce2010-02-12 10:34:29 +00004522
4523 // Build up a list of operands to add together to form the full base.
4524 SmallVector<const SCEV *, 8> Ops;
4525
4526 // Expand the BaseRegs portion.
Craig Topper77b99412015-05-23 08:01:41 +00004527 for (const SCEV *Reg : F.BaseRegs) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004528 assert(!Reg->isZero() && "Zero allocated in a base register!");
4529
Dan Gohmand006ab92010-04-07 22:27:08 +00004530 // If we're expanding for a post-inc user, make the post-inc adjustment.
4531 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
4532 Reg = TransformForPostIncUse(Denormalize, Reg,
4533 LF.UserInst, LF.OperandValToReplace,
4534 Loops, SE, DT);
Dan Gohman45774ce2010-02-12 10:34:29 +00004535
Craig Topperf40110f2014-04-25 05:29:35 +00004536 Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr, IP)));
Dan Gohman45774ce2010-02-12 10:34:29 +00004537 }
4538
4539 // Expand the ScaledReg portion.
Craig Topperf40110f2014-04-25 05:29:35 +00004540 Value *ICmpScaledV = nullptr;
Chandler Carruth6e479322013-01-07 15:04:40 +00004541 if (F.Scale != 0) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004542 const SCEV *ScaledS = F.ScaledReg;
4543
Dan Gohmand006ab92010-04-07 22:27:08 +00004544 // If we're expanding for a post-inc user, make the post-inc adjustment.
4545 PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
4546 ScaledS = TransformForPostIncUse(Denormalize, ScaledS,
4547 LF.UserInst, LF.OperandValToReplace,
4548 Loops, SE, DT);
Dan Gohman45774ce2010-02-12 10:34:29 +00004549
4550 if (LU.Kind == LSRUse::ICmpZero) {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004551 // Expand ScaleReg as if it was part of the base regs.
4552 if (F.Scale == 1)
4553 Ops.push_back(
4554 SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, IP)));
4555 else {
4556 // An interesting way of "folding" with an icmp is to use a negated
4557 // scale, which we'll implement by inserting it into the other operand
4558 // of the icmp.
4559 assert(F.Scale == -1 &&
4560 "The only scale supported by ICmpZero uses is -1!");
4561 ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr, IP);
4562 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004563 } else {
4564 // Otherwise just expand the scaled register and an explicit scale,
4565 // which is expected to be matched as part of the address.
Andrew Trick8370c7c2012-06-15 20:07:29 +00004566
4567 // Flush the operand list to suppress SCEVExpander hoisting address modes.
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004568 // Unless the addressing mode will not be folded.
4569 if (!Ops.empty() && LU.Kind == LSRUse::Address &&
4570 isAMCompletelyFolded(TTI, LU, F)) {
Andrew Trick8370c7c2012-06-15 20:07:29 +00004571 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
4572 Ops.clear();
4573 Ops.push_back(SE.getUnknown(FullV));
4574 }
Craig Topperf40110f2014-04-25 05:29:35 +00004575 ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr, IP));
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004576 if (F.Scale != 1)
4577 ScaledS =
4578 SE.getMulExpr(ScaledS, SE.getConstant(ScaledS->getType(), F.Scale));
Dan Gohman45774ce2010-02-12 10:34:29 +00004579 Ops.push_back(ScaledS);
4580 }
4581 }
4582
Dan Gohman29707de2010-03-03 05:29:13 +00004583 // Expand the GV portion.
Chandler Carruth6e479322013-01-07 15:04:40 +00004584 if (F.BaseGV) {
Dan Gohman29707de2010-03-03 05:29:13 +00004585 // Flush the operand list to suppress SCEVExpander hoisting.
Andrew Trick8370c7c2012-06-15 20:07:29 +00004586 if (!Ops.empty()) {
4587 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
4588 Ops.clear();
4589 Ops.push_back(SE.getUnknown(FullV));
4590 }
Chandler Carruth6e479322013-01-07 15:04:40 +00004591 Ops.push_back(SE.getUnknown(F.BaseGV));
Andrew Trick8370c7c2012-06-15 20:07:29 +00004592 }
4593
4594 // Flush the operand list to suppress SCEVExpander hoisting of both folded and
4595 // unfolded offsets. LSR assumes they both live next to their uses.
4596 if (!Ops.empty()) {
Dan Gohman29707de2010-03-03 05:29:13 +00004597 Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty, IP);
4598 Ops.clear();
4599 Ops.push_back(SE.getUnknown(FullV));
4600 }
4601
4602 // Expand the immediate portion.
Chandler Carruth6e479322013-01-07 15:04:40 +00004603 int64_t Offset = (uint64_t)F.BaseOffset + LF.Offset;
Dan Gohman45774ce2010-02-12 10:34:29 +00004604 if (Offset != 0) {
4605 if (LU.Kind == LSRUse::ICmpZero) {
4606 // The other interesting way of "folding" with an ICmpZero is to use a
4607 // negated immediate.
4608 if (!ICmpScaledV)
Eli Friedmanb46345d2011-10-13 23:48:33 +00004609 ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset);
Dan Gohman45774ce2010-02-12 10:34:29 +00004610 else {
4611 Ops.push_back(SE.getUnknown(ICmpScaledV));
4612 ICmpScaledV = ConstantInt::get(IntTy, Offset);
4613 }
4614 } else {
4615 // Just add the immediate values. These again are expected to be matched
4616 // as part of the address.
Dan Gohman29707de2010-03-03 05:29:13 +00004617 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
Dan Gohman45774ce2010-02-12 10:34:29 +00004618 }
4619 }
4620
Dan Gohman6136e942011-05-03 00:46:49 +00004621 // Expand the unfolded offset portion.
4622 int64_t UnfoldedOffset = F.UnfoldedOffset;
4623 if (UnfoldedOffset != 0) {
4624 // Just add the immediate values.
4625 Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy,
4626 UnfoldedOffset)));
4627 }
4628
Dan Gohman45774ce2010-02-12 10:34:29 +00004629 // Emit instructions summing all the operands.
4630 const SCEV *FullS = Ops.empty() ?
Dan Gohman1d2ded72010-05-03 22:09:21 +00004631 SE.getConstant(IntTy, 0) :
Dan Gohman45774ce2010-02-12 10:34:29 +00004632 SE.getAddExpr(Ops);
4633 Value *FullV = Rewriter.expandCodeFor(FullS, Ty, IP);
4634
4635 // We're done expanding now, so reset the rewriter.
Dan Gohmand006ab92010-04-07 22:27:08 +00004636 Rewriter.clearPostInc();
Dan Gohman45774ce2010-02-12 10:34:29 +00004637
4638 // An ICmpZero Formula represents an ICmp which we're handling as a
4639 // comparison against zero. Now that we've expanded an expression for that
4640 // form, update the ICmp's other operand.
4641 if (LU.Kind == LSRUse::ICmpZero) {
4642 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
4643 DeadInsts.push_back(CI->getOperand(1));
Chandler Carruth6e479322013-01-07 15:04:40 +00004644 assert(!F.BaseGV && "ICmp does not support folding a global value and "
Dan Gohman45774ce2010-02-12 10:34:29 +00004645 "a scale at the same time!");
Chandler Carruth6e479322013-01-07 15:04:40 +00004646 if (F.Scale == -1) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004647 if (ICmpScaledV->getType() != OpTy) {
4648 Instruction *Cast =
4649 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
4650 OpTy, false),
4651 ICmpScaledV, OpTy, "tmp", CI);
4652 ICmpScaledV = Cast;
4653 }
4654 CI->setOperand(1, ICmpScaledV);
4655 } else {
Quentin Colombetc88baa5c2014-05-20 19:25:04 +00004656 // A scale of 1 means that the scale has been expanded as part of the
4657 // base regs.
4658 assert((F.Scale == 0 || F.Scale == 1) &&
Dan Gohman45774ce2010-02-12 10:34:29 +00004659 "ICmp does not support folding a global value and "
4660 "a scale at the same time!");
4661 Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
4662 -(uint64_t)Offset);
4663 if (C->getType() != OpTy)
4664 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4665 OpTy, false),
4666 C, OpTy);
4667
4668 CI->setOperand(1, C);
4669 }
4670 }
4671
4672 return FullV;
4673}
4674
Dan Gohman6deab962010-02-16 20:25:07 +00004675/// RewriteForPHI - Helper for Rewrite. PHI nodes are special because the use
4676/// of their operands effectively happens in their predecessor blocks, so the
4677/// expression may need to be expanded in multiple places.
4678void LSRInstance::RewriteForPHI(PHINode *PN,
4679 const LSRFixup &LF,
4680 const Formula &F,
Dan Gohman6deab962010-02-16 20:25:07 +00004681 SCEVExpander &Rewriter,
4682 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman6deab962010-02-16 20:25:07 +00004683 Pass *P) const {
4684 DenseMap<BasicBlock *, Value *> Inserted;
4685 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4686 if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
4687 BasicBlock *BB = PN->getIncomingBlock(i);
4688
4689 // If this is a critical edge, split the edge so that we do not insert
4690 // the code on all predecessor/successor paths. We do this unless this
4691 // is the canonical backedge for this loop, which complicates post-inc
4692 // users.
4693 if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
Dan Gohmande7f6992011-02-08 00:55:13 +00004694 !isa<IndirectBrInst>(BB->getTerminator())) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00004695 BasicBlock *Parent = PN->getParent();
4696 Loop *PNLoop = LI.getLoopFor(Parent);
4697 if (!PNLoop || Parent != PNLoop->getHeader()) {
Dan Gohmande7f6992011-02-08 00:55:13 +00004698 // Split the critical edge.
Craig Topperf40110f2014-04-25 05:29:35 +00004699 BasicBlock *NewBB = nullptr;
Bill Wendling3fb137f2011-08-25 05:55:40 +00004700 if (!Parent->isLandingPad()) {
Chandler Carruth37df2cf2015-01-19 12:09:11 +00004701 NewBB = SplitCriticalEdge(BB, Parent,
4702 CriticalEdgeSplittingOptions(&DT, &LI)
4703 .setMergeIdenticalEdges()
4704 .setDontDeleteUselessPHIs());
Bill Wendling3fb137f2011-08-25 05:55:40 +00004705 } else {
4706 SmallVector<BasicBlock*, 2> NewBBs;
Chandler Carruth0eae1122015-01-19 03:03:39 +00004707 SplitLandingPadPredecessors(Parent, BB, "", "", NewBBs,
4708 /*AliasAnalysis*/ nullptr, &DT, &LI);
Bill Wendling3fb137f2011-08-25 05:55:40 +00004709 NewBB = NewBBs[0];
4710 }
Andrew Trick402edbb2012-09-18 17:51:33 +00004711 // If NewBB==NULL, then SplitCriticalEdge refused to split because all
4712 // phi predecessors are identical. The simple thing to do is skip
4713 // splitting in this case rather than complicate the API.
4714 if (NewBB) {
4715 // If PN is outside of the loop and BB is in the loop, we want to
4716 // move the block to be immediately before the PHI block, not
4717 // immediately after BB.
4718 if (L->contains(BB) && !L->contains(PN))
4719 NewBB->moveBefore(PN->getParent());
Dan Gohman6deab962010-02-16 20:25:07 +00004720
Andrew Trick402edbb2012-09-18 17:51:33 +00004721 // Splitting the edge can reduce the number of PHI entries we have.
4722 e = PN->getNumIncomingValues();
4723 BB = NewBB;
4724 i = PN->getBasicBlockIndex(BB);
4725 }
Dan Gohmande7f6992011-02-08 00:55:13 +00004726 }
Dan Gohman6deab962010-02-16 20:25:07 +00004727 }
4728
4729 std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
Craig Topperf40110f2014-04-25 05:29:35 +00004730 Inserted.insert(std::make_pair(BB, static_cast<Value *>(nullptr)));
Dan Gohman6deab962010-02-16 20:25:07 +00004731 if (!Pair.second)
4732 PN->setIncomingValue(i, Pair.first->second);
4733 else {
Dan Gohman8c16b382010-02-22 04:11:59 +00004734 Value *FullV = Expand(LF, F, BB->getTerminator(), Rewriter, DeadInsts);
Dan Gohman6deab962010-02-16 20:25:07 +00004735
4736 // If this is reuse-by-noop-cast, insert the noop cast.
Chris Lattner229907c2011-07-18 04:54:35 +00004737 Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman6deab962010-02-16 20:25:07 +00004738 if (FullV->getType() != OpTy)
4739 FullV =
4740 CastInst::Create(CastInst::getCastOpcode(FullV, false,
4741 OpTy, false),
4742 FullV, LF.OperandValToReplace->getType(),
4743 "tmp", BB->getTerminator());
4744
4745 PN->setIncomingValue(i, FullV);
4746 Pair.first->second = FullV;
4747 }
4748 }
4749}
4750
Dan Gohman45774ce2010-02-12 10:34:29 +00004751/// Rewrite - Emit instructions for the leading candidate expression for this
4752/// LSRUse (this is called "expanding"), and update the UserInst to reference
4753/// the newly expanded value.
4754void LSRInstance::Rewrite(const LSRFixup &LF,
4755 const Formula &F,
Dan Gohman45774ce2010-02-12 10:34:29 +00004756 SCEVExpander &Rewriter,
4757 SmallVectorImpl<WeakVH> &DeadInsts,
Dan Gohman45774ce2010-02-12 10:34:29 +00004758 Pass *P) const {
Dan Gohman45774ce2010-02-12 10:34:29 +00004759 // First, find an insertion point that dominates UserInst. For PHI nodes,
4760 // find the nearest block which dominates all the relevant uses.
4761 if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
Dan Gohman8c16b382010-02-22 04:11:59 +00004762 RewriteForPHI(PN, LF, F, Rewriter, DeadInsts, P);
Dan Gohman45774ce2010-02-12 10:34:29 +00004763 } else {
Dan Gohman8c16b382010-02-22 04:11:59 +00004764 Value *FullV = Expand(LF, F, LF.UserInst, Rewriter, DeadInsts);
Dan Gohman45774ce2010-02-12 10:34:29 +00004765
4766 // If this is reuse-by-noop-cast, insert the noop cast.
Chris Lattner229907c2011-07-18 04:54:35 +00004767 Type *OpTy = LF.OperandValToReplace->getType();
Dan Gohman45774ce2010-02-12 10:34:29 +00004768 if (FullV->getType() != OpTy) {
4769 Instruction *Cast =
4770 CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
4771 FullV, OpTy, "tmp", LF.UserInst);
4772 FullV = Cast;
4773 }
4774
4775 // Update the user. ICmpZero is handled specially here (for now) because
4776 // Expand may have updated one of the operands of the icmp already, and
4777 // its new value may happen to be equal to LF.OperandValToReplace, in
4778 // which case doing replaceUsesOfWith leads to replacing both operands
4779 // with the same value. TODO: Reorganize this.
4780 if (Uses[LF.LUIdx].Kind == LSRUse::ICmpZero)
4781 LF.UserInst->setOperand(0, FullV);
4782 else
4783 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
4784 }
4785
4786 DeadInsts.push_back(LF.OperandValToReplace);
4787}
4788
Dan Gohmana4ca28a2010-05-20 20:52:00 +00004789/// ImplementSolution - Rewrite all the fixup locations with new values,
4790/// following the chosen solution.
Dan Gohman45774ce2010-02-12 10:34:29 +00004791void
4792LSRInstance::ImplementSolution(const SmallVectorImpl<const Formula *> &Solution,
4793 Pass *P) {
4794 // Keep track of instructions we may have made dead, so that
4795 // we can remove them after we are done working.
4796 SmallVector<WeakVH, 16> DeadInsts;
4797
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004798 SCEVExpander Rewriter(SE, L->getHeader()->getModule()->getDataLayout(),
4799 "lsr");
Andrew Trick4dc3eff2012-01-09 18:58:16 +00004800#ifndef NDEBUG
4801 Rewriter.setDebugType(DEBUG_TYPE);
4802#endif
Dan Gohman45774ce2010-02-12 10:34:29 +00004803 Rewriter.disableCanonicalMode();
Andrew Trick7fb669a2011-10-07 23:46:21 +00004804 Rewriter.enableLSRMode();
Dan Gohman45774ce2010-02-12 10:34:29 +00004805 Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
4806
Andrew Trickd5d2db92012-01-10 01:45:08 +00004807 // Mark phi nodes that terminate chains so the expander tries to reuse them.
Craig Topper77b99412015-05-23 08:01:41 +00004808 for (const IVChain &Chain : IVChainVec) {
4809 if (PHINode *PN = dyn_cast<PHINode>(Chain.tailUserInst()))
Andrew Trickd5d2db92012-01-10 01:45:08 +00004810 Rewriter.setChainedPhi(PN);
4811 }
4812
Dan Gohman45774ce2010-02-12 10:34:29 +00004813 // Expand the new value definitions and update the users.
Craig Topper77b99412015-05-23 08:01:41 +00004814 for (const LSRFixup &Fixup : Fixups) {
Dan Gohman927bcaa2010-05-20 20:33:18 +00004815 Rewrite(Fixup, *Solution[Fixup.LUIdx], Rewriter, DeadInsts, P);
Dan Gohman45774ce2010-02-12 10:34:29 +00004816
4817 Changed = true;
4818 }
4819
Craig Topper77b99412015-05-23 08:01:41 +00004820 for (const IVChain &Chain : IVChainVec) {
4821 GenerateIVChain(Chain, Rewriter, DeadInsts);
Andrew Trick248d4102012-01-09 21:18:52 +00004822 Changed = true;
4823 }
Dan Gohman45774ce2010-02-12 10:34:29 +00004824 // Clean up after ourselves. This must be done before deleting any
4825 // instructions.
4826 Rewriter.clear();
4827
4828 Changed |= DeleteTriviallyDeadInstructions(DeadInsts);
4829}
4830
Chandler Carruth26c59fa2013-01-07 14:41:08 +00004831LSRInstance::LSRInstance(Loop *L, Pass *P)
4832 : IU(P->getAnalysis<IVUsers>()), SE(P->getAnalysis<ScalarEvolution>()),
Chandler Carruth73523022014-01-13 13:07:17 +00004833 DT(P->getAnalysis<DominatorTreeWrapperPass>().getDomTree()),
Chandler Carruth4f8f3072015-01-17 14:16:18 +00004834 LI(P->getAnalysis<LoopInfoWrapperPass>().getLoopInfo()),
Chandler Carruthfdb9c572015-02-01 12:01:35 +00004835 TTI(P->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
4836 *L->getHeader()->getParent())),
4837 L(L), Changed(false), IVIncInsertPos(nullptr) {
Dan Gohmana83ac2d2009-11-05 21:11:53 +00004838 // If LoopSimplify form is not available, stay out of trouble.
Andrew Trick732ad802012-01-07 03:16:50 +00004839 if (!L->isLoopSimplifyForm())
4840 return;
Dan Gohmana83ac2d2009-11-05 21:11:53 +00004841
Andrew Trick070e5402012-03-16 03:16:56 +00004842 // If there's no interesting work to be done, bail early.
4843 if (IU.empty()) return;
4844
Andrew Trick19f80c12012-04-18 04:00:10 +00004845 // If there's too much analysis to be done, bail early. We won't be able to
4846 // model the problem anyway.
4847 unsigned NumUsers = 0;
Craig Topper77b99412015-05-23 08:01:41 +00004848 for (const IVStrideUse &U : IU) {
Andrew Trick19f80c12012-04-18 04:00:10 +00004849 if (++NumUsers > MaxIVUsers) {
Craig Topper37d0d862015-05-23 08:20:33 +00004850 (void)U;
Craig Topper77b99412015-05-23 08:01:41 +00004851 DEBUG(dbgs() << "LSR skipping loop, too many IV Users in " << U << "\n");
Andrew Trick19f80c12012-04-18 04:00:10 +00004852 return;
4853 }
4854 }
4855
Andrew Trick070e5402012-03-16 03:16:56 +00004856#ifndef NDEBUG
Andrew Trick12728f02012-01-17 06:45:52 +00004857 // All dominating loops must have preheaders, or SCEVExpander may not be able
4858 // to materialize an AddRecExpr whose Start is an outer AddRecExpr.
4859 //
Andrew Trick070e5402012-03-16 03:16:56 +00004860 // IVUsers analysis should only create users that are dominated by simple loop
4861 // headers. Since this loop should dominate all of its users, its user list
4862 // should be empty if this loop itself is not within a simple loop nest.
Andrew Trick12728f02012-01-17 06:45:52 +00004863 for (DomTreeNode *Rung = DT.getNode(L->getLoopPreheader());
4864 Rung; Rung = Rung->getIDom()) {
4865 BasicBlock *BB = Rung->getBlock();
4866 const Loop *DomLoop = LI.getLoopFor(BB);
4867 if (DomLoop && DomLoop->getHeader() == BB) {
Andrew Trick070e5402012-03-16 03:16:56 +00004868 assert(DomLoop->getLoopPreheader() && "LSR needs a simplified loop nest");
Andrew Trick12728f02012-01-17 06:45:52 +00004869 }
Andrew Trick732ad802012-01-07 03:16:50 +00004870 }
Andrew Trick070e5402012-03-16 03:16:56 +00004871#endif // DEBUG
Dan Gohman85875f72009-03-09 20:34:59 +00004872
Dan Gohman45774ce2010-02-12 10:34:29 +00004873 DEBUG(dbgs() << "\nLSR on loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00004874 L->getHeader()->printAsOperand(dbgs(), /*PrintType=*/false);
Dan Gohman45774ce2010-02-12 10:34:29 +00004875 dbgs() << ":\n");
Dan Gohmane201f8f2009-03-09 20:46:50 +00004876
Dan Gohman927bcaa2010-05-20 20:33:18 +00004877 // First, perform some low-level loop optimizations.
Dan Gohman45774ce2010-02-12 10:34:29 +00004878 OptimizeShadowIV();
Dan Gohman4c4043c2010-05-20 20:05:31 +00004879 OptimizeLoopTermCond();
Evan Cheng78a4eb82009-05-11 22:33:01 +00004880
Andrew Trick8acb4342011-07-21 00:40:04 +00004881 // If loop preparation eliminates all interesting IV users, bail.
4882 if (IU.empty()) return;
4883
Andrew Trick168dfff2011-09-29 01:53:08 +00004884 // Skip nested loops until we can model them better with formulae.
Andrew Trickd97b83e2012-03-22 22:42:45 +00004885 if (!L->empty()) {
Andrew Trickbc6de902011-09-29 01:33:38 +00004886 DEBUG(dbgs() << "LSR skipping outer loop " << *L << "\n");
Andrew Trick168dfff2011-09-29 01:53:08 +00004887 return;
Andrew Trickbc6de902011-09-29 01:33:38 +00004888 }
4889
Dan Gohman927bcaa2010-05-20 20:33:18 +00004890 // Start collecting data and preparing for the solver.
Andrew Trick29fe5f02012-01-09 19:50:34 +00004891 CollectChains();
Dan Gohman45774ce2010-02-12 10:34:29 +00004892 CollectInterestingTypesAndFactors();
4893 CollectFixupsAndInitialFormulae();
4894 CollectLoopInvariantFixupsAndFormulae();
Chris Lattner9bfa6f82005-08-08 05:28:22 +00004895
Andrew Trick248d4102012-01-09 21:18:52 +00004896 assert(!Uses.empty() && "IVUsers reported at least one use");
Dan Gohman45774ce2010-02-12 10:34:29 +00004897 DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
4898 print_uses(dbgs()));
Misha Brukmanb1c93172005-04-21 23:48:37 +00004899
Dan Gohman45774ce2010-02-12 10:34:29 +00004900 // Now use the reuse data to generate a bunch of interesting ways
4901 // to formulate the values needed for the uses.
4902 GenerateAllReuseFormulae();
Evan Cheng3df447d2006-03-16 21:53:05 +00004903
Dan Gohman45774ce2010-02-12 10:34:29 +00004904 FilterOutUndesirableDedicatedRegisters();
4905 NarrowSearchSpaceUsingHeuristics();
Dan Gohman92c36962009-12-18 00:06:20 +00004906
Dan Gohman45774ce2010-02-12 10:34:29 +00004907 SmallVector<const Formula *, 8> Solution;
4908 Solve(Solution);
Dan Gohman92c36962009-12-18 00:06:20 +00004909
Dan Gohman45774ce2010-02-12 10:34:29 +00004910 // Release memory that is no longer needed.
4911 Factors.clear();
4912 Types.clear();
4913 RegUses.clear();
4914
Andrew Trick58124392011-09-27 00:44:14 +00004915 if (Solution.empty())
4916 return;
4917
Dan Gohman45774ce2010-02-12 10:34:29 +00004918#ifndef NDEBUG
4919 // Formulae should be legal.
Craig Topper77b99412015-05-23 08:01:41 +00004920 for (const LSRUse &LU : Uses) {
4921 for (const Formula &F : LU.Formulae)
Chandler Carruth26c59fa2013-01-07 14:41:08 +00004922 assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
Craig Topper77b99412015-05-23 08:01:41 +00004923 F) && "Illegal formula generated!");
Dan Gohman45774ce2010-02-12 10:34:29 +00004924 };
4925#endif
4926
4927 // Now that we've decided what we want, make it so.
4928 ImplementSolution(Solution, P);
4929}
4930
4931void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
4932 if (Factors.empty() && Types.empty()) return;
4933
4934 OS << "LSR has identified the following interesting factors and types: ";
4935 bool First = true;
4936
Craig Topper77b99412015-05-23 08:01:41 +00004937 for (int64_t I : Factors) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004938 if (!First) OS << ", ";
4939 First = false;
Craig Topper77b99412015-05-23 08:01:41 +00004940 OS << '*' << I;
Evan Cheng87fe40b2009-11-10 21:14:05 +00004941 }
Dale Johannesen02cb2bf2009-05-11 17:15:42 +00004942
Craig Topper77b99412015-05-23 08:01:41 +00004943 for (Type *I : Types) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004944 if (!First) OS << ", ";
4945 First = false;
Craig Topper77b99412015-05-23 08:01:41 +00004946 OS << '(' << *I << ')';
Dan Gohman45774ce2010-02-12 10:34:29 +00004947 }
4948 OS << '\n';
4949}
4950
4951void LSRInstance::print_fixups(raw_ostream &OS) const {
4952 OS << "LSR is examining the following fixup sites:\n";
Craig Topper77b99412015-05-23 08:01:41 +00004953 for (const LSRFixup &LF : Fixups) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004954 dbgs() << " ";
Craig Topper77b99412015-05-23 08:01:41 +00004955 LF.print(OS);
Dan Gohman45774ce2010-02-12 10:34:29 +00004956 OS << '\n';
4957 }
4958}
4959
4960void LSRInstance::print_uses(raw_ostream &OS) const {
4961 OS << "LSR is examining the following uses:\n";
Craig Topper77b99412015-05-23 08:01:41 +00004962 for (const LSRUse &LU : Uses) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004963 dbgs() << " ";
4964 LU.print(OS);
4965 OS << '\n';
Craig Topper77b99412015-05-23 08:01:41 +00004966 for (const Formula &F : LU.Formulae) {
Dan Gohman45774ce2010-02-12 10:34:29 +00004967 OS << " ";
Craig Topper77b99412015-05-23 08:01:41 +00004968 F.print(OS);
Dan Gohman45774ce2010-02-12 10:34:29 +00004969 OS << '\n';
4970 }
4971 }
4972}
4973
4974void LSRInstance::print(raw_ostream &OS) const {
4975 print_factors_and_types(OS);
4976 print_fixups(OS);
4977 print_uses(OS);
4978}
4979
Manman Ren49d684e2012-09-12 05:06:18 +00004980#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman45774ce2010-02-12 10:34:29 +00004981void LSRInstance::dump() const {
4982 print(errs()); errs() << '\n';
4983}
Manman Renc3366cc2012-09-06 19:55:56 +00004984#endif
Dan Gohman45774ce2010-02-12 10:34:29 +00004985
4986namespace {
4987
4988class LoopStrengthReduce : public LoopPass {
Dan Gohman45774ce2010-02-12 10:34:29 +00004989public:
4990 static char ID; // Pass ID, replacement for typeid
Chandler Carruth26c59fa2013-01-07 14:41:08 +00004991 LoopStrengthReduce();
Dan Gohman45774ce2010-02-12 10:34:29 +00004992
4993private:
Craig Topper3e4c6972014-03-05 09:10:37 +00004994 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
4995 void getAnalysisUsage(AnalysisUsage &AU) const override;
Dan Gohman45774ce2010-02-12 10:34:29 +00004996};
4997
4998}
4999
5000char LoopStrengthReduce::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +00005001INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce",
Owen Andersondf7a4f22010-10-07 22:25:06 +00005002 "Loop Strength Reduction", false, false)
Chandler Carruth705b1852015-01-31 03:43:40 +00005003INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
Chandler Carruth73523022014-01-13 13:07:17 +00005004INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +00005005INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
5006INITIALIZE_PASS_DEPENDENCY(IVUsers)
Chandler Carruth4f8f3072015-01-17 14:16:18 +00005007INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Owen Andersona4fefc12010-10-19 20:08:44 +00005008INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Owen Anderson8ac477f2010-10-12 19:48:12 +00005009INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce",
5010 "Loop Strength Reduction", false, false)
5011
Nadav Rotem4dc976f2012-10-19 21:28:43 +00005012
Chandler Carruth26c59fa2013-01-07 14:41:08 +00005013Pass *llvm::createLoopStrengthReducePass() {
5014 return new LoopStrengthReduce();
Dan Gohman45774ce2010-02-12 10:34:29 +00005015}
5016
Chandler Carruth26c59fa2013-01-07 14:41:08 +00005017LoopStrengthReduce::LoopStrengthReduce() : LoopPass(ID) {
5018 initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry());
5019}
Dan Gohman45774ce2010-02-12 10:34:29 +00005020
5021void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
5022 // We split critical edges, so we change the CFG. However, we do update
5023 // many analyses if they are around.
Eric Christopherda6bd452011-02-10 01:48:24 +00005024 AU.addPreservedID(LoopSimplifyID);
Dan Gohman45774ce2010-02-12 10:34:29 +00005025
Chandler Carruth4f8f3072015-01-17 14:16:18 +00005026 AU.addRequired<LoopInfoWrapperPass>();
5027 AU.addPreserved<LoopInfoWrapperPass>();
Eric Christopherda6bd452011-02-10 01:48:24 +00005028 AU.addRequiredID(LoopSimplifyID);
Chandler Carruth73523022014-01-13 13:07:17 +00005029 AU.addRequired<DominatorTreeWrapperPass>();
5030 AU.addPreserved<DominatorTreeWrapperPass>();
Dan Gohman45774ce2010-02-12 10:34:29 +00005031 AU.addRequired<ScalarEvolution>();
5032 AU.addPreserved<ScalarEvolution>();
Cameron Zwarich97dae4d2011-02-10 23:53:14 +00005033 // Requiring LoopSimplify a second time here prevents IVUsers from running
5034 // twice, since LoopSimplify was invalidated by running ScalarEvolution.
5035 AU.addRequiredID(LoopSimplifyID);
Dan Gohman45774ce2010-02-12 10:34:29 +00005036 AU.addRequired<IVUsers>();
5037 AU.addPreserved<IVUsers>();
Chandler Carruth705b1852015-01-31 03:43:40 +00005038 AU.addRequired<TargetTransformInfoWrapperPass>();
Dan Gohman45774ce2010-02-12 10:34:29 +00005039}
5040
5041bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00005042 if (skipOptnoneFunction(L))
5043 return false;
5044
Dan Gohman45774ce2010-02-12 10:34:29 +00005045 bool Changed = false;
5046
5047 // Run the main LSR transformation.
Chandler Carruth26c59fa2013-01-07 14:41:08 +00005048 Changed |= LSRInstance(L, this).getChanged();
Dan Gohman45774ce2010-02-12 10:34:29 +00005049
Andrew Trick2ec61a82012-01-07 01:36:44 +00005050 // Remove any extra phis created by processing inner loops.
Dan Gohmanb5358002010-01-05 16:31:45 +00005051 Changed |= DeleteDeadPHIs(L->getHeader());
Andrew Trickf950ce82013-01-06 05:59:39 +00005052 if (EnablePhiElim && L->isLoopSimplifyForm()) {
Andrew Trick2ec61a82012-01-07 01:36:44 +00005053 SmallVector<WeakVH, 16> DeadInsts;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00005054 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
5055 SCEVExpander Rewriter(getAnalysis<ScalarEvolution>(), DL, "lsr");
Andrew Trick2ec61a82012-01-07 01:36:44 +00005056#ifndef NDEBUG
5057 Rewriter.setDebugType(DEBUG_TYPE);
5058#endif
Chandler Carruth73523022014-01-13 13:07:17 +00005059 unsigned numFolded = Rewriter.replaceCongruentIVs(
5060 L, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(), DeadInsts,
Chandler Carruthfdb9c572015-02-01 12:01:35 +00005061 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
5062 *L->getHeader()->getParent()));
Andrew Trick2ec61a82012-01-07 01:36:44 +00005063 if (numFolded) {
5064 Changed = true;
5065 DeleteTriviallyDeadInstructions(DeadInsts);
5066 DeleteDeadPHIs(L->getHeader());
5067 }
5068 }
Evan Cheng03001cb2008-07-07 19:51:32 +00005069 return Changed;
Nate Begemanb18121e2004-10-18 21:08:22 +00005070}