blob: 98ab6f484ea15666e169b6f4563aaf32cd13dc08 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
17// can handle. These classes are reference counted, managed by the SCEVHandle
18// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
31//
32// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
36// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
62#define DEBUG_TYPE "scalar-evolution"
63#include "llvm/Analysis/ScalarEvolutionExpressions.h"
64#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
66#include "llvm/GlobalVariable.h"
67#include "llvm/Instructions.h"
68#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng98c073b2009-02-17 00:13:06 +000069#include "llvm/Analysis/Dominators.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070#include "llvm/Analysis/LoopInfo.h"
71#include "llvm/Assembly/Writer.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000072#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000073#include "llvm/Support/CommandLine.h"
74#include "llvm/Support/Compiler.h"
75#include "llvm/Support/ConstantRange.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000076#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000077#include "llvm/Support/InstIterator.h"
78#include "llvm/Support/ManagedStatic.h"
79#include "llvm/Support/MathExtras.h"
Dan Gohman13058cc2009-04-21 00:47:46 +000080#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081#include "llvm/ADT/Statistic.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000082#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083#include <algorithm>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084using namespace llvm;
85
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086STATISTIC(NumArrayLenItCounts,
87 "Number of trip counts computed with array length");
88STATISTIC(NumTripCountsComputed,
89 "Number of loops with predictable loop counts");
90STATISTIC(NumTripCountsNotComputed,
91 "Number of loops without predictable loop counts");
92STATISTIC(NumBruteForceTripCountsComputed,
93 "Number of loops with trip counts computed by force");
94
Dan Gohman089efff2008-05-13 00:00:25 +000095static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000096MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
97 cl::desc("Maximum number of iterations SCEV will "
98 "symbolically execute a constant derived loop"),
99 cl::init(100));
100
Dan Gohman089efff2008-05-13 00:00:25 +0000101static RegisterPass<ScalarEvolution>
102R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000103char ScalarEvolution::ID = 0;
104
105//===----------------------------------------------------------------------===//
106// SCEV class definitions
107//===----------------------------------------------------------------------===//
108
109//===----------------------------------------------------------------------===//
110// Implementation of the SCEV class.
111//
112SCEV::~SCEV() {}
113void SCEV::dump() const {
Dan Gohman13058cc2009-04-21 00:47:46 +0000114 print(errs());
115 errs() << '\n';
116}
117
118void SCEV::print(std::ostream &o) const {
119 raw_os_ostream OS(o);
120 print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000121}
122
Dan Gohman7b560c42008-06-18 16:23:07 +0000123bool SCEV::isZero() const {
124 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
125 return SC->getValue()->isZero();
126 return false;
127}
128
Dan Gohmanf8bc8e82009-05-18 15:22:39 +0000129bool SCEV::isOne() const {
130 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
131 return SC->getValue()->isOne();
132 return false;
133}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000134
135SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
Dan Gohmanffd36ba2009-04-21 23:15:49 +0000136SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000137
138bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
139 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
140 return false;
141}
142
143const Type *SCEVCouldNotCompute::getType() const {
144 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
145 return 0;
146}
147
148bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
149 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
150 return false;
151}
152
153SCEVHandle SCEVCouldNotCompute::
154replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000155 const SCEVHandle &Conc,
156 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157 return this;
158}
159
Dan Gohman13058cc2009-04-21 00:47:46 +0000160void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161 OS << "***COULDNOTCOMPUTE***";
162}
163
164bool SCEVCouldNotCompute::classof(const SCEV *S) {
165 return S->getSCEVType() == scCouldNotCompute;
166}
167
168
169// SCEVConstants - Only allow the creation of one SCEVConstant for any
170// particular value. Don't use a SCEVHandle here, or else the object will
171// never be deleted!
172static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
173
174
175SCEVConstant::~SCEVConstant() {
176 SCEVConstants->erase(V);
177}
178
Dan Gohman89f85052007-10-22 18:31:58 +0000179SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000180 SCEVConstant *&R = (*SCEVConstants)[V];
181 if (R == 0) R = new SCEVConstant(V);
182 return R;
183}
184
Dan Gohman89f85052007-10-22 18:31:58 +0000185SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
186 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187}
188
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000189const Type *SCEVConstant::getType() const { return V->getType(); }
190
Dan Gohman13058cc2009-04-21 00:47:46 +0000191void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000192 WriteAsOperand(OS, V, false);
193}
194
Dan Gohman2a381532009-04-21 01:25:57 +0000195SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
196 const SCEVHandle &op, const Type *ty)
197 : SCEV(SCEVTy), Op(op), Ty(ty) {}
198
199SCEVCastExpr::~SCEVCastExpr() {}
200
201bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
202 return Op->dominates(BB, DT);
203}
204
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
206// particular input. Don't use a SCEVHandle here, or else the object will
207// never be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000208static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000209 SCEVTruncateExpr*> > SCEVTruncates;
210
211SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000212 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000213 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
214 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000216}
217
218SCEVTruncateExpr::~SCEVTruncateExpr() {
219 SCEVTruncates->erase(std::make_pair(Op, Ty));
220}
221
Dan Gohman13058cc2009-04-21 00:47:46 +0000222void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000223 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224}
225
226// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
227// particular input. Don't use a SCEVHandle here, or else the object will never
228// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000229static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230 SCEVZeroExtendExpr*> > SCEVZeroExtends;
231
232SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000233 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000234 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
235 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237}
238
239SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
240 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
241}
242
Dan Gohman13058cc2009-04-21 00:47:46 +0000243void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000244 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000245}
246
247// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
248// particular input. Don't use a SCEVHandle here, or else the object will never
249// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000250static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251 SCEVSignExtendExpr*> > SCEVSignExtends;
252
253SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000254 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000255 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
256 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000258}
259
260SCEVSignExtendExpr::~SCEVSignExtendExpr() {
261 SCEVSignExtends->erase(std::make_pair(Op, Ty));
262}
263
Dan Gohman13058cc2009-04-21 00:47:46 +0000264void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000265 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000266}
267
268// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
269// particular input. Don't use a SCEVHandle here, or else the object will never
270// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000271static ManagedStatic<std::map<std::pair<unsigned, std::vector<const SCEV*> >,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272 SCEVCommutativeExpr*> > SCEVCommExprs;
273
274SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000275 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
276 SCEVCommExprs->erase(std::make_pair(getSCEVType(), SCEVOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000277}
278
Dan Gohman13058cc2009-04-21 00:47:46 +0000279void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
281 const char *OpStr = getOperationStr();
282 OS << "(" << *Operands[0];
283 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
284 OS << OpStr << *Operands[i];
285 OS << ")";
286}
287
288SCEVHandle SCEVCommutativeExpr::
289replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000290 const SCEVHandle &Conc,
291 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000293 SCEVHandle H =
294 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295 if (H != getOperand(i)) {
296 std::vector<SCEVHandle> NewOps;
297 NewOps.reserve(getNumOperands());
298 for (unsigned j = 0; j != i; ++j)
299 NewOps.push_back(getOperand(j));
300 NewOps.push_back(H);
301 for (++i; i != e; ++i)
302 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000303 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304
305 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000306 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000307 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000308 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000309 else if (isa<SCEVSMaxExpr>(this))
310 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000311 else if (isa<SCEVUMaxExpr>(this))
312 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313 else
314 assert(0 && "Unknown commutative expr!");
315 }
316 }
317 return this;
318}
319
Dan Gohman72a8a022009-05-07 14:00:19 +0000320bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng98c073b2009-02-17 00:13:06 +0000321 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
322 if (!getOperand(i)->dominates(BB, DT))
323 return false;
324 }
325 return true;
326}
327
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000328
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000329// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330// input. Don't use a SCEVHandle here, or else the object will never be
331// deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000332static ManagedStatic<std::map<std::pair<const SCEV*, const SCEV*>,
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000333 SCEVUDivExpr*> > SCEVUDivs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000335SCEVUDivExpr::~SCEVUDivExpr() {
336 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000337}
338
Evan Cheng98c073b2009-02-17 00:13:06 +0000339bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
340 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
341}
342
Dan Gohman13058cc2009-04-21 00:47:46 +0000343void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000344 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000345}
346
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000347const Type *SCEVUDivExpr::getType() const {
Dan Gohman140f08f2009-05-26 17:44:05 +0000348 // In most cases the types of LHS and RHS will be the same, but in some
349 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
350 // depend on the type for correctness, but handling types carefully can
351 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
352 // a pointer type than the RHS, so use the RHS' type here.
353 return RHS->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000354}
355
356// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
357// particular input. Don't use a SCEVHandle here, or else the object will never
358// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000359static ManagedStatic<std::map<std::pair<const Loop *,
360 std::vector<const SCEV*> >,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361 SCEVAddRecExpr*> > SCEVAddRecExprs;
362
363SCEVAddRecExpr::~SCEVAddRecExpr() {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000364 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
365 SCEVAddRecExprs->erase(std::make_pair(L, SCEVOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000366}
367
368SCEVHandle SCEVAddRecExpr::
369replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000370 const SCEVHandle &Conc,
371 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000373 SCEVHandle H =
374 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375 if (H != getOperand(i)) {
376 std::vector<SCEVHandle> NewOps;
377 NewOps.reserve(getNumOperands());
378 for (unsigned j = 0; j != i; ++j)
379 NewOps.push_back(getOperand(j));
380 NewOps.push_back(H);
381 for (++i; i != e; ++i)
382 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000383 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000384
Dan Gohman89f85052007-10-22 18:31:58 +0000385 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386 }
387 }
388 return this;
389}
390
391
392bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
393 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
394 // contain L and if the start is invariant.
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000395 // Add recurrences are never invariant in the function-body (null loop).
396 return QueryLoop &&
397 !QueryLoop->contains(L->getHeader()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000398 getOperand(0)->isLoopInvariant(QueryLoop);
399}
400
401
Dan Gohman13058cc2009-04-21 00:47:46 +0000402void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000403 OS << "{" << *Operands[0];
404 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
405 OS << ",+," << *Operands[i];
406 OS << "}<" << L->getHeader()->getName() + ">";
407}
408
409// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
410// value. Don't use a SCEVHandle here, or else the object will never be
411// deleted!
412static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
413
414SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
415
416bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
417 // All non-instruction values are loop invariant. All instructions are loop
418 // invariant if they are not contained in the specified loop.
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000419 // Instructions are never considered invariant in the function body
420 // (null loop) because they are defined within the "loop".
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000421 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000422 return L && !L->contains(I->getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000423 return true;
424}
425
Evan Cheng98c073b2009-02-17 00:13:06 +0000426bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
427 if (Instruction *I = dyn_cast<Instruction>(getValue()))
428 return DT->dominates(I->getParent(), BB);
429 return true;
430}
431
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432const Type *SCEVUnknown::getType() const {
433 return V->getType();
434}
435
Dan Gohman13058cc2009-04-21 00:47:46 +0000436void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000437 WriteAsOperand(OS, V, false);
438}
439
440//===----------------------------------------------------------------------===//
441// SCEV Utilities
442//===----------------------------------------------------------------------===//
443
444namespace {
445 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
446 /// than the complexity of the RHS. This comparator is used to canonicalize
447 /// expressions.
Dan Gohman5d486452009-05-07 14:39:04 +0000448 class VISIBILITY_HIDDEN SCEVComplexityCompare {
449 LoopInfo *LI;
450 public:
451 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
452
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000453 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman5d486452009-05-07 14:39:04 +0000454 // Primarily, sort the SCEVs by their getSCEVType().
455 if (LHS->getSCEVType() != RHS->getSCEVType())
456 return LHS->getSCEVType() < RHS->getSCEVType();
457
458 // Aside from the getSCEVType() ordering, the particular ordering
459 // isn't very important except that it's beneficial to be consistent,
460 // so that (a + b) and (b + a) don't end up as different expressions.
461
462 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
463 // not as complete as it could be.
464 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
465 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
466
Dan Gohmand0c01232009-05-19 02:15:55 +0000467 // Order pointer values after integer values. This helps SCEVExpander
468 // form GEPs.
469 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
470 return false;
471 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
472 return true;
473
Dan Gohman5d486452009-05-07 14:39:04 +0000474 // Compare getValueID values.
475 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
476 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
477
478 // Sort arguments by their position.
479 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
480 const Argument *RA = cast<Argument>(RU->getValue());
481 return LA->getArgNo() < RA->getArgNo();
482 }
483
484 // For instructions, compare their loop depth, and their opcode.
485 // This is pretty loose.
486 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
487 Instruction *RV = cast<Instruction>(RU->getValue());
488
489 // Compare loop depths.
490 if (LI->getLoopDepth(LV->getParent()) !=
491 LI->getLoopDepth(RV->getParent()))
492 return LI->getLoopDepth(LV->getParent()) <
493 LI->getLoopDepth(RV->getParent());
494
495 // Compare opcodes.
496 if (LV->getOpcode() != RV->getOpcode())
497 return LV->getOpcode() < RV->getOpcode();
498
499 // Compare the number of operands.
500 if (LV->getNumOperands() != RV->getNumOperands())
501 return LV->getNumOperands() < RV->getNumOperands();
502 }
503
504 return false;
505 }
506
507 // Constant sorting doesn't matter since they'll be folded.
508 if (isa<SCEVConstant>(LHS))
509 return false;
510
511 // Lexicographically compare n-ary expressions.
512 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
513 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
514 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
515 if (i >= RC->getNumOperands())
516 return false;
517 if (operator()(LC->getOperand(i), RC->getOperand(i)))
518 return true;
519 if (operator()(RC->getOperand(i), LC->getOperand(i)))
520 return false;
521 }
522 return LC->getNumOperands() < RC->getNumOperands();
523 }
524
Dan Gohman6e10db12009-05-07 19:23:21 +0000525 // Lexicographically compare udiv expressions.
526 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
527 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
528 if (operator()(LC->getLHS(), RC->getLHS()))
529 return true;
530 if (operator()(RC->getLHS(), LC->getLHS()))
531 return false;
532 if (operator()(LC->getRHS(), RC->getRHS()))
533 return true;
534 if (operator()(RC->getRHS(), LC->getRHS()))
535 return false;
536 return false;
537 }
538
Dan Gohman5d486452009-05-07 14:39:04 +0000539 // Compare cast expressions by operand.
540 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
541 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
542 return operator()(LC->getOperand(), RC->getOperand());
543 }
544
545 assert(0 && "Unknown SCEV kind!");
546 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000547 }
548 };
549}
550
551/// GroupByComplexity - Given a list of SCEV objects, order them by their
552/// complexity, and group objects of the same complexity together by value.
553/// When this routine is finished, we know that any duplicates in the vector are
554/// consecutive and that complexity is monotonically increasing.
555///
556/// Note that we go take special precautions to ensure that we get determinstic
557/// results from this routine. In other words, we don't want the results of
558/// this to depend on where the addresses of various SCEV objects happened to
559/// land in memory.
560///
Dan Gohman5d486452009-05-07 14:39:04 +0000561static void GroupByComplexity(std::vector<SCEVHandle> &Ops,
562 LoopInfo *LI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000563 if (Ops.size() < 2) return; // Noop
564 if (Ops.size() == 2) {
565 // This is the common case, which also happens to be trivially simple.
566 // Special case it.
Dan Gohman5d486452009-05-07 14:39:04 +0000567 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000568 std::swap(Ops[0], Ops[1]);
569 return;
570 }
571
572 // Do the rough sort by complexity.
Dan Gohman5d486452009-05-07 14:39:04 +0000573 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000574
575 // Now that we are sorted by complexity, group elements of the same
576 // complexity. Note that this is, at worst, N^2, but the vector is likely to
577 // be extremely short in practice. Note that we take this approach because we
578 // do not want to depend on the addresses of the objects we are grouping.
579 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000580 const SCEV *S = Ops[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000581 unsigned Complexity = S->getSCEVType();
582
583 // If there are any objects of the same complexity and same value as this
584 // one, group them.
585 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
586 if (Ops[j] == S) { // Found a duplicate.
587 // Move it to immediately after i'th element.
588 std::swap(Ops[i+1], Ops[j]);
589 ++i; // no need to rescan it.
590 if (i == e-2) return; // Done!
591 }
592 }
593 }
594}
595
596
597
598//===----------------------------------------------------------------------===//
599// Simple SCEV method implementations
600//===----------------------------------------------------------------------===//
601
Eli Friedman7489ec92008-08-04 23:49:06 +0000602/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohmanc8a29272009-05-24 23:45:28 +0000603/// Assume, K > 0.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000604static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000605 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000606 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000607 // Handle the simplest case efficiently.
608 if (K == 1)
609 return SE.getTruncateOrZeroExtend(It, ResultTy);
610
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000611 // We are using the following formula for BC(It, K):
612 //
613 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
614 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000615 // Suppose, W is the bitwidth of the return value. We must be prepared for
616 // overflow. Hence, we must assure that the result of our computation is
617 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
618 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000619 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000620 // However, this code doesn't use exactly that formula; the formula it uses
621 // is something like the following, where T is the number of factors of 2 in
622 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
623 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000624 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000625 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000626 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000627 // This formula is trivially equivalent to the previous formula. However,
628 // this formula can be implemented much more efficiently. The trick is that
629 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
630 // arithmetic. To do exact division in modular arithmetic, all we have
631 // to do is multiply by the inverse. Therefore, this step can be done at
632 // width W.
633 //
634 // The next issue is how to safely do the division by 2^T. The way this
635 // is done is by doing the multiplication step at a width of at least W + T
636 // bits. This way, the bottom W+T bits of the product are accurate. Then,
637 // when we perform the division by 2^T (which is equivalent to a right shift
638 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
639 // truncated out after the division by 2^T.
640 //
641 // In comparison to just directly using the first formula, this technique
642 // is much more efficient; using the first formula requires W * K bits,
643 // but this formula less than W + K bits. Also, the first formula requires
644 // a division step, whereas this formula only requires multiplies and shifts.
645 //
646 // It doesn't matter whether the subtraction step is done in the calculation
647 // width or the input iteration count's width; if the subtraction overflows,
648 // the result must be zero anyway. We prefer here to do it in the width of
649 // the induction variable because it helps a lot for certain cases; CodeGen
650 // isn't smart enough to ignore the overflow, which leads to much less
651 // efficient code if the width of the subtraction is wider than the native
652 // register width.
653 //
654 // (It's possible to not widen at all by pulling out factors of 2 before
655 // the multiplication; for example, K=2 can be calculated as
656 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
657 // extra arithmetic, so it's not an obvious win, and it gets
658 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000659
Eli Friedman7489ec92008-08-04 23:49:06 +0000660 // Protection from insane SCEVs; this bound is conservative,
661 // but it probably doesn't matter.
662 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000663 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000664
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000665 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000666
Eli Friedman7489ec92008-08-04 23:49:06 +0000667 // Calculate K! / 2^T and T; we divide out the factors of two before
668 // multiplying for calculating K! / 2^T to avoid overflow.
669 // Other overflow doesn't matter because we only care about the bottom
670 // W bits of the result.
671 APInt OddFactorial(W, 1);
672 unsigned T = 1;
673 for (unsigned i = 3; i <= K; ++i) {
674 APInt Mult(W, i);
675 unsigned TwoFactors = Mult.countTrailingZeros();
676 T += TwoFactors;
677 Mult = Mult.lshr(TwoFactors);
678 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000679 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000680
Eli Friedman7489ec92008-08-04 23:49:06 +0000681 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000682 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000683
684 // Calcuate 2^T, at width T+W.
685 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
686
687 // Calculate the multiplicative inverse of K! / 2^T;
688 // this multiplication factor will perform the exact division by
689 // K! / 2^T.
690 APInt Mod = APInt::getSignedMinValue(W+1);
691 APInt MultiplyFactor = OddFactorial.zext(W+1);
692 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
693 MultiplyFactor = MultiplyFactor.trunc(W);
694
695 // Calculate the product, at width T+W
696 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
697 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
698 for (unsigned i = 1; i != K; ++i) {
699 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
700 Dividend = SE.getMulExpr(Dividend,
701 SE.getTruncateOrZeroExtend(S, CalculationTy));
702 }
703
704 // Divide by 2^T
705 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
706
707 // Truncate the result, and divide by K! / 2^T.
708
709 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
710 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000711}
712
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000713/// evaluateAtIteration - Return the value of this chain of recurrences at
714/// the specified iteration number. We can evaluate this recurrence by
715/// multiplying each element in the chain by the binomial coefficient
716/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
717///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000718/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000719///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000720/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000721///
Dan Gohman89f85052007-10-22 18:31:58 +0000722SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
723 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000724 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000725 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000726 // The computation is correct in the face of overflow provided that the
727 // multiplication is performed _after_ the evaluation of the binomial
728 // coefficient.
Dan Gohman01c2ee72009-04-16 03:18:22 +0000729 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000730 if (isa<SCEVCouldNotCompute>(Coeff))
731 return Coeff;
732
733 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000734 }
735 return Result;
736}
737
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000738//===----------------------------------------------------------------------===//
739// SCEV Expression folder implementations
740//===----------------------------------------------------------------------===//
741
Dan Gohman9c8abcc2009-05-01 16:44:56 +0000742SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
743 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000744 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000745 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000746 assert(isSCEVable(Ty) &&
747 "This is not a conversion to a SCEVable type!");
748 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000749
Dan Gohmanc76b5452009-05-04 22:02:23 +0000750 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000751 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000752 ConstantExpr::getTrunc(SC->getValue(), Ty));
753
Dan Gohman1a5c4992009-04-22 16:20:48 +0000754 // trunc(trunc(x)) --> trunc(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000755 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000756 return getTruncateExpr(ST->getOperand(), Ty);
757
Nick Lewycky37d04642009-04-23 05:15:08 +0000758 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000759 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000760 return getTruncateOrSignExtend(SS->getOperand(), Ty);
761
762 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000763 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000764 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
765
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000766 // If the input value is a chrec scev made out of constants, truncate
767 // all of the constants.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000768 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000769 std::vector<SCEVHandle> Operands;
770 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman45b3b542009-05-08 21:03:19 +0000771 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
772 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000773 }
774
775 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
776 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
777 return Result;
778}
779
Dan Gohman36d40922009-04-16 19:25:55 +0000780SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
781 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000782 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000783 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000784 assert(isSCEVable(Ty) &&
785 "This is not a conversion to a SCEVable type!");
786 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000787
Dan Gohmanc76b5452009-05-04 22:02:23 +0000788 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000789 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000790 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
791 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
792 return getUnknown(C);
793 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000794
Dan Gohman1a5c4992009-04-22 16:20:48 +0000795 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000796 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000797 return getZeroExtendExpr(SZ->getOperand(), Ty);
798
Dan Gohmana9dba962009-04-27 20:16:15 +0000799 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000800 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000801 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000802 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000803 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000804 if (AR->isAffine()) {
805 // Check whether the backedge-taken count is SCEVCouldNotCompute.
806 // Note that this serves two purposes: It filters out loops that are
807 // simply not analyzable, and it covers the case where this code is
808 // being called from within backedge-taken count analysis, such that
809 // attempting to ask for the backedge-taken count would likely result
810 // in infinite recursion. In the later case, the analysis code will
811 // cope with a conservative value, and it will take care to purge
812 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000813 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
814 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000815 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000816 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000817 SCEVHandle Start = AR->getStart();
818 SCEVHandle Step = AR->getStepRecurrence(*this);
819
820 // Check whether the backedge-taken count can be losslessly casted to
821 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000822 SCEVHandle CastedMaxBECount =
823 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman3bb37f52009-05-18 15:58:39 +0000824 SCEVHandle RecastedMaxBECount =
825 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
826 if (MaxBECount == RecastedMaxBECount) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000827 const Type *WideTy =
828 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000829 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000830 SCEVHandle ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000831 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000832 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000833 SCEVHandle Add = getAddExpr(Start, ZMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000834 SCEVHandle OperandExtendedAdd =
835 getAddExpr(getZeroExtendExpr(Start, WideTy),
836 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
837 getZeroExtendExpr(Step, WideTy)));
838 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000839 // Return the expression with the addrec on the outside.
840 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
841 getZeroExtendExpr(Step, Ty),
842 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000843
844 // Similar to above, only this time treat the step value as signed.
845 // This covers loops that count down.
846 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000847 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000848 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000849 Add = getAddExpr(Start, SMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000850 OperandExtendedAdd =
851 getAddExpr(getZeroExtendExpr(Start, WideTy),
852 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
853 getSignExtendExpr(Step, WideTy)));
854 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000855 // Return the expression with the addrec on the outside.
856 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
857 getSignExtendExpr(Step, Ty),
858 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000859 }
860 }
861 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000862
863 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
864 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
865 return Result;
866}
867
Dan Gohmana9dba962009-04-27 20:16:15 +0000868SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
869 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000870 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000871 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000872 assert(isSCEVable(Ty) &&
873 "This is not a conversion to a SCEVable type!");
874 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000875
Dan Gohmanc76b5452009-05-04 22:02:23 +0000876 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000877 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000878 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
879 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
880 return getUnknown(C);
881 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000882
Dan Gohman1a5c4992009-04-22 16:20:48 +0000883 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000884 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000885 return getSignExtendExpr(SS->getOperand(), Ty);
886
Dan Gohmana9dba962009-04-27 20:16:15 +0000887 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000888 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000889 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000890 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000891 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000892 if (AR->isAffine()) {
893 // Check whether the backedge-taken count is SCEVCouldNotCompute.
894 // Note that this serves two purposes: It filters out loops that are
895 // simply not analyzable, and it covers the case where this code is
896 // being called from within backedge-taken count analysis, such that
897 // attempting to ask for the backedge-taken count would likely result
898 // in infinite recursion. In the later case, the analysis code will
899 // cope with a conservative value, and it will take care to purge
900 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000901 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
902 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000903 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000904 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000905 SCEVHandle Start = AR->getStart();
906 SCEVHandle Step = AR->getStepRecurrence(*this);
907
908 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000909 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000910 SCEVHandle CastedMaxBECount =
911 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman3bb37f52009-05-18 15:58:39 +0000912 SCEVHandle RecastedMaxBECount =
913 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
914 if (MaxBECount == RecastedMaxBECount) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000915 const Type *WideTy =
916 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000917 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000918 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000919 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000920 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000921 SCEVHandle Add = getAddExpr(Start, SMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000922 SCEVHandle OperandExtendedAdd =
923 getAddExpr(getSignExtendExpr(Start, WideTy),
924 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
925 getSignExtendExpr(Step, WideTy)));
926 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000927 // Return the expression with the addrec on the outside.
928 return getAddRecExpr(getSignExtendExpr(Start, Ty),
929 getSignExtendExpr(Step, Ty),
930 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000931 }
932 }
933 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934
935 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
936 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
937 return Result;
938}
939
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000940/// getAnyExtendExpr - Return a SCEV for the given operand extended with
941/// unspecified bits out to the given type.
942///
943SCEVHandle ScalarEvolution::getAnyExtendExpr(const SCEVHandle &Op,
944 const Type *Ty) {
945 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
946 "This is not an extending conversion!");
947 assert(isSCEVable(Ty) &&
948 "This is not a conversion to a SCEVable type!");
949 Ty = getEffectiveSCEVType(Ty);
950
951 // Sign-extend negative constants.
952 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
953 if (SC->getValue()->getValue().isNegative())
954 return getSignExtendExpr(Op, Ty);
955
956 // Peel off a truncate cast.
957 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
958 SCEVHandle NewOp = T->getOperand();
959 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
960 return getAnyExtendExpr(NewOp, Ty);
961 return getTruncateOrNoop(NewOp, Ty);
962 }
963
964 // Next try a zext cast. If the cast is folded, use it.
965 SCEVHandle ZExt = getZeroExtendExpr(Op, Ty);
966 if (!isa<SCEVZeroExtendExpr>(ZExt))
967 return ZExt;
968
969 // Next try a sext cast. If the cast is folded, use it.
970 SCEVHandle SExt = getSignExtendExpr(Op, Ty);
971 if (!isa<SCEVSignExtendExpr>(SExt))
972 return SExt;
973
974 // If the expression is obviously signed, use the sext cast value.
975 if (isa<SCEVSMaxExpr>(Op))
976 return SExt;
977
978 // Absent any other information, use the zext cast value.
979 return ZExt;
980}
981
Dan Gohmanc8a29272009-05-24 23:45:28 +0000982/// getAddExpr - Get a canonical add expression, or something simpler if
983/// possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000984SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000985 assert(!Ops.empty() && "Cannot get empty add!");
986 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +0000987#ifndef NDEBUG
988 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
989 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
990 getEffectiveSCEVType(Ops[0]->getType()) &&
991 "SCEVAddExpr operand types don't match!");
992#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000993
994 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +0000995 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000996
997 // If there are any constants, fold them together.
998 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +0000999 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001000 ++Idx;
1001 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001002 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001003 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001004 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
1005 RHSC->getValue()->getValue());
1006 Ops[0] = getConstant(Fold);
1007 Ops.erase(Ops.begin()+1); // Erase the folded element
1008 if (Ops.size() == 1) return Ops[0];
1009 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001010 }
1011
1012 // If we are left with a constant zero being added, strip it off.
1013 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1014 Ops.erase(Ops.begin());
1015 --Idx;
1016 }
1017 }
1018
1019 if (Ops.size() == 1) return Ops[0];
1020
1021 // Okay, check to see if the same value occurs in the operand list twice. If
1022 // so, merge them together into an multiply expression. Since we sorted the
1023 // list, these values are required to be adjacent.
1024 const Type *Ty = Ops[0]->getType();
1025 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1026 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1027 // Found a match, merge the two values into a multiply, and add any
1028 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +00001029 SCEVHandle Two = getIntegerSCEV(2, Ty);
1030 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001031 if (Ops.size() == 2)
1032 return Mul;
1033 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1034 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +00001035 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001036 }
1037
Dan Gohman45b3b542009-05-08 21:03:19 +00001038 // Check for truncates. If all the operands are truncated from the same
1039 // type, see if factoring out the truncate would permit the result to be
1040 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1041 // if the contents of the resulting outer trunc fold to something simple.
1042 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1043 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1044 const Type *DstType = Trunc->getType();
1045 const Type *SrcType = Trunc->getOperand()->getType();
1046 std::vector<SCEVHandle> LargeOps;
1047 bool Ok = true;
1048 // Check all the operands to see if they can be represented in the
1049 // source type of the truncate.
1050 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1051 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1052 if (T->getOperand()->getType() != SrcType) {
1053 Ok = false;
1054 break;
1055 }
1056 LargeOps.push_back(T->getOperand());
1057 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1058 // This could be either sign or zero extension, but sign extension
1059 // is much more likely to be foldable here.
1060 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1061 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1062 std::vector<SCEVHandle> LargeMulOps;
1063 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1064 if (const SCEVTruncateExpr *T =
1065 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1066 if (T->getOperand()->getType() != SrcType) {
1067 Ok = false;
1068 break;
1069 }
1070 LargeMulOps.push_back(T->getOperand());
1071 } else if (const SCEVConstant *C =
1072 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1073 // This could be either sign or zero extension, but sign extension
1074 // is much more likely to be foldable here.
1075 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1076 } else {
1077 Ok = false;
1078 break;
1079 }
1080 }
1081 if (Ok)
1082 LargeOps.push_back(getMulExpr(LargeMulOps));
1083 } else {
1084 Ok = false;
1085 break;
1086 }
1087 }
1088 if (Ok) {
1089 // Evaluate the expression in the larger type.
1090 SCEVHandle Fold = getAddExpr(LargeOps);
1091 // If it folds to something simple, use it. Otherwise, don't.
1092 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1093 return getTruncateExpr(Fold, DstType);
1094 }
1095 }
1096
1097 // Skip past any other cast SCEVs.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001098 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1099 ++Idx;
1100
1101 // If there are add operands they would be next.
1102 if (Idx < Ops.size()) {
1103 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001104 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001105 // If we have an add, expand the add operands onto the end of the operands
1106 // list.
1107 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1108 Ops.erase(Ops.begin()+Idx);
1109 DeletedAdd = true;
1110 }
1111
1112 // If we deleted at least one add, we added operands to the end of the list,
1113 // and they are not necessarily sorted. Recurse to resort and resimplify
1114 // any operands we just aquired.
1115 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +00001116 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001117 }
1118
1119 // Skip over the add expression until we get to a multiply.
1120 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1121 ++Idx;
1122
1123 // If we are adding something to a multiply expression, make sure the
1124 // something is not already an operand of the multiply. If so, merge it into
1125 // the multiply.
1126 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001127 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001128 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001129 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001130 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1131 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
1132 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1133 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
1134 if (Mul->getNumOperands() != 2) {
1135 // If the multiply has more than two operands, we must get the
1136 // Y*Z term.
1137 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1138 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001139 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140 }
Dan Gohman89f85052007-10-22 18:31:58 +00001141 SCEVHandle One = getIntegerSCEV(1, Ty);
1142 SCEVHandle AddOne = getAddExpr(InnerMul, One);
1143 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001144 if (Ops.size() == 2) return OuterMul;
1145 if (AddOp < Idx) {
1146 Ops.erase(Ops.begin()+AddOp);
1147 Ops.erase(Ops.begin()+Idx-1);
1148 } else {
1149 Ops.erase(Ops.begin()+Idx);
1150 Ops.erase(Ops.begin()+AddOp-1);
1151 }
1152 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001153 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001154 }
1155
1156 // Check this multiply against other multiplies being added together.
1157 for (unsigned OtherMulIdx = Idx+1;
1158 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1159 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001160 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001161 // If MulOp occurs in OtherMul, we can fold the two multiplies
1162 // together.
1163 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1164 OMulOp != e; ++OMulOp)
1165 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1166 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1167 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1168 if (Mul->getNumOperands() != 2) {
1169 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1170 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001171 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001172 }
1173 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1174 if (OtherMul->getNumOperands() != 2) {
1175 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
1176 OtherMul->op_end());
1177 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001178 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001179 }
Dan Gohman89f85052007-10-22 18:31:58 +00001180 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1181 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001182 if (Ops.size() == 2) return OuterMul;
1183 Ops.erase(Ops.begin()+Idx);
1184 Ops.erase(Ops.begin()+OtherMulIdx-1);
1185 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001186 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001187 }
1188 }
1189 }
1190 }
1191
1192 // If there are any add recurrences in the operands list, see if any other
1193 // added values are loop invariant. If so, we can fold them into the
1194 // recurrence.
1195 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1196 ++Idx;
1197
1198 // Scan over all recurrences, trying to fold loop invariants into them.
1199 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1200 // Scan all of the other operands to this add and add them to the vector if
1201 // they are loop invariant w.r.t. the recurrence.
1202 std::vector<SCEVHandle> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001203 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001204 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1205 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1206 LIOps.push_back(Ops[i]);
1207 Ops.erase(Ops.begin()+i);
1208 --i; --e;
1209 }
1210
1211 // If we found some loop invariants, fold them into the recurrence.
1212 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001213 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001214 LIOps.push_back(AddRec->getStart());
1215
1216 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001217 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001218
Dan Gohman89f85052007-10-22 18:31:58 +00001219 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001220 // If all of the other operands were loop invariant, we are done.
1221 if (Ops.size() == 1) return NewRec;
1222
1223 // Otherwise, add the folded AddRec by the non-liv parts.
1224 for (unsigned i = 0;; ++i)
1225 if (Ops[i] == AddRec) {
1226 Ops[i] = NewRec;
1227 break;
1228 }
Dan Gohman89f85052007-10-22 18:31:58 +00001229 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001230 }
1231
1232 // Okay, if there weren't any loop invariants to be folded, check to see if
1233 // there are multiple AddRec's with the same loop induction variable being
1234 // added together. If so, we can fold them.
1235 for (unsigned OtherIdx = Idx+1;
1236 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1237 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001238 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001239 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1240 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1241 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1242 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1243 if (i >= NewOps.size()) {
1244 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1245 OtherAddRec->op_end());
1246 break;
1247 }
Dan Gohman89f85052007-10-22 18:31:58 +00001248 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001249 }
Dan Gohman89f85052007-10-22 18:31:58 +00001250 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001251
1252 if (Ops.size() == 2) return NewAddRec;
1253
1254 Ops.erase(Ops.begin()+Idx);
1255 Ops.erase(Ops.begin()+OtherIdx-1);
1256 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001257 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001258 }
1259 }
1260
1261 // Otherwise couldn't fold anything into this recurrence. Move onto the
1262 // next one.
1263 }
1264
1265 // Okay, it looks like we really DO need an add expr. Check to see if we
1266 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001267 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001268 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1269 SCEVOps)];
1270 if (Result == 0) Result = new SCEVAddExpr(Ops);
1271 return Result;
1272}
1273
1274
Dan Gohmanc8a29272009-05-24 23:45:28 +00001275/// getMulExpr - Get a canonical multiply expression, or something simpler if
1276/// possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001277SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001278 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana77b3d42009-05-18 15:44:58 +00001279#ifndef NDEBUG
1280 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1281 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1282 getEffectiveSCEVType(Ops[0]->getType()) &&
1283 "SCEVMulExpr operand types don't match!");
1284#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001285
1286 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001287 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001288
1289 // If there are any constants, fold them together.
1290 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001291 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001292
1293 // C1*(C2+V) -> C1*C2 + C1*V
1294 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001295 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001296 if (Add->getNumOperands() == 2 &&
1297 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001298 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1299 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001300
1301
1302 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001303 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001304 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001305 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1306 RHSC->getValue()->getValue());
1307 Ops[0] = getConstant(Fold);
1308 Ops.erase(Ops.begin()+1); // Erase the folded element
1309 if (Ops.size() == 1) return Ops[0];
1310 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001311 }
1312
1313 // If we are left with a constant one being multiplied, strip it off.
1314 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1315 Ops.erase(Ops.begin());
1316 --Idx;
1317 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1318 // If we have a multiply of zero, it will always be zero.
1319 return Ops[0];
1320 }
1321 }
1322
1323 // Skip over the add expression until we get to a multiply.
1324 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1325 ++Idx;
1326
1327 if (Ops.size() == 1)
1328 return Ops[0];
1329
1330 // If there are mul operands inline them all into this expression.
1331 if (Idx < Ops.size()) {
1332 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001333 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001334 // If we have an mul, expand the mul operands onto the end of the operands
1335 // list.
1336 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1337 Ops.erase(Ops.begin()+Idx);
1338 DeletedMul = true;
1339 }
1340
1341 // If we deleted at least one mul, we added operands to the end of the list,
1342 // and they are not necessarily sorted. Recurse to resort and resimplify
1343 // any operands we just aquired.
1344 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001345 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001346 }
1347
1348 // If there are any add recurrences in the operands list, see if any other
1349 // added values are loop invariant. If so, we can fold them into the
1350 // recurrence.
1351 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1352 ++Idx;
1353
1354 // Scan over all recurrences, trying to fold loop invariants into them.
1355 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1356 // Scan all of the other operands to this mul and add them to the vector if
1357 // they are loop invariant w.r.t. the recurrence.
1358 std::vector<SCEVHandle> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001359 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001360 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1361 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1362 LIOps.push_back(Ops[i]);
1363 Ops.erase(Ops.begin()+i);
1364 --i; --e;
1365 }
1366
1367 // If we found some loop invariants, fold them into the recurrence.
1368 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001369 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001370 std::vector<SCEVHandle> NewOps;
1371 NewOps.reserve(AddRec->getNumOperands());
1372 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001373 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001374 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001375 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001376 } else {
1377 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1378 std::vector<SCEVHandle> MulOps(LIOps);
1379 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001380 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001381 }
1382 }
1383
Dan Gohman89f85052007-10-22 18:31:58 +00001384 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001385
1386 // If all of the other operands were loop invariant, we are done.
1387 if (Ops.size() == 1) return NewRec;
1388
1389 // Otherwise, multiply the folded AddRec by the non-liv parts.
1390 for (unsigned i = 0;; ++i)
1391 if (Ops[i] == AddRec) {
1392 Ops[i] = NewRec;
1393 break;
1394 }
Dan Gohman89f85052007-10-22 18:31:58 +00001395 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001396 }
1397
1398 // Okay, if there weren't any loop invariants to be folded, check to see if
1399 // there are multiple AddRec's with the same loop induction variable being
1400 // multiplied together. If so, we can fold them.
1401 for (unsigned OtherIdx = Idx+1;
1402 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1403 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001404 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001405 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1406 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001407 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001408 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001409 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001410 SCEVHandle B = F->getStepRecurrence(*this);
1411 SCEVHandle D = G->getStepRecurrence(*this);
1412 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1413 getMulExpr(G, B),
1414 getMulExpr(B, D));
1415 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1416 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001417 if (Ops.size() == 2) return NewAddRec;
1418
1419 Ops.erase(Ops.begin()+Idx);
1420 Ops.erase(Ops.begin()+OtherIdx-1);
1421 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001422 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001423 }
1424 }
1425
1426 // Otherwise couldn't fold anything into this recurrence. Move onto the
1427 // next one.
1428 }
1429
1430 // Okay, it looks like we really DO need an mul expr. Check to see if we
1431 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001432 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001433 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1434 SCEVOps)];
1435 if (Result == 0)
1436 Result = new SCEVMulExpr(Ops);
1437 return Result;
1438}
1439
Dan Gohmanc8a29272009-05-24 23:45:28 +00001440/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1441/// possible.
Dan Gohman77841cd2009-05-04 22:23:18 +00001442SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1443 const SCEVHandle &RHS) {
Dan Gohmana77b3d42009-05-18 15:44:58 +00001444 assert(getEffectiveSCEVType(LHS->getType()) ==
1445 getEffectiveSCEVType(RHS->getType()) &&
1446 "SCEVUDivExpr operand types don't match!");
1447
Dan Gohmanc76b5452009-05-04 22:02:23 +00001448 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001449 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001450 return LHS; // X udiv 1 --> x
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001451 if (RHSC->isZero())
1452 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001453
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001454 // Determine if the division can be folded into the operands of
1455 // its operands.
1456 // TODO: Generalize this to non-constants by using known-bits information.
1457 const Type *Ty = LHS->getType();
1458 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1459 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1460 // For non-power-of-two values, effectively round the value up to the
1461 // nearest power of two.
1462 if (!RHSC->getValue()->getValue().isPowerOf2())
1463 ++MaxShiftAmt;
1464 const IntegerType *ExtTy =
1465 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1466 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1467 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1468 if (const SCEVConstant *Step =
1469 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1470 if (!Step->getValue()->getValue()
1471 .urem(RHSC->getValue()->getValue()) &&
Dan Gohman14374d32009-05-08 23:11:16 +00001472 getZeroExtendExpr(AR, ExtTy) ==
1473 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1474 getZeroExtendExpr(Step, ExtTy),
1475 AR->getLoop())) {
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001476 std::vector<SCEVHandle> Operands;
1477 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1478 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1479 return getAddRecExpr(Operands, AR->getLoop());
1480 }
1481 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001482 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1483 std::vector<SCEVHandle> Operands;
1484 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1485 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1486 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001487 // Find an operand that's safely divisible.
1488 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1489 SCEVHandle Op = M->getOperand(i);
1490 SCEVHandle Div = getUDivExpr(Op, RHSC);
1491 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman14374d32009-05-08 23:11:16 +00001492 Operands = M->getOperands();
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001493 Operands[i] = Div;
1494 return getMulExpr(Operands);
1495 }
1496 }
Dan Gohman14374d32009-05-08 23:11:16 +00001497 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001498 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001499 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1500 std::vector<SCEVHandle> Operands;
1501 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1502 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1503 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1504 Operands.clear();
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001505 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1506 SCEVHandle Op = getUDivExpr(A->getOperand(i), RHS);
1507 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1508 break;
1509 Operands.push_back(Op);
1510 }
1511 if (Operands.size() == A->getNumOperands())
1512 return getAddExpr(Operands);
1513 }
Dan Gohman14374d32009-05-08 23:11:16 +00001514 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001515
1516 // Fold if both operands are constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001517 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001518 Constant *LHSCV = LHSC->getValue();
1519 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001520 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001521 }
1522 }
1523
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001524 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1525 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001526 return Result;
1527}
1528
1529
Dan Gohmanc8a29272009-05-24 23:45:28 +00001530/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1531/// Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001532SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001533 const SCEVHandle &Step, const Loop *L) {
1534 std::vector<SCEVHandle> Operands;
1535 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001536 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001537 if (StepChrec->getLoop() == L) {
1538 Operands.insert(Operands.end(), StepChrec->op_begin(),
1539 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001540 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001541 }
1542
1543 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001544 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001545}
1546
Dan Gohmanc8a29272009-05-24 23:45:28 +00001547/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1548/// Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001549SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Nick Lewycky37d04642009-04-23 05:15:08 +00001550 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001551 if (Operands.size() == 1) return Operands[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001552#ifndef NDEBUG
1553 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1554 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1555 getEffectiveSCEVType(Operands[0]->getType()) &&
1556 "SCEVAddRecExpr operand types don't match!");
1557#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001558
Dan Gohman7b560c42008-06-18 16:23:07 +00001559 if (Operands.back()->isZero()) {
1560 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001561 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001562 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001563
Dan Gohman42936882008-08-08 18:33:12 +00001564 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001565 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001566 const Loop* NestedLoop = NestedAR->getLoop();
1567 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1568 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1569 NestedAR->op_end());
1570 SCEVHandle NestedARHandle(NestedAR);
1571 Operands[0] = NestedAR->getStart();
1572 NestedOperands[0] = getAddRecExpr(Operands, L);
1573 return getAddRecExpr(NestedOperands, NestedLoop);
1574 }
1575 }
1576
Dan Gohmanbff6b582009-05-04 22:30:44 +00001577 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1578 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001579 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1580 return Result;
1581}
1582
Nick Lewycky711640a2007-11-25 22:41:31 +00001583SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1584 const SCEVHandle &RHS) {
1585 std::vector<SCEVHandle> Ops;
1586 Ops.push_back(LHS);
1587 Ops.push_back(RHS);
1588 return getSMaxExpr(Ops);
1589}
1590
1591SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1592 assert(!Ops.empty() && "Cannot get empty smax!");
1593 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001594#ifndef NDEBUG
1595 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1596 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1597 getEffectiveSCEVType(Ops[0]->getType()) &&
1598 "SCEVSMaxExpr operand types don't match!");
1599#endif
Nick Lewycky711640a2007-11-25 22:41:31 +00001600
1601 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001602 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001603
1604 // If there are any constants, fold them together.
1605 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001606 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001607 ++Idx;
1608 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001609 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001610 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001611 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001612 APIntOps::smax(LHSC->getValue()->getValue(),
1613 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001614 Ops[0] = getConstant(Fold);
1615 Ops.erase(Ops.begin()+1); // Erase the folded element
1616 if (Ops.size() == 1) return Ops[0];
1617 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001618 }
1619
1620 // If we are left with a constant -inf, strip it off.
1621 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1622 Ops.erase(Ops.begin());
1623 --Idx;
1624 }
1625 }
1626
1627 if (Ops.size() == 1) return Ops[0];
1628
1629 // Find the first SMax
1630 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1631 ++Idx;
1632
1633 // Check to see if one of the operands is an SMax. If so, expand its operands
1634 // onto our operand list, and recurse to simplify.
1635 if (Idx < Ops.size()) {
1636 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001637 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001638 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1639 Ops.erase(Ops.begin()+Idx);
1640 DeletedSMax = true;
1641 }
1642
1643 if (DeletedSMax)
1644 return getSMaxExpr(Ops);
1645 }
1646
1647 // Okay, check to see if the same value occurs in the operand list twice. If
1648 // so, delete one. Since we sorted the list, these values are required to
1649 // be adjacent.
1650 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1651 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1652 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1653 --i; --e;
1654 }
1655
1656 if (Ops.size() == 1) return Ops[0];
1657
1658 assert(!Ops.empty() && "Reduced smax down to nothing!");
1659
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001660 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001661 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001662 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewycky711640a2007-11-25 22:41:31 +00001663 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1664 SCEVOps)];
1665 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1666 return Result;
1667}
1668
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001669SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1670 const SCEVHandle &RHS) {
1671 std::vector<SCEVHandle> Ops;
1672 Ops.push_back(LHS);
1673 Ops.push_back(RHS);
1674 return getUMaxExpr(Ops);
1675}
1676
1677SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1678 assert(!Ops.empty() && "Cannot get empty umax!");
1679 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001680#ifndef NDEBUG
1681 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1682 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1683 getEffectiveSCEVType(Ops[0]->getType()) &&
1684 "SCEVUMaxExpr operand types don't match!");
1685#endif
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001686
1687 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001688 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001689
1690 // If there are any constants, fold them together.
1691 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001692 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001693 ++Idx;
1694 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001695 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001696 // We found two constants, fold them together!
1697 ConstantInt *Fold = ConstantInt::get(
1698 APIntOps::umax(LHSC->getValue()->getValue(),
1699 RHSC->getValue()->getValue()));
1700 Ops[0] = getConstant(Fold);
1701 Ops.erase(Ops.begin()+1); // Erase the folded element
1702 if (Ops.size() == 1) return Ops[0];
1703 LHSC = cast<SCEVConstant>(Ops[0]);
1704 }
1705
1706 // If we are left with a constant zero, strip it off.
1707 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1708 Ops.erase(Ops.begin());
1709 --Idx;
1710 }
1711 }
1712
1713 if (Ops.size() == 1) return Ops[0];
1714
1715 // Find the first UMax
1716 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1717 ++Idx;
1718
1719 // Check to see if one of the operands is a UMax. If so, expand its operands
1720 // onto our operand list, and recurse to simplify.
1721 if (Idx < Ops.size()) {
1722 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001723 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001724 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1725 Ops.erase(Ops.begin()+Idx);
1726 DeletedUMax = true;
1727 }
1728
1729 if (DeletedUMax)
1730 return getUMaxExpr(Ops);
1731 }
1732
1733 // Okay, check to see if the same value occurs in the operand list twice. If
1734 // so, delete one. Since we sorted the list, these values are required to
1735 // be adjacent.
1736 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1737 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1738 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1739 --i; --e;
1740 }
1741
1742 if (Ops.size() == 1) return Ops[0];
1743
1744 assert(!Ops.empty() && "Reduced umax down to nothing!");
1745
1746 // Okay, it looks like we really DO need a umax expr. Check to see if we
1747 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001748 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001749 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1750 SCEVOps)];
1751 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1752 return Result;
1753}
1754
Dan Gohman89f85052007-10-22 18:31:58 +00001755SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001756 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001757 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001758 if (isa<ConstantPointerNull>(V))
1759 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001760 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1761 if (Result == 0) Result = new SCEVUnknown(V);
1762 return Result;
1763}
1764
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001765//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001766// Basic SCEV Analysis and PHI Idiom Recognition Code
1767//
1768
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001769/// isSCEVable - Test if values of the given type are analyzable within
1770/// the SCEV framework. This primarily includes integer types, and it
1771/// can optionally include pointer types if the ScalarEvolution class
1772/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001773bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001774 // Integers are always SCEVable.
1775 if (Ty->isInteger())
1776 return true;
1777
1778 // Pointers are SCEVable if TargetData information is available
1779 // to provide pointer size information.
1780 if (isa<PointerType>(Ty))
1781 return TD != NULL;
1782
1783 // Otherwise it's not SCEVable.
1784 return false;
1785}
1786
1787/// getTypeSizeInBits - Return the size in bits of the specified type,
1788/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001789uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001790 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1791
1792 // If we have a TargetData, use it!
1793 if (TD)
1794 return TD->getTypeSizeInBits(Ty);
1795
1796 // Otherwise, we support only integer types.
1797 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1798 return Ty->getPrimitiveSizeInBits();
1799}
1800
1801/// getEffectiveSCEVType - Return a type with the same bitwidth as
1802/// the given type and which represents how SCEV will treat the given
1803/// type, for which isSCEVable must return true. For pointer types,
1804/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001805const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001806 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1807
1808 if (Ty->isInteger())
1809 return Ty;
1810
1811 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1812 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001813}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001814
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001815SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman0c850912009-06-06 14:37:11 +00001816 return CouldNotCompute;
Dan Gohman0ad08b02009-04-18 17:58:19 +00001817}
1818
Dan Gohmand83d4af2009-05-04 22:20:30 +00001819/// hasSCEV - Return true if the SCEV for this value has already been
Edwin Török0e828d62009-05-01 08:33:47 +00001820/// computed.
1821bool ScalarEvolution::hasSCEV(Value *V) const {
1822 return Scalars.count(V);
1823}
1824
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001825/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1826/// expression and create a new one.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001827SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001828 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001829
Dan Gohmanbff6b582009-05-04 22:30:44 +00001830 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001831 if (I != Scalars.end()) return I->second;
1832 SCEVHandle S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00001833 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001834 return S;
1835}
1836
Dan Gohman01c2ee72009-04-16 03:18:22 +00001837/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1838/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001839SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1840 Ty = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001841 Constant *C;
1842 if (Val == 0)
1843 C = Constant::getNullValue(Ty);
1844 else if (Ty->isFloatingPoint())
1845 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1846 APFloat::IEEEdouble, Val));
1847 else
1848 C = ConstantInt::get(Ty, Val);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001849 return getUnknown(C);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001850}
1851
1852/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1853///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001854SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001855 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001856 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001857
1858 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001859 Ty = getEffectiveSCEVType(Ty);
1860 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001861}
1862
1863/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001864SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001865 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001866 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001867
1868 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001869 Ty = getEffectiveSCEVType(Ty);
1870 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001871 return getMinusSCEV(AllOnes, V);
1872}
1873
1874/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1875///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001876SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky37d04642009-04-23 05:15:08 +00001877 const SCEVHandle &RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001878 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001879 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001880}
1881
1882/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1883/// input value to the specified type. If the type must be extended, it is zero
1884/// extended.
1885SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001886ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001887 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001888 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001889 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1890 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001891 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001892 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001893 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001894 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001895 return getTruncateExpr(V, Ty);
1896 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001897}
1898
1899/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1900/// input value to the specified type. If the type must be extended, it is sign
1901/// extended.
1902SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001903ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001904 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001905 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001906 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1907 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001908 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001909 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001910 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001911 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001912 return getTruncateExpr(V, Ty);
1913 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001914}
1915
Dan Gohmanac959332009-05-13 03:46:30 +00001916/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
1917/// input value to the specified type. If the type must be extended, it is zero
1918/// extended. The conversion must not be narrowing.
1919SCEVHandle
1920ScalarEvolution::getNoopOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
1921 const Type *SrcTy = V->getType();
1922 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1923 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1924 "Cannot noop or zero extend with non-integer arguments!");
1925 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
1926 "getNoopOrZeroExtend cannot truncate!");
1927 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1928 return V; // No conversion
1929 return getZeroExtendExpr(V, Ty);
1930}
1931
1932/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
1933/// input value to the specified type. If the type must be extended, it is sign
1934/// extended. The conversion must not be narrowing.
1935SCEVHandle
1936ScalarEvolution::getNoopOrSignExtend(const SCEVHandle &V, const Type *Ty) {
1937 const Type *SrcTy = V->getType();
1938 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1939 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1940 "Cannot noop or sign extend with non-integer arguments!");
1941 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
1942 "getNoopOrSignExtend cannot truncate!");
1943 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1944 return V; // No conversion
1945 return getSignExtendExpr(V, Ty);
1946}
1947
Dan Gohmane1ca7e82009-06-13 15:56:47 +00001948/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
1949/// the input value to the specified type. If the type must be extended,
1950/// it is extended with unspecified bits. The conversion must not be
1951/// narrowing.
1952SCEVHandle
1953ScalarEvolution::getNoopOrAnyExtend(const SCEVHandle &V, const Type *Ty) {
1954 const Type *SrcTy = V->getType();
1955 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1956 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1957 "Cannot noop or any extend with non-integer arguments!");
1958 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
1959 "getNoopOrAnyExtend cannot truncate!");
1960 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1961 return V; // No conversion
1962 return getAnyExtendExpr(V, Ty);
1963}
1964
Dan Gohmanac959332009-05-13 03:46:30 +00001965/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
1966/// input value to the specified type. The conversion must not be widening.
1967SCEVHandle
1968ScalarEvolution::getTruncateOrNoop(const SCEVHandle &V, const Type *Ty) {
1969 const Type *SrcTy = V->getType();
1970 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1971 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1972 "Cannot truncate or noop with non-integer arguments!");
1973 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
1974 "getTruncateOrNoop cannot extend!");
1975 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1976 return V; // No conversion
1977 return getTruncateExpr(V, Ty);
1978}
1979
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001980/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1981/// the specified instruction and replaces any references to the symbolic value
1982/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001983void ScalarEvolution::
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001984ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1985 const SCEVHandle &NewVal) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001986 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
1987 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001988 if (SI == Scalars.end()) return;
1989
1990 SCEVHandle NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001991 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001992 if (NV == SI->second) return; // No change.
1993
1994 SI->second = NV; // Update the scalars map!
1995
1996 // Any instruction values that use this instruction might also need to be
1997 // updated!
1998 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1999 UI != E; ++UI)
2000 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2001}
2002
2003/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2004/// a loop header, making it a potential recurrence, or it doesn't.
2005///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002006SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002007 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002008 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002009 if (L->getHeader() == PN->getParent()) {
2010 // If it lives in the loop header, it has two incoming values, one
2011 // from outside the loop, and one from inside.
2012 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2013 unsigned BackEdge = IncomingEdge^1;
2014
2015 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002016 SCEVHandle SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002017 assert(Scalars.find(PN) == Scalars.end() &&
2018 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002019 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002020
2021 // Using this symbolic name for the PHI, analyze the value coming around
2022 // the back-edge.
2023 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
2024
2025 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2026 // has a special value for the first iteration of the loop.
2027
2028 // If the value coming around the backedge is an add with the symbolic
2029 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00002030 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002031 // If there is a single occurrence of the symbolic value, replace it
2032 // with a recurrence.
2033 unsigned FoundIndex = Add->getNumOperands();
2034 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2035 if (Add->getOperand(i) == SymbolicName)
2036 if (FoundIndex == e) {
2037 FoundIndex = i;
2038 break;
2039 }
2040
2041 if (FoundIndex != Add->getNumOperands()) {
2042 // Create an add with everything but the specified operand.
2043 std::vector<SCEVHandle> Ops;
2044 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2045 if (i != FoundIndex)
2046 Ops.push_back(Add->getOperand(i));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002047 SCEVHandle Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002048
2049 // This is not a valid addrec if the step amount is varying each
2050 // loop iteration, but is not itself an addrec in this loop.
2051 if (Accum->isLoopInvariant(L) ||
2052 (isa<SCEVAddRecExpr>(Accum) &&
2053 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2054 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002055 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002056
2057 // Okay, for the entire analysis of this edge we assumed the PHI
2058 // to be symbolic. We now need to go back and update all of the
2059 // entries for the scalars that use the PHI (except for the PHI
2060 // itself) to use the new analyzed value instead of the "symbolic"
2061 // value.
2062 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2063 return PHISCEV;
2064 }
2065 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00002066 } else if (const SCEVAddRecExpr *AddRec =
2067 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002068 // Otherwise, this could be a loop like this:
2069 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2070 // In this case, j = {1,+,1} and BEValue is j.
2071 // Because the other in-value of i (0) fits the evolution of BEValue
2072 // i really is an addrec evolution.
2073 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2074 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2075
2076 // If StartVal = j.start - j.stride, we can use StartVal as the
2077 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002078 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00002079 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002080 SCEVHandle PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002081 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002082
2083 // Okay, for the entire analysis of this edge we assumed the PHI
2084 // to be symbolic. We now need to go back and update all of the
2085 // entries for the scalars that use the PHI (except for the PHI
2086 // itself) to use the new analyzed value instead of the "symbolic"
2087 // value.
2088 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2089 return PHISCEV;
2090 }
2091 }
2092 }
2093
2094 return SymbolicName;
2095 }
2096
2097 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002098 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002099}
2100
Dan Gohman509cf4d2009-05-08 20:26:55 +00002101/// createNodeForGEP - Expand GEP instructions into add and multiply
2102/// operations. This allows them to be analyzed by regular SCEV code.
2103///
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002104SCEVHandle ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman509cf4d2009-05-08 20:26:55 +00002105
2106 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002107 Value *Base = GEP->getOperand(0);
Dan Gohmand586a4f2009-05-09 00:14:52 +00002108 // Don't attempt to analyze GEPs over unsized objects.
2109 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2110 return getUnknown(GEP);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002111 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002112 gep_type_iterator GTI = gep_type_begin(GEP);
2113 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2114 E = GEP->op_end();
Dan Gohman509cf4d2009-05-08 20:26:55 +00002115 I != E; ++I) {
2116 Value *Index = *I;
2117 // Compute the (potentially symbolic) offset in bytes for this index.
2118 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2119 // For a struct, add the member offset.
2120 const StructLayout &SL = *TD->getStructLayout(STy);
2121 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2122 uint64_t Offset = SL.getElementOffset(FieldNo);
2123 TotalOffset = getAddExpr(TotalOffset,
2124 getIntegerSCEV(Offset, IntPtrTy));
2125 } else {
2126 // For an array, add the element offset, explicitly scaled.
2127 SCEVHandle LocalOffset = getSCEV(Index);
2128 if (!isa<PointerType>(LocalOffset->getType()))
2129 // Getelementptr indicies are signed.
2130 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2131 IntPtrTy);
2132 LocalOffset =
2133 getMulExpr(LocalOffset,
Duncan Sandsec4f97d2009-05-09 07:06:46 +00002134 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman509cf4d2009-05-08 20:26:55 +00002135 IntPtrTy));
2136 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2137 }
2138 }
2139 return getAddExpr(getSCEV(Base), TotalOffset);
2140}
2141
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002142/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2143/// guaranteed to end in (at every loop iteration). It is, at the same time,
2144/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2145/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002146static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002147 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00002148 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002149
Dan Gohmanc76b5452009-05-04 22:02:23 +00002150 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002151 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
2152 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002153
Dan Gohmanc76b5452009-05-04 22:02:23 +00002154 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002155 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2156 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
Dan Gohmanbfd51da2009-05-12 01:23:18 +00002157 SE.getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002158 }
2159
Dan Gohmanc76b5452009-05-04 22:02:23 +00002160 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002161 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2162 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
Dan Gohmanbfd51da2009-05-12 01:23:18 +00002163 SE.getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002164 }
2165
Dan Gohmanc76b5452009-05-04 22:02:23 +00002166 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002167 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002168 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002169 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002170 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002171 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002172 }
2173
Dan Gohmanc76b5452009-05-04 22:02:23 +00002174 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002175 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002176 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
2177 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002178 for (unsigned i = 1, e = M->getNumOperands();
2179 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002180 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002181 BitWidth);
2182 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002183 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002184
Dan Gohmanc76b5452009-05-04 22:02:23 +00002185 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002186 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002187 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002188 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002189 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002190 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002191 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002192
Dan Gohmanc76b5452009-05-04 22:02:23 +00002193 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00002194 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002195 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00002196 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002197 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00002198 return MinOpRes;
2199 }
2200
Dan Gohmanc76b5452009-05-04 22:02:23 +00002201 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002202 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002203 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002204 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002205 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002206 return MinOpRes;
2207 }
2208
Nick Lewycky35b56022009-01-13 09:18:58 +00002209 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002210 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002211}
2212
2213/// createSCEV - We know that there is no SCEV for the specified value.
2214/// Analyze the expression.
2215///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002216SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002217 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002218 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002219
Dan Gohman3996f472008-06-22 19:56:46 +00002220 unsigned Opcode = Instruction::UserOp1;
2221 if (Instruction *I = dyn_cast<Instruction>(V))
2222 Opcode = I->getOpcode();
2223 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2224 Opcode = CE->getOpcode();
2225 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002226 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002227
Dan Gohman3996f472008-06-22 19:56:46 +00002228 User *U = cast<User>(V);
2229 switch (Opcode) {
2230 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002231 return getAddExpr(getSCEV(U->getOperand(0)),
2232 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002233 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002234 return getMulExpr(getSCEV(U->getOperand(0)),
2235 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002236 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002237 return getUDivExpr(getSCEV(U->getOperand(0)),
2238 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002239 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002240 return getMinusSCEV(getSCEV(U->getOperand(0)),
2241 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002242 case Instruction::And:
2243 // For an expression like x&255 that merely masks off the high bits,
2244 // use zext(trunc(x)) as the SCEV expression.
2245 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002246 if (CI->isNullValue())
2247 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00002248 if (CI->isAllOnesValue())
2249 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002250 const APInt &A = CI->getValue();
2251 unsigned Ones = A.countTrailingOnes();
2252 if (APIntOps::isMask(Ones, A))
2253 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002254 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
2255 IntegerType::get(Ones)),
2256 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00002257 }
2258 break;
Dan Gohman3996f472008-06-22 19:56:46 +00002259 case Instruction::Or:
2260 // If the RHS of the Or is a constant, we may have something like:
2261 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2262 // optimizations will transparently handle this case.
2263 //
2264 // In order for this transformation to be safe, the LHS must be of the
2265 // form X*(2^n) and the Or constant must be less than 2^n.
2266 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2267 SCEVHandle LHS = getSCEV(U->getOperand(0));
2268 const APInt &CIVal = CI->getValue();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002269 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman3996f472008-06-22 19:56:46 +00002270 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002271 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002272 }
Dan Gohman3996f472008-06-22 19:56:46 +00002273 break;
2274 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00002275 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00002276 // If the RHS of the xor is a signbit, then this is just an add.
2277 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00002278 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002279 return getAddExpr(getSCEV(U->getOperand(0)),
2280 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002281
2282 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmanc897f752009-05-18 16:17:44 +00002283 if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002284 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohmanfc78cff2009-05-18 16:29:04 +00002285
2286 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2287 // This is a variant of the check for xor with -1, and it handles
2288 // the case where instcombine has trimmed non-demanded bits out
2289 // of an xor with -1.
2290 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2291 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2292 if (BO->getOpcode() == Instruction::And &&
2293 LCI->getValue() == CI->getValue())
2294 if (const SCEVZeroExtendExpr *Z =
2295 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0))))
2296 return getZeroExtendExpr(getNotSCEV(Z->getOperand()),
2297 U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002298 }
2299 break;
2300
2301 case Instruction::Shl:
2302 // Turn shift left of a constant amount into a multiply.
2303 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2304 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2305 Constant *X = ConstantInt::get(
2306 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002307 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00002308 }
2309 break;
2310
Nick Lewycky7fd27892008-07-07 06:15:49 +00002311 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00002312 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00002313 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2314 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2315 Constant *X = ConstantInt::get(
2316 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002317 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002318 }
2319 break;
2320
Dan Gohman53bf64a2009-04-21 02:26:00 +00002321 case Instruction::AShr:
2322 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2323 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2324 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2325 if (L->getOpcode() == Instruction::Shl &&
2326 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002327 unsigned BitWidth = getTypeSizeInBits(U->getType());
2328 uint64_t Amt = BitWidth - CI->getZExtValue();
2329 if (Amt == BitWidth)
2330 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2331 if (Amt > BitWidth)
2332 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00002333 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002334 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00002335 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00002336 U->getType());
2337 }
2338 break;
2339
Dan Gohman3996f472008-06-22 19:56:46 +00002340 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002341 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002342
2343 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002344 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002345
2346 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002347 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002348
2349 case Instruction::BitCast:
2350 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002351 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002352 return getSCEV(U->getOperand(0));
2353 break;
2354
Dan Gohman01c2ee72009-04-16 03:18:22 +00002355 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002356 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002357 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002358 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002359
2360 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002361 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002362 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2363 U->getType());
2364
Dan Gohman509cf4d2009-05-08 20:26:55 +00002365 case Instruction::GetElementPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002366 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002367 return createNodeForGEP(U);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002368
Dan Gohman3996f472008-06-22 19:56:46 +00002369 case Instruction::PHI:
2370 return createNodeForPHI(cast<PHINode>(U));
2371
2372 case Instruction::Select:
2373 // This could be a smax or umax that was lowered earlier.
2374 // Try to recover it.
2375 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2376 Value *LHS = ICI->getOperand(0);
2377 Value *RHS = ICI->getOperand(1);
2378 switch (ICI->getPredicate()) {
2379 case ICmpInst::ICMP_SLT:
2380 case ICmpInst::ICMP_SLE:
2381 std::swap(LHS, RHS);
2382 // fall through
2383 case ICmpInst::ICMP_SGT:
2384 case ICmpInst::ICMP_SGE:
2385 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002386 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002387 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00002388 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002389 return getNotSCEV(getSMaxExpr(
2390 getNotSCEV(getSCEV(LHS)),
2391 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002392 break;
2393 case ICmpInst::ICMP_ULT:
2394 case ICmpInst::ICMP_ULE:
2395 std::swap(LHS, RHS);
2396 // fall through
2397 case ICmpInst::ICMP_UGT:
2398 case ICmpInst::ICMP_UGE:
2399 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002400 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002401 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2402 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002403 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2404 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002405 break;
2406 default:
2407 break;
2408 }
2409 }
2410
2411 default: // We cannot analyze this expression.
2412 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002413 }
2414
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002415 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002416}
2417
2418
2419
2420//===----------------------------------------------------------------------===//
2421// Iteration Count Computation Code
2422//
2423
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002424/// getBackedgeTakenCount - If the specified loop has a predictable
2425/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2426/// object. The backedge-taken count is the number of times the loop header
2427/// will be branched to from within the loop. This is one less than the
2428/// trip count of the loop, since it doesn't count the first iteration,
2429/// when the header is branched to from outside the loop.
2430///
2431/// Note that it is not valid to call this method on a loop without a
2432/// loop-invariant backedge-taken count (see
2433/// hasLoopInvariantBackedgeTakenCount).
2434///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002435SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002436 return getBackedgeTakenInfo(L).Exact;
2437}
2438
2439/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2440/// return the least SCEV value that is known never to be less than the
2441/// actual backedge taken count.
2442SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2443 return getBackedgeTakenInfo(L).Max;
2444}
2445
2446const ScalarEvolution::BackedgeTakenInfo &
2447ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002448 // Initially insert a CouldNotCompute for this loop. If the insertion
2449 // succeeds, procede to actually compute a backedge-taken count and
2450 // update the value. The temporary CouldNotCompute value tells SCEV
2451 // code elsewhere that it shouldn't attempt to request a new
2452 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002453 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002454 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2455 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002456 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman0c850912009-06-06 14:37:11 +00002457 if (ItCount.Exact != CouldNotCompute) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002458 assert(ItCount.Exact->isLoopInvariant(L) &&
2459 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002460 "Computed trip count isn't loop invariant for loop!");
2461 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002462
Dan Gohmana9dba962009-04-27 20:16:15 +00002463 // Update the value in the map.
2464 Pair.first->second = ItCount;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002465 } else if (isa<PHINode>(L->getHeader()->begin())) {
2466 // Only count loops that have phi nodes as not being computable.
2467 ++NumTripCountsNotComputed;
2468 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002469
2470 // Now that we know more about the trip count for this loop, forget any
2471 // existing SCEV values for PHI nodes in this loop since they are only
2472 // conservative estimates made without the benefit
2473 // of trip count information.
2474 if (ItCount.hasAnyInfo())
Dan Gohman94623022009-05-02 17:43:35 +00002475 forgetLoopPHIs(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002476 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002477 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002478}
2479
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002480/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002481/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002482/// ScalarEvolution's ability to compute a trip count, or if the loop
2483/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002484void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002485 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002486 forgetLoopPHIs(L);
2487}
2488
2489/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2490/// PHI nodes in the given loop. This is used when the trip count of
2491/// the loop may have changed.
2492void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002493 BasicBlock *Header = L->getHeader();
2494
Dan Gohman9fd4a002009-05-12 01:27:58 +00002495 // Push all Loop-header PHIs onto the Worklist stack, except those
2496 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2497 // a PHI either means that it has an unrecognized structure, or it's
2498 // a PHI that's in the progress of being computed by createNodeForPHI.
2499 // In the former case, additional loop trip count information isn't
2500 // going to change anything. In the later case, createNodeForPHI will
2501 // perform the necessary updates on its own when it gets to that point.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002502 SmallVector<Instruction *, 16> Worklist;
2503 for (BasicBlock::iterator I = Header->begin();
Dan Gohman9fd4a002009-05-12 01:27:58 +00002504 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2505 std::map<SCEVCallbackVH, SCEVHandle>::iterator It = Scalars.find((Value*)I);
2506 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2507 Worklist.push_back(PN);
2508 }
Dan Gohmanbff6b582009-05-04 22:30:44 +00002509
2510 while (!Worklist.empty()) {
2511 Instruction *I = Worklist.pop_back_val();
2512 if (Scalars.erase(I))
2513 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2514 UI != UE; ++UI)
2515 Worklist.push_back(cast<Instruction>(UI));
2516 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002517}
2518
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002519/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2520/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002521ScalarEvolution::BackedgeTakenInfo
2522ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002523 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel7388a9a2009-06-05 23:08:56 +00002524 BasicBlock *ExitBlock = L->getExitBlock();
2525 if (!ExitBlock)
Dan Gohman0c850912009-06-06 14:37:11 +00002526 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002527
2528 // Okay, there is one exit block. Try to find the condition that causes the
2529 // loop to be exited.
Devang Patel7388a9a2009-06-05 23:08:56 +00002530 BasicBlock *ExitingBlock = L->getExitingBlock();
2531 if (!ExitingBlock)
Dan Gohman0c850912009-06-06 14:37:11 +00002532 return CouldNotCompute; // More than one block exiting!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002533
2534 // Okay, we've computed the exiting block. See what condition causes us to
2535 // exit.
2536 //
2537 // FIXME: we should be able to handle switch instructions (with a single exit)
2538 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman0c850912009-06-06 14:37:11 +00002539 if (ExitBr == 0) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002540 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2541
2542 // At this point, we know we have a conditional branch that determines whether
2543 // the loop is exited. However, we don't know if the branch is executed each
2544 // time through the loop. If not, then the execution count of the branch will
2545 // not be equal to the trip count of the loop.
2546 //
2547 // Currently we check for this by checking to see if the Exit branch goes to
2548 // the loop header. If so, we know it will always execute the same number of
2549 // times as the loop. We also handle the case where the exit block *is* the
2550 // loop header. This is common for un-rotated loops. More extensive analysis
2551 // could be done to handle more cases here.
2552 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2553 ExitBr->getSuccessor(1) != L->getHeader() &&
2554 ExitBr->getParent() != L->getHeader())
Dan Gohman0c850912009-06-06 14:37:11 +00002555 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002556
2557 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2558
Eli Friedman459d7292009-05-09 12:32:42 +00002559 // If it's not an integer or pointer comparison then compute it the hard way.
2560 if (ExitCond == 0)
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002561 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002562 ExitBr->getSuccessor(0) == ExitBlock);
2563
2564 // If the condition was exit on true, convert the condition to exit on false
2565 ICmpInst::Predicate Cond;
2566 if (ExitBr->getSuccessor(1) == ExitBlock)
2567 Cond = ExitCond->getPredicate();
2568 else
2569 Cond = ExitCond->getInversePredicate();
2570
2571 // Handle common loops like: for (X = "string"; *X; ++X)
2572 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2573 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2574 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002575 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002576 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2577 }
2578
2579 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2580 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2581
2582 // Try to evaluate any dependencies out of the loop.
Dan Gohmanaff14d62009-05-24 23:25:42 +00002583 LHS = getSCEVAtScope(LHS, L);
2584 RHS = getSCEVAtScope(RHS, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002585
2586 // At this point, we would like to compute how many iterations of the
2587 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002588 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2589 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002590 std::swap(LHS, RHS);
2591 Cond = ICmpInst::getSwappedPredicate(Cond);
2592 }
2593
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002594 // If we have a comparison of a chrec against a constant, try to use value
2595 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002596 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2597 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002598 if (AddRec->getLoop() == L) {
Eli Friedman459d7292009-05-09 12:32:42 +00002599 // Form the constant range.
2600 ConstantRange CompRange(
2601 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002602
Eli Friedman459d7292009-05-09 12:32:42 +00002603 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
2604 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002605 }
2606
2607 switch (Cond) {
2608 case ICmpInst::ICMP_NE: { // while (X != Y)
2609 // Convert to: while (X-Y != 0)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002610 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002611 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2612 break;
2613 }
2614 case ICmpInst::ICMP_EQ: {
2615 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002616 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002617 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2618 break;
2619 }
2620 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002621 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2622 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002623 break;
2624 }
2625 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002626 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2627 getNotSCEV(RHS), L, true);
2628 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002629 break;
2630 }
2631 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002632 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2633 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002634 break;
2635 }
2636 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002637 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2638 getNotSCEV(RHS), L, false);
2639 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002640 break;
2641 }
2642 default:
2643#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002644 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002645 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002646 errs() << "[unsigned] ";
2647 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002648 << Instruction::getOpcodeName(Instruction::ICmp)
2649 << " " << *RHS << "\n";
2650#endif
2651 break;
2652 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002653 return
2654 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2655 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002656}
2657
2658static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002659EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2660 ScalarEvolution &SE) {
2661 SCEVHandle InVal = SE.getConstant(C);
2662 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002663 assert(isa<SCEVConstant>(Val) &&
2664 "Evaluation of SCEV at constant didn't fold correctly?");
2665 return cast<SCEVConstant>(Val)->getValue();
2666}
2667
2668/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2669/// and a GEP expression (missing the pointer index) indexing into it, return
2670/// the addressed element of the initializer or null if the index expression is
2671/// invalid.
2672static Constant *
2673GetAddressedElementFromGlobal(GlobalVariable *GV,
2674 const std::vector<ConstantInt*> &Indices) {
2675 Constant *Init = GV->getInitializer();
2676 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2677 uint64_t Idx = Indices[i]->getZExtValue();
2678 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2679 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2680 Init = cast<Constant>(CS->getOperand(Idx));
2681 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2682 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2683 Init = cast<Constant>(CA->getOperand(Idx));
2684 } else if (isa<ConstantAggregateZero>(Init)) {
2685 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2686 assert(Idx < STy->getNumElements() && "Bad struct index!");
2687 Init = Constant::getNullValue(STy->getElementType(Idx));
2688 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2689 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2690 Init = Constant::getNullValue(ATy->getElementType());
2691 } else {
2692 assert(0 && "Unknown constant aggregate type!");
2693 }
2694 return 0;
2695 } else {
2696 return 0; // Unknown initializer type
2697 }
2698 }
2699 return Init;
2700}
2701
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002702/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2703/// 'icmp op load X, cst', try to see if we can compute the backedge
2704/// execution count.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002705SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002706ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2707 const Loop *L,
2708 ICmpInst::Predicate predicate) {
Dan Gohman0c850912009-06-06 14:37:11 +00002709 if (LI->isVolatile()) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002710
2711 // Check to see if the loaded pointer is a getelementptr of a global.
2712 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman0c850912009-06-06 14:37:11 +00002713 if (!GEP) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002714
2715 // Make sure that it is really a constant global we are gepping, with an
2716 // initializer, and make sure the first IDX is really 0.
2717 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2718 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2719 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2720 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman0c850912009-06-06 14:37:11 +00002721 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002722
2723 // Okay, we allow one non-constant index into the GEP instruction.
2724 Value *VarIdx = 0;
2725 std::vector<ConstantInt*> Indexes;
2726 unsigned VarIdxNum = 0;
2727 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2728 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2729 Indexes.push_back(CI);
2730 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman0c850912009-06-06 14:37:11 +00002731 if (VarIdx) return CouldNotCompute; // Multiple non-constant idx's.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002732 VarIdx = GEP->getOperand(i);
2733 VarIdxNum = i-2;
2734 Indexes.push_back(0);
2735 }
2736
2737 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2738 // Check to see if X is a loop variant variable value now.
2739 SCEVHandle Idx = getSCEV(VarIdx);
Dan Gohmanaff14d62009-05-24 23:25:42 +00002740 Idx = getSCEVAtScope(Idx, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002741
2742 // We can only recognize very limited forms of loop index expressions, in
2743 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002744 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002745 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2746 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2747 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman0c850912009-06-06 14:37:11 +00002748 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002749
2750 unsigned MaxSteps = MaxBruteForceIterations;
2751 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2752 ConstantInt *ItCst =
2753 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002754 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002755
2756 // Form the GEP offset.
2757 Indexes[VarIdxNum] = Val;
2758
2759 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2760 if (Result == 0) break; // Cannot compute!
2761
2762 // Evaluate the condition for this iteration.
2763 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2764 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2765 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2766#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002767 errs() << "\n***\n*** Computed loop count " << *ItCst
2768 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2769 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002770#endif
2771 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002772 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002773 }
2774 }
Dan Gohman0c850912009-06-06 14:37:11 +00002775 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002776}
2777
2778
2779/// CanConstantFold - Return true if we can constant fold an instruction of the
2780/// specified type, assuming that all operands were constants.
2781static bool CanConstantFold(const Instruction *I) {
2782 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2783 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2784 return true;
2785
2786 if (const CallInst *CI = dyn_cast<CallInst>(I))
2787 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002788 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002789 return false;
2790}
2791
2792/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2793/// in the loop that V is derived from. We allow arbitrary operations along the
2794/// way, but the operands of an operation must either be constants or a value
2795/// derived from a constant PHI. If this expression does not fit with these
2796/// constraints, return null.
2797static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2798 // If this is not an instruction, or if this is an instruction outside of the
2799 // loop, it can't be derived from a loop PHI.
2800 Instruction *I = dyn_cast<Instruction>(V);
2801 if (I == 0 || !L->contains(I->getParent())) return 0;
2802
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002803 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002804 if (L->getHeader() == I->getParent())
2805 return PN;
2806 else
2807 // We don't currently keep track of the control flow needed to evaluate
2808 // PHIs, so we cannot handle PHIs inside of loops.
2809 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002810 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002811
2812 // If we won't be able to constant fold this expression even if the operands
2813 // are constants, return early.
2814 if (!CanConstantFold(I)) return 0;
2815
2816 // Otherwise, we can evaluate this instruction if all of its operands are
2817 // constant or derived from a PHI node themselves.
2818 PHINode *PHI = 0;
2819 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2820 if (!(isa<Constant>(I->getOperand(Op)) ||
2821 isa<GlobalValue>(I->getOperand(Op)))) {
2822 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2823 if (P == 0) return 0; // Not evolving from PHI
2824 if (PHI == 0)
2825 PHI = P;
2826 else if (PHI != P)
2827 return 0; // Evolving from multiple different PHIs.
2828 }
2829
2830 // This is a expression evolving from a constant PHI!
2831 return PHI;
2832}
2833
2834/// EvaluateExpression - Given an expression that passes the
2835/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2836/// in the loop has the value PHIVal. If we can't fold this expression for some
2837/// reason, return null.
2838static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2839 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002840 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002841 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002842 Instruction *I = cast<Instruction>(V);
2843
2844 std::vector<Constant*> Operands;
2845 Operands.resize(I->getNumOperands());
2846
2847 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2848 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2849 if (Operands[i] == 0) return 0;
2850 }
2851
Chris Lattnerd6e56912007-12-10 22:53:04 +00002852 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2853 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2854 &Operands[0], Operands.size());
2855 else
2856 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2857 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002858}
2859
2860/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2861/// in the header of its containing loop, we know the loop executes a
2862/// constant number of times, and the PHI node is just a recurrence
2863/// involving constants, fold it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002864Constant *ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002865getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002866 std::map<PHINode*, Constant*>::iterator I =
2867 ConstantEvolutionLoopExitValue.find(PN);
2868 if (I != ConstantEvolutionLoopExitValue.end())
2869 return I->second;
2870
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002871 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002872 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2873
2874 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2875
2876 // Since the loop is canonicalized, the PHI node must have two entries. One
2877 // entry must be a constant (coming in from outside of the loop), and the
2878 // second must be derived from the same PHI.
2879 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2880 Constant *StartCST =
2881 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2882 if (StartCST == 0)
2883 return RetVal = 0; // Must be a constant.
2884
2885 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2886 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2887 if (PN2 != PN)
2888 return RetVal = 0; // Not derived from same PHI.
2889
2890 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002891 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002892 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2893
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002894 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002895 unsigned IterationNum = 0;
2896 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2897 if (IterationNum == NumIterations)
2898 return RetVal = PHIVal; // Got exit value!
2899
2900 // Compute the value of the PHI node for the next iteration.
2901 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2902 if (NextPHI == PHIVal)
2903 return RetVal = NextPHI; // Stopped evolving!
2904 if (NextPHI == 0)
2905 return 0; // Couldn't evaluate!
2906 PHIVal = NextPHI;
2907 }
2908}
2909
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002910/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002911/// constant number of times (the condition evolves only from constants),
2912/// try to evaluate a few iterations of the loop until we get the exit
2913/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman0c850912009-06-06 14:37:11 +00002914/// evaluate the trip count of the loop, return CouldNotCompute.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002915SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002916ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002917 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman0c850912009-06-06 14:37:11 +00002918 if (PN == 0) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002919
2920 // Since the loop is canonicalized, the PHI node must have two entries. One
2921 // entry must be a constant (coming in from outside of the loop), and the
2922 // second must be derived from the same PHI.
2923 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2924 Constant *StartCST =
2925 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman0c850912009-06-06 14:37:11 +00002926 if (StartCST == 0) return CouldNotCompute; // Must be a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002927
2928 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2929 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman0c850912009-06-06 14:37:11 +00002930 if (PN2 != PN) return CouldNotCompute; // Not derived from same PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002931
2932 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2933 // the loop symbolically to determine when the condition gets a value of
2934 // "ExitWhen".
2935 unsigned IterationNum = 0;
2936 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2937 for (Constant *PHIVal = StartCST;
2938 IterationNum != MaxIterations; ++IterationNum) {
2939 ConstantInt *CondVal =
2940 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2941
2942 // Couldn't symbolically evaluate.
Dan Gohman0c850912009-06-06 14:37:11 +00002943 if (!CondVal) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002944
2945 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2946 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2947 ++NumBruteForceTripCountsComputed;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002948 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002949 }
2950
2951 // Compute the value of the PHI node for the next iteration.
2952 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2953 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman0c850912009-06-06 14:37:11 +00002954 return CouldNotCompute; // Couldn't evaluate or not making progress...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002955 PHIVal = NextPHI;
2956 }
2957
2958 // Too many iterations were needed to evaluate.
Dan Gohman0c850912009-06-06 14:37:11 +00002959 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002960}
2961
Dan Gohmandd40e9a2009-05-08 20:38:54 +00002962/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2963/// at the specified scope in the program. The L value specifies a loop
2964/// nest to evaluate the expression at, where null is the top-level or a
2965/// specified loop is immediately inside of the loop.
2966///
2967/// This method can be used to compute the exit value for a variable defined
2968/// in a loop by querying what the value will hold in the parent loop.
2969///
Dan Gohmanaff14d62009-05-24 23:25:42 +00002970/// In the case that a relevant loop exit value cannot be computed, the
2971/// original value V is returned.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002972SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002973 // FIXME: this should be turned into a virtual method on SCEV!
2974
2975 if (isa<SCEVConstant>(V)) return V;
2976
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002977 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002978 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002979 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002980 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002981 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002982 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2983 if (PHINode *PN = dyn_cast<PHINode>(I))
2984 if (PN->getParent() == LI->getHeader()) {
2985 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002986 // to see if the loop that contains it has a known backedge-taken
2987 // count. If so, we may be able to force computation of the exit
2988 // value.
2989 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002990 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002991 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002992 // Okay, we know how many times the containing loop executes. If
2993 // this is a constant evolving PHI node, get the final value at
2994 // the specified iteration number.
2995 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002996 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002997 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002998 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002999 }
3000 }
3001
3002 // Okay, this is an expression that we cannot symbolically evaluate
3003 // into a SCEV. Check to see if it's possible to symbolically evaluate
3004 // the arguments into constants, and if so, try to constant propagate the
3005 // result. This is particularly useful for computing loop exit values.
3006 if (CanConstantFold(I)) {
Dan Gohmanda0071e2009-05-08 20:47:27 +00003007 // Check to see if we've folded this instruction at this loop before.
3008 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3009 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3010 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3011 if (!Pair.second)
3012 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
3013
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003014 std::vector<Constant*> Operands;
3015 Operands.reserve(I->getNumOperands());
3016 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3017 Value *Op = I->getOperand(i);
3018 if (Constant *C = dyn_cast<Constant>(Op)) {
3019 Operands.push_back(C);
3020 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00003021 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00003022 // non-integer and non-pointer, don't even try to analyze them
3023 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00003024 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00003025 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003026
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003027 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003028 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003029 Constant *C = SC->getValue();
3030 if (C->getType() != Op->getType())
3031 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3032 Op->getType(),
3033 false),
3034 C, Op->getType());
3035 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003036 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003037 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3038 if (C->getType() != Op->getType())
3039 C =
3040 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3041 Op->getType(),
3042 false),
3043 C, Op->getType());
3044 Operands.push_back(C);
3045 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003046 return V;
3047 } else {
3048 return V;
3049 }
3050 }
3051 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00003052
3053 Constant *C;
3054 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3055 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3056 &Operands[0], Operands.size());
3057 else
3058 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3059 &Operands[0], Operands.size());
Dan Gohmanda0071e2009-05-08 20:47:27 +00003060 Pair.first->second = C;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003061 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003062 }
3063 }
3064
3065 // This is some other type of SCEVUnknown, just return it.
3066 return V;
3067 }
3068
Dan Gohmanc76b5452009-05-04 22:02:23 +00003069 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003070 // Avoid performing the look-up in the common case where the specified
3071 // expression has no loop-variant portions.
3072 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
3073 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3074 if (OpAtScope != Comm->getOperand(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003075 // Okay, at least one of these operands is loop variant but might be
3076 // foldable. Build a new instance of the folded commutative expression.
3077 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
3078 NewOps.push_back(OpAtScope);
3079
3080 for (++i; i != e; ++i) {
3081 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003082 NewOps.push_back(OpAtScope);
3083 }
3084 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003085 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003086 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003087 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003088 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003089 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003090 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003091 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003092 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003093 }
3094 }
3095 // If we got here, all operands are loop invariant.
3096 return Comm;
3097 }
3098
Dan Gohmanc76b5452009-05-04 22:02:23 +00003099 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003100 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003101 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003102 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3103 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003104 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003105 }
3106
3107 // If this is a loop recurrence for a loop that does not contain L, then we
3108 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003109 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003110 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3111 // To evaluate this recurrence, we need to know how many times the AddRec
3112 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003113 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman0c850912009-06-06 14:37:11 +00003114 if (BackedgeTakenCount == CouldNotCompute) return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003115
Eli Friedman7489ec92008-08-04 23:49:06 +00003116 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003117 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003118 }
Dan Gohmanaff14d62009-05-24 23:25:42 +00003119 return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003120 }
3121
Dan Gohmanc76b5452009-05-04 22:02:23 +00003122 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003123 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003124 if (Op == Cast->getOperand())
3125 return Cast; // must be loop invariant
3126 return getZeroExtendExpr(Op, Cast->getType());
3127 }
3128
Dan Gohmanc76b5452009-05-04 22:02:23 +00003129 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003130 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003131 if (Op == Cast->getOperand())
3132 return Cast; // must be loop invariant
3133 return getSignExtendExpr(Op, Cast->getType());
3134 }
3135
Dan Gohmanc76b5452009-05-04 22:02:23 +00003136 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003137 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003138 if (Op == Cast->getOperand())
3139 return Cast; // must be loop invariant
3140 return getTruncateExpr(Op, Cast->getType());
3141 }
3142
3143 assert(0 && "Unknown SCEV type!");
Daniel Dunbara95d96c2009-05-18 16:43:04 +00003144 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003145}
3146
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003147/// getSCEVAtScope - This is a convenience function which does
3148/// getSCEVAtScope(getSCEV(V), L).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003149SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
3150 return getSCEVAtScope(getSCEV(V), L);
3151}
3152
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003153/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3154/// following equation:
3155///
3156/// A * X = B (mod N)
3157///
3158/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3159/// A and B isn't important.
3160///
3161/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
3162static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
3163 ScalarEvolution &SE) {
3164 uint32_t BW = A.getBitWidth();
3165 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3166 assert(A != 0 && "A must be non-zero.");
3167
3168 // 1. D = gcd(A, N)
3169 //
3170 // The gcd of A and N may have only one prime factor: 2. The number of
3171 // trailing zeros in A is its multiplicity
3172 uint32_t Mult2 = A.countTrailingZeros();
3173 // D = 2^Mult2
3174
3175 // 2. Check if B is divisible by D.
3176 //
3177 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3178 // is not less than multiplicity of this prime factor for D.
3179 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00003180 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003181
3182 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3183 // modulo (N / D).
3184 //
3185 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3186 // bit width during computations.
3187 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3188 APInt Mod(BW + 1, 0);
3189 Mod.set(BW - Mult2); // Mod = N / D
3190 APInt I = AD.multiplicativeInverse(Mod);
3191
3192 // 4. Compute the minimum unsigned root of the equation:
3193 // I * (B / D) mod (N / D)
3194 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3195
3196 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3197 // bits.
3198 return SE.getConstant(Result.trunc(BW));
3199}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003200
3201/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3202/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3203/// might be the same) or two SCEVCouldNotCompute objects.
3204///
3205static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00003206SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003207 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00003208 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3209 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3210 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003211
3212 // We currently can only solve this if the coefficients are constants.
3213 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003214 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003215 return std::make_pair(CNC, CNC);
3216 }
3217
3218 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3219 const APInt &L = LC->getValue()->getValue();
3220 const APInt &M = MC->getValue()->getValue();
3221 const APInt &N = NC->getValue()->getValue();
3222 APInt Two(BitWidth, 2);
3223 APInt Four(BitWidth, 4);
3224
3225 {
3226 using namespace APIntOps;
3227 const APInt& C = L;
3228 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3229 // The B coefficient is M-N/2
3230 APInt B(M);
3231 B -= sdiv(N,Two);
3232
3233 // The A coefficient is N/2
3234 APInt A(N.sdiv(Two));
3235
3236 // Compute the B^2-4ac term.
3237 APInt SqrtTerm(B);
3238 SqrtTerm *= B;
3239 SqrtTerm -= Four * (A * C);
3240
3241 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3242 // integer value or else APInt::sqrt() will assert.
3243 APInt SqrtVal(SqrtTerm.sqrt());
3244
3245 // Compute the two solutions for the quadratic formula.
3246 // The divisions must be performed as signed divisions.
3247 APInt NegB(-B);
3248 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00003249 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003250 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00003251 return std::make_pair(CNC, CNC);
3252 }
3253
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003254 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3255 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
3256
Dan Gohman89f85052007-10-22 18:31:58 +00003257 return std::make_pair(SE.getConstant(Solution1),
3258 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003259 } // end APIntOps namespace
3260}
3261
3262/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman0c850912009-06-06 14:37:11 +00003263/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohmanbff6b582009-05-04 22:30:44 +00003264SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003265 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00003266 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003267 // If the value is already zero, the branch will execute zero times.
3268 if (C->getValue()->isZero()) return C;
Dan Gohman0c850912009-06-06 14:37:11 +00003269 return CouldNotCompute; // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003270 }
3271
Dan Gohmanbff6b582009-05-04 22:30:44 +00003272 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003273 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman0c850912009-06-06 14:37:11 +00003274 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003275
3276 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003277 // If this is an affine expression, the execution count of this branch is
3278 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003279 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003280 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003281 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003282 // equivalent to:
3283 //
3284 // Step*N = -Start (mod 2^BW)
3285 //
3286 // where BW is the common bit width of Start and Step.
3287
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003288 // Get the initial value for the loop.
3289 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003290 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003291
Dan Gohmanc76b5452009-05-04 22:02:23 +00003292 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003293 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003294
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003295 // First, handle unitary steps.
3296 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003297 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003298 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3299 return Start; // N = Start (as unsigned)
3300
3301 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003302 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003303 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003304 -StartC->getValue()->getValue(),
3305 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003306 }
3307 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3308 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3309 // the quadratic equation to solve it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003310 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
3311 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003312 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3313 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003314 if (R1) {
3315#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003316 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3317 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003318#endif
3319 // Pick the smallest positive root value.
3320 if (ConstantInt *CB =
3321 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3322 R1->getValue(), R2->getValue()))) {
3323 if (CB->getZExtValue() == false)
3324 std::swap(R1, R2); // R1 is the minimum root now.
3325
3326 // We can only use this value if the chrec ends up with an exact zero
3327 // value at this index. When solving for "X*X != 5", for example, we
3328 // should not accept a root of 2.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003329 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00003330 if (Val->isZero())
3331 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003332 }
3333 }
3334 }
3335
Dan Gohman0c850912009-06-06 14:37:11 +00003336 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003337}
3338
3339/// HowFarToNonZero - Return the number of times a backedge checking the
3340/// specified value for nonzero will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00003341/// CouldNotCompute
Dan Gohmanbff6b582009-05-04 22:30:44 +00003342SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003343 // Loops that look like: while (X == 0) are very strange indeed. We don't
3344 // handle them yet except for the trivial case. This could be expanded in the
3345 // future as needed.
3346
3347 // If the value is a constant, check to see if it is known to be non-zero
3348 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003349 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00003350 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003351 return getIntegerSCEV(0, C->getType());
Dan Gohman0c850912009-06-06 14:37:11 +00003352 return CouldNotCompute; // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003353 }
3354
3355 // We could implement others, but I really doubt anyone writes loops like
3356 // this, and if they did, they would already be constant folded.
Dan Gohman0c850912009-06-06 14:37:11 +00003357 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003358}
3359
Dan Gohmanab157b22009-05-18 15:36:09 +00003360/// getLoopPredecessor - If the given loop's header has exactly one unique
3361/// predecessor outside the loop, return it. Otherwise return null.
3362///
3363BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3364 BasicBlock *Header = L->getHeader();
3365 BasicBlock *Pred = 0;
3366 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3367 PI != E; ++PI)
3368 if (!L->contains(*PI)) {
3369 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3370 Pred = *PI;
3371 }
3372 return Pred;
3373}
3374
Dan Gohman1cddf972008-09-15 22:18:04 +00003375/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3376/// (which may not be an immediate predecessor) which has exactly one
3377/// successor from which BB is reachable, or null if no such block is
3378/// found.
3379///
3380BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003381ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00003382 // If the block has a unique predecessor, then there is no path from the
3383 // predecessor to the block that does not go through the direct edge
3384 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00003385 if (BasicBlock *Pred = BB->getSinglePredecessor())
3386 return Pred;
3387
3388 // A loop's header is defined to be a block that dominates the loop.
Dan Gohmanab157b22009-05-18 15:36:09 +00003389 // If the header has a unique predecessor outside the loop, it must be
3390 // a block that has exactly one successor that can reach the loop.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003391 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanab157b22009-05-18 15:36:09 +00003392 return getLoopPredecessor(L);
Dan Gohman1cddf972008-09-15 22:18:04 +00003393
3394 return 0;
3395}
3396
Dan Gohmancacd2012009-02-12 22:19:27 +00003397/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman1116ea72009-04-30 20:48:53 +00003398/// a conditional between LHS and RHS. This is used to help avoid max
3399/// expressions in loop trip counts.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003400bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman1116ea72009-04-30 20:48:53 +00003401 ICmpInst::Predicate Pred,
Dan Gohmanbff6b582009-05-04 22:30:44 +00003402 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8b938182009-05-18 16:03:58 +00003403 // Interpret a null as meaning no loop, where there is obviously no guard
3404 // (interprocedural conditions notwithstanding).
3405 if (!L) return false;
3406
Dan Gohmanab157b22009-05-18 15:36:09 +00003407 BasicBlock *Predecessor = getLoopPredecessor(L);
3408 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003409
Dan Gohmanab157b22009-05-18 15:36:09 +00003410 // Starting at the loop predecessor, climb up the predecessor chain, as long
3411 // as there are predecessors that can be found that have unique successors
Dan Gohman1cddf972008-09-15 22:18:04 +00003412 // leading to the original header.
Dan Gohmanab157b22009-05-18 15:36:09 +00003413 for (; Predecessor;
3414 PredecessorDest = Predecessor,
3415 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00003416
3417 BranchInst *LoopEntryPredicate =
Dan Gohmanab157b22009-05-18 15:36:09 +00003418 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00003419 if (!LoopEntryPredicate ||
3420 LoopEntryPredicate->isUnconditional())
3421 continue;
3422
3423 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3424 if (!ICI) continue;
3425
3426 // Now that we found a conditional branch that dominates the loop, check to
3427 // see if it is the comparison we are looking for.
3428 Value *PreCondLHS = ICI->getOperand(0);
3429 Value *PreCondRHS = ICI->getOperand(1);
3430 ICmpInst::Predicate Cond;
Dan Gohmanab157b22009-05-18 15:36:09 +00003431 if (LoopEntryPredicate->getSuccessor(0) == PredecessorDest)
Dan Gohmanab678fb2008-08-12 20:17:31 +00003432 Cond = ICI->getPredicate();
3433 else
3434 Cond = ICI->getInversePredicate();
3435
Dan Gohmancacd2012009-02-12 22:19:27 +00003436 if (Cond == Pred)
3437 ; // An exact match.
3438 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3439 ; // The actual condition is beyond sufficient.
3440 else
3441 // Check a few special cases.
3442 switch (Cond) {
3443 case ICmpInst::ICMP_UGT:
3444 if (Pred == ICmpInst::ICMP_ULT) {
3445 std::swap(PreCondLHS, PreCondRHS);
3446 Cond = ICmpInst::ICMP_ULT;
3447 break;
3448 }
3449 continue;
3450 case ICmpInst::ICMP_SGT:
3451 if (Pred == ICmpInst::ICMP_SLT) {
3452 std::swap(PreCondLHS, PreCondRHS);
3453 Cond = ICmpInst::ICMP_SLT;
3454 break;
3455 }
3456 continue;
3457 case ICmpInst::ICMP_NE:
3458 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3459 // so check for this case by checking if the NE is comparing against
3460 // a minimum or maximum constant.
3461 if (!ICmpInst::isTrueWhenEqual(Pred))
3462 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3463 const APInt &A = CI->getValue();
3464 switch (Pred) {
3465 case ICmpInst::ICMP_SLT:
3466 if (A.isMaxSignedValue()) break;
3467 continue;
3468 case ICmpInst::ICMP_SGT:
3469 if (A.isMinSignedValue()) break;
3470 continue;
3471 case ICmpInst::ICMP_ULT:
3472 if (A.isMaxValue()) break;
3473 continue;
3474 case ICmpInst::ICMP_UGT:
3475 if (A.isMinValue()) break;
3476 continue;
3477 default:
3478 continue;
3479 }
3480 Cond = ICmpInst::ICMP_NE;
3481 // NE is symmetric but the original comparison may not be. Swap
3482 // the operands if necessary so that they match below.
3483 if (isa<SCEVConstant>(LHS))
3484 std::swap(PreCondLHS, PreCondRHS);
3485 break;
3486 }
3487 continue;
3488 default:
3489 // We weren't able to reconcile the condition.
3490 continue;
3491 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003492
3493 if (!PreCondLHS->getType()->isInteger()) continue;
3494
3495 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3496 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3497 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003498 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3499 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohmanab678fb2008-08-12 20:17:31 +00003500 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003501 }
3502
Dan Gohmanab678fb2008-08-12 20:17:31 +00003503 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003504}
3505
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003506/// HowManyLessThans - Return the number of times a backedge containing the
3507/// specified less-than comparison will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00003508/// CouldNotCompute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003509ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Dan Gohmanbff6b582009-05-04 22:30:44 +00003510HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3511 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003512 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman0c850912009-06-06 14:37:11 +00003513 if (!RHS->isLoopInvariant(L)) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003514
Dan Gohmanbff6b582009-05-04 22:30:44 +00003515 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003516 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman0c850912009-06-06 14:37:11 +00003517 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003518
3519 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003520 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003521 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3522 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3523 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3524
3525 // TODO: handle non-constant strides.
3526 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3527 if (!CStep || CStep->isZero())
Dan Gohman0c850912009-06-06 14:37:11 +00003528 return CouldNotCompute;
Dan Gohmanf8bc8e82009-05-18 15:22:39 +00003529 if (CStep->isOne()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003530 // With unit stride, the iteration never steps past the limit value.
3531 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3532 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3533 // Test whether a positive iteration iteration can step past the limit
3534 // value and past the maximum value for its type in a single step.
3535 if (isSigned) {
3536 APInt Max = APInt::getSignedMaxValue(BitWidth);
3537 if ((Max - CStep->getValue()->getValue())
3538 .slt(CLimit->getValue()->getValue()))
Dan Gohman0c850912009-06-06 14:37:11 +00003539 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003540 } else {
3541 APInt Max = APInt::getMaxValue(BitWidth);
3542 if ((Max - CStep->getValue()->getValue())
3543 .ult(CLimit->getValue()->getValue()))
Dan Gohman0c850912009-06-06 14:37:11 +00003544 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003545 }
3546 } else
3547 // TODO: handle non-constant limit values below.
Dan Gohman0c850912009-06-06 14:37:11 +00003548 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003549 } else
3550 // TODO: handle negative strides below.
Dan Gohman0c850912009-06-06 14:37:11 +00003551 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003552
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003553 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3554 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3555 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00003556 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003557
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003558 // First, we get the value of the LHS in the first iteration: n
3559 SCEVHandle Start = AddRec->getOperand(0);
3560
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003561 // Determine the minimum constant start value.
3562 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3563 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3564 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003565
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003566 // If we know that the condition is true in order to enter the loop,
3567 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohmanc8a29272009-05-24 23:45:28 +00003568 // only know that it will execute (max(m,n)-n)/s times. In both cases,
3569 // the division must round up.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003570 SCEVHandle End = RHS;
3571 if (!isLoopGuardedByCond(L,
3572 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3573 getMinusSCEV(Start, Step), RHS))
3574 End = isSigned ? getSMaxExpr(RHS, Start)
3575 : getUMaxExpr(RHS, Start);
3576
3577 // Determine the maximum constant end value.
3578 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3579 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3580 APInt::getMaxValue(BitWidth));
3581
3582 // Finally, we subtract these two values and divide, rounding up, to get
3583 // the number of times the backedge is executed.
3584 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3585 getAddExpr(Step, NegOne)),
3586 Step);
3587
3588 // The maximum backedge count is similar, except using the minimum start
3589 // value and the maximum end value.
3590 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3591 MinStart),
3592 getAddExpr(Step, NegOne)),
3593 Step);
3594
3595 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003596 }
3597
Dan Gohman0c850912009-06-06 14:37:11 +00003598 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003599}
3600
3601/// getNumIterationsInRange - Return the number of iterations of this loop that
3602/// produce values in the specified constant range. Another way of looking at
3603/// this is that it returns the first iteration number where the value is not in
3604/// the condition, thus computing the exit count. If the iteration count can't
3605/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00003606SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3607 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003608 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003609 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003610
3611 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003612 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003613 if (!SC->getValue()->isZero()) {
3614 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003615 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3616 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00003617 if (const SCEVAddRecExpr *ShiftedAddRec =
3618 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003619 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003620 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003621 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003622 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003623 }
3624
3625 // The only time we can solve this is when we have all constant indices.
3626 // Otherwise, we cannot determine the overflow conditions.
3627 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3628 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003629 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003630
3631
3632 // Okay at this point we know that all elements of the chrec are constants and
3633 // that the start element is zero.
3634
3635 // First check to see if the range contains zero. If not, the first
3636 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003637 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003638 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003639 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003640
3641 if (isAffine()) {
3642 // If this is an affine expression then we have this situation:
3643 // Solve {0,+,A} in Range === Ax in Range
3644
3645 // We know that zero is in the range. If A is positive then we know that
3646 // the upper value of the range must be the first possible exit value.
3647 // If A is negative then the lower of the range is the last possible loop
3648 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003649 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003650 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3651 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3652
3653 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003654 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003655 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3656
3657 // Evaluate at the exit value. If we really did fall out of the valid
3658 // range, then we computed our trip count, otherwise wrap around or other
3659 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003660 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003661 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003662 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003663
3664 // Ensure that the previous value is in the range. This is a sanity check.
3665 assert(Range.contains(
3666 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003667 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003668 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003669 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003670 } else if (isQuadratic()) {
3671 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3672 // quadratic equation to solve it. To do this, we must frame our problem in
3673 // terms of figuring out when zero is crossed, instead of when
3674 // Range.getUpper() is crossed.
3675 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003676 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3677 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003678
3679 // Next, solve the constructed addrec
3680 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003681 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003682 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3683 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003684 if (R1) {
3685 // Pick the smallest positive root value.
3686 if (ConstantInt *CB =
3687 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3688 R1->getValue(), R2->getValue()))) {
3689 if (CB->getZExtValue() == false)
3690 std::swap(R1, R2); // R1 is the minimum root now.
3691
3692 // Make sure the root is not off by one. The returned iteration should
3693 // not be in the range, but the previous one should be. When solving
3694 // for "X*X < 5", for example, we should not return a root of 2.
3695 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003696 R1->getValue(),
3697 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003698 if (Range.contains(R1Val->getValue())) {
3699 // The next iteration must be out of the range...
3700 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3701
Dan Gohman89f85052007-10-22 18:31:58 +00003702 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003703 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003704 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003705 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003706 }
3707
3708 // If R1 was not in the range, then it is a good return value. Make
3709 // sure that R1-1 WAS in the range though, just in case.
3710 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003711 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003712 if (Range.contains(R1Val->getValue()))
3713 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003714 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003715 }
3716 }
3717 }
3718
Dan Gohman0ad08b02009-04-18 17:58:19 +00003719 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003720}
3721
3722
3723
3724//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00003725// SCEVCallbackVH Class Implementation
3726//===----------------------------------------------------------------------===//
3727
Dan Gohman999d14e2009-05-19 19:22:47 +00003728void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003729 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3730 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3731 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003732 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
3733 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003734 SE->Scalars.erase(getValPtr());
3735 // this now dangles!
3736}
3737
Dan Gohman999d14e2009-05-19 19:22:47 +00003738void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003739 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3740
3741 // Forget all the expressions associated with users of the old value,
3742 // so that future queries will recompute the expressions using the new
3743 // value.
3744 SmallVector<User *, 16> Worklist;
3745 Value *Old = getValPtr();
3746 bool DeleteOld = false;
3747 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3748 UI != UE; ++UI)
3749 Worklist.push_back(*UI);
3750 while (!Worklist.empty()) {
3751 User *U = Worklist.pop_back_val();
3752 // Deleting the Old value will cause this to dangle. Postpone
3753 // that until everything else is done.
3754 if (U == Old) {
3755 DeleteOld = true;
3756 continue;
3757 }
3758 if (PHINode *PN = dyn_cast<PHINode>(U))
3759 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003760 if (Instruction *I = dyn_cast<Instruction>(U))
3761 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003762 if (SE->Scalars.erase(U))
3763 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3764 UI != UE; ++UI)
3765 Worklist.push_back(*UI);
3766 }
3767 if (DeleteOld) {
3768 if (PHINode *PN = dyn_cast<PHINode>(Old))
3769 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003770 if (Instruction *I = dyn_cast<Instruction>(Old))
3771 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003772 SE->Scalars.erase(Old);
3773 // this now dangles!
3774 }
3775 // this may dangle!
3776}
3777
Dan Gohman999d14e2009-05-19 19:22:47 +00003778ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohmanbff6b582009-05-04 22:30:44 +00003779 : CallbackVH(V), SE(se) {}
3780
3781//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003782// ScalarEvolution Class Implementation
3783//===----------------------------------------------------------------------===//
3784
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003785ScalarEvolution::ScalarEvolution()
Dan Gohman0c850912009-06-06 14:37:11 +00003786 : FunctionPass(&ID), CouldNotCompute(new SCEVCouldNotCompute()) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003787}
3788
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003789bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003790 this->F = &F;
3791 LI = &getAnalysis<LoopInfo>();
3792 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003793 return false;
3794}
3795
3796void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003797 Scalars.clear();
3798 BackedgeTakenCounts.clear();
3799 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanda0071e2009-05-08 20:47:27 +00003800 ValuesAtScopes.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003801}
3802
3803void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3804 AU.setPreservesAll();
3805 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003806}
3807
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003808bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003809 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003810}
3811
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003812static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003813 const Loop *L) {
3814 // Print all inner loops first
3815 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3816 PrintLoopInfo(OS, SE, *I);
3817
Nick Lewyckye5da1912008-01-02 02:49:20 +00003818 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003819
Devang Patel02451fa2007-08-21 00:31:24 +00003820 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003821 L->getExitBlocks(ExitBlocks);
3822 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003823 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003824
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003825 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3826 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003827 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003828 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003829 }
3830
Nick Lewyckye5da1912008-01-02 02:49:20 +00003831 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003832}
3833
Dan Gohman13058cc2009-04-21 00:47:46 +00003834void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003835 // ScalarEvolution's implementaiton of the print method is to print
3836 // out SCEV values of all instructions that are interesting. Doing
3837 // this potentially causes it to create new SCEV objects though,
3838 // which technically conflicts with the const qualifier. This isn't
3839 // observable from outside the class though (the hasSCEV function
3840 // notwithstanding), so casting away the const isn't dangerous.
3841 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003842
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003843 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003844 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00003845 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003846 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003847 OS << " --> ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003848 SCEVHandle SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003849 SV->print(OS);
3850 OS << "\t\t";
3851
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003852 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003853 OS << "Exits: ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003854 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmanaff14d62009-05-24 23:25:42 +00003855 if (!ExitValue->isLoopInvariant(L)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003856 OS << "<<Unknown>>";
3857 } else {
3858 OS << *ExitValue;
3859 }
3860 }
3861
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003862 OS << "\n";
3863 }
3864
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003865 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3866 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3867 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003868}
Dan Gohman13058cc2009-04-21 00:47:46 +00003869
3870void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3871 raw_os_ostream OS(o);
3872 print(OS, M);
3873}