blob: 26010ebaa2fe3b7626d103b6d00edbb8bb58e4fd [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
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.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000031//
Chris Lattner53e677a2004-04-02 20:23:17 +000032// 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//
Chris Lattner53e677a2004-04-02 20:23:17 +000036// 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
Chris Lattner3b27d682006-12-19 22:30:33 +000062#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000063#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000064#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000066#include "llvm/GlobalVariable.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
John Criswella1156432005-10-27 15:54:34 +000068#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000069#include "llvm/Analysis/LoopInfo.h"
70#include "llvm/Assembly/Writer.h"
71#include "llvm/Transforms/Scalar.h"
72#include "llvm/Support/CFG.h"
Chris Lattner95255282006-06-28 23:17:24 +000073#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000074#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000075#include "llvm/Support/ConstantRange.h"
76#include "llvm/Support/InstIterator.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000077#include "llvm/Support/ManagedStatic.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000078#include "llvm/Support/MathExtras.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000079#include "llvm/Support/Streams.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000080#include "llvm/ADT/Statistic.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000081#include <ostream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000082#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000083#include <cmath>
Chris Lattner53e677a2004-04-02 20:23:17 +000084using namespace llvm;
85
Chris Lattner3b27d682006-12-19 22:30:33 +000086STATISTIC(NumBruteForceEvaluations,
87 "Number of brute force evaluations needed to "
88 "calculate high-order polynomial exit values");
89STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
97
Dan Gohman844731a2008-05-13 00:00:25 +000098static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +000099MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
101 "symbolically execute a constant derived loop"),
102 cl::init(100));
103
Dan Gohman844731a2008-05-13 00:00:25 +0000104static RegisterPass<ScalarEvolution>
105R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000106char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000107
108//===----------------------------------------------------------------------===//
109// SCEV class definitions
110//===----------------------------------------------------------------------===//
111
112//===----------------------------------------------------------------------===//
113// Implementation of the SCEV class.
114//
Chris Lattner53e677a2004-04-02 20:23:17 +0000115SCEV::~SCEV() {}
116void SCEV::dump() const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000117 print(cerr);
Chris Lattner53e677a2004-04-02 20:23:17 +0000118}
119
120/// getValueRange - Return the tightest constant bounds that this value is
121/// known to have. This method is only valid on integer SCEV objects.
122ConstantRange SCEV::getValueRange() const {
123 const Type *Ty = getType();
Chris Lattner42a75512007-01-15 02:27:26 +0000124 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000125 // Default to a full range if no better information is available.
Reid Spencerc6aedf72007-02-28 22:03:51 +0000126 return ConstantRange(getBitWidth());
Chris Lattner53e677a2004-04-02 20:23:17 +0000127}
128
Reid Spencer581b0d42007-02-28 19:57:34 +0000129uint32_t SCEV::getBitWidth() const {
130 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
131 return ITy->getBitWidth();
132 return 0;
133}
134
Chris Lattner53e677a2004-04-02 20:23:17 +0000135
136SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
137
138bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
139 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000140 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000141}
142
143const Type *SCEVCouldNotCompute::getType() const {
144 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000145 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000146}
147
148bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
149 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
150 return false;
151}
152
Chris Lattner4dc534c2005-02-13 04:37:18 +0000153SCEVHandle SCEVCouldNotCompute::
154replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000155 const SCEVHandle &Conc,
156 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000157 return this;
158}
159
Chris Lattner53e677a2004-04-02 20:23:17 +0000160void SCEVCouldNotCompute::print(std::ostream &OS) const {
161 OS << "***COULDNOTCOMPUTE***";
162}
163
164bool SCEVCouldNotCompute::classof(const SCEV *S) {
165 return S->getSCEVType() == scCouldNotCompute;
166}
167
168
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000169// 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!
Chris Lattnerb3364092006-10-04 21:49:37 +0000172static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000173
Chris Lattner53e677a2004-04-02 20:23:17 +0000174
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000175SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000176 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000177}
Chris Lattner53e677a2004-04-02 20:23:17 +0000178
Dan Gohman246b2562007-10-22 18:31:58 +0000179SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Chris Lattnerb3364092006-10-04 21:49:37 +0000180 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000181 if (R == 0) R = new SCEVConstant(V);
182 return R;
183}
Chris Lattner53e677a2004-04-02 20:23:17 +0000184
Dan Gohman246b2562007-10-22 18:31:58 +0000185SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
186 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000187}
188
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000189ConstantRange SCEVConstant::getValueRange() const {
Reid Spencerdc5c1592007-02-28 18:57:32 +0000190 return ConstantRange(V->getValue());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000191}
Chris Lattner53e677a2004-04-02 20:23:17 +0000192
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000193const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000194
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000195void SCEVConstant::print(std::ostream &OS) const {
196 WriteAsOperand(OS, V, false);
197}
Chris Lattner53e677a2004-04-02 20:23:17 +0000198
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000199// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
200// particular input. Don't use a SCEVHandle here, or else the object will
201// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000202static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
203 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000204
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000205SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
206 : SCEV(scTruncate), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000207 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000208 "Cannot truncate non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000209 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
210 && "This is not a truncating conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000211}
Chris Lattner53e677a2004-04-02 20:23:17 +0000212
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000213SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000214 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000215}
Chris Lattner53e677a2004-04-02 20:23:17 +0000216
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000217ConstantRange SCEVTruncateExpr::getValueRange() const {
Reid Spencerc6aedf72007-02-28 22:03:51 +0000218 return getOperand()->getValueRange().truncate(getBitWidth());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219}
Chris Lattner53e677a2004-04-02 20:23:17 +0000220
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000221void SCEVTruncateExpr::print(std::ostream &OS) const {
222 OS << "(truncate " << *Op << " to " << *Ty << ")";
223}
224
225// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
226// particular input. Don't use a SCEVHandle here, or else the object will never
227// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000228static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
229 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000230
231SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000232 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000233 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000234 "Cannot zero extend non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000235 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
236 && "This is not an extending conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000237}
238
239SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000240 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000241}
242
243ConstantRange SCEVZeroExtendExpr::getValueRange() const {
Reid Spencerc6aedf72007-02-28 22:03:51 +0000244 return getOperand()->getValueRange().zeroExtend(getBitWidth());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000245}
246
247void SCEVZeroExtendExpr::print(std::ostream &OS) const {
248 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
249}
250
Dan Gohmand19534a2007-06-15 14:38:12 +0000251// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
252// particular input. Don't use a SCEVHandle here, or else the object will never
253// be deleted!
254static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
255 SCEVSignExtendExpr*> > SCEVSignExtends;
256
257SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
258 : SCEV(scSignExtend), Op(op), Ty(ty) {
259 assert(Op->getType()->isInteger() && Ty->isInteger() &&
260 "Cannot sign extend non-integer value!");
261 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
262 && "This is not an extending conversion!");
263}
264
265SCEVSignExtendExpr::~SCEVSignExtendExpr() {
266 SCEVSignExtends->erase(std::make_pair(Op, Ty));
267}
268
269ConstantRange SCEVSignExtendExpr::getValueRange() const {
270 return getOperand()->getValueRange().signExtend(getBitWidth());
271}
272
273void SCEVSignExtendExpr::print(std::ostream &OS) const {
274 OS << "(signextend " << *Op << " to " << *Ty << ")";
275}
276
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000277// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
278// particular input. Don't use a SCEVHandle here, or else the object will never
279// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000280static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
281 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000282
283SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000284 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
285 std::vector<SCEV*>(Operands.begin(),
286 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000287}
288
289void SCEVCommutativeExpr::print(std::ostream &OS) const {
290 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
291 const char *OpStr = getOperationStr();
292 OS << "(" << *Operands[0];
293 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
294 OS << OpStr << *Operands[i];
295 OS << ")";
296}
297
Chris Lattner4dc534c2005-02-13 04:37:18 +0000298SCEVHandle SCEVCommutativeExpr::
299replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000300 const SCEVHandle &Conc,
301 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000302 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000303 SCEVHandle H =
304 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000305 if (H != getOperand(i)) {
306 std::vector<SCEVHandle> NewOps;
307 NewOps.reserve(getNumOperands());
308 for (unsigned j = 0; j != i; ++j)
309 NewOps.push_back(getOperand(j));
310 NewOps.push_back(H);
311 for (++i; i != e; ++i)
312 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000313 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000314
315 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000316 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000317 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000318 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000319 else if (isa<SCEVSMaxExpr>(this))
320 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000321 else if (isa<SCEVUMaxExpr>(this))
322 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000323 else
324 assert(0 && "Unknown commutative expr!");
325 }
326 }
327 return this;
328}
329
330
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000331// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000332// input. Don't use a SCEVHandle here, or else the object will never be
333// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000334static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000335 SCEVUDivExpr*> > SCEVUDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000336
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000337SCEVUDivExpr::~SCEVUDivExpr() {
338 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000339}
340
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000341void SCEVUDivExpr::print(std::ostream &OS) const {
342 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000343}
344
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000345const Type *SCEVUDivExpr::getType() const {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000346 return LHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000347}
348
349// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
350// particular input. Don't use a SCEVHandle here, or else the object will never
351// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000352static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
353 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000354
355SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000356 SCEVAddRecExprs->erase(std::make_pair(L,
357 std::vector<SCEV*>(Operands.begin(),
358 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000359}
360
Chris Lattner4dc534c2005-02-13 04:37:18 +0000361SCEVHandle SCEVAddRecExpr::
362replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000363 const SCEVHandle &Conc,
364 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000365 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000366 SCEVHandle H =
367 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000368 if (H != getOperand(i)) {
369 std::vector<SCEVHandle> NewOps;
370 NewOps.reserve(getNumOperands());
371 for (unsigned j = 0; j != i; ++j)
372 NewOps.push_back(getOperand(j));
373 NewOps.push_back(H);
374 for (++i; i != e; ++i)
375 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000376 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000377
Dan Gohman246b2562007-10-22 18:31:58 +0000378 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000379 }
380 }
381 return this;
382}
383
384
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000385bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
386 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000387 // contain L and if the start is invariant.
388 return !QueryLoop->contains(L->getHeader()) &&
389 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000390}
391
392
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000393void SCEVAddRecExpr::print(std::ostream &OS) const {
394 OS << "{" << *Operands[0];
395 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
396 OS << ",+," << *Operands[i];
397 OS << "}<" << L->getHeader()->getName() + ">";
398}
Chris Lattner53e677a2004-04-02 20:23:17 +0000399
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000400// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
401// value. Don't use a SCEVHandle here, or else the object will never be
402// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000403static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000404
Chris Lattnerb3364092006-10-04 21:49:37 +0000405SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000406
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000407bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
408 // All non-instruction values are loop invariant. All instructions are loop
409 // invariant if they are not contained in the specified loop.
410 if (Instruction *I = dyn_cast<Instruction>(V))
411 return !L->contains(I->getParent());
412 return true;
413}
Chris Lattner53e677a2004-04-02 20:23:17 +0000414
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000415const Type *SCEVUnknown::getType() const {
416 return V->getType();
417}
Chris Lattner53e677a2004-04-02 20:23:17 +0000418
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000419void SCEVUnknown::print(std::ostream &OS) const {
420 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000421}
422
Chris Lattner8d741b82004-06-20 06:23:15 +0000423//===----------------------------------------------------------------------===//
424// SCEV Utilities
425//===----------------------------------------------------------------------===//
426
427namespace {
428 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
429 /// than the complexity of the RHS. This comparator is used to canonicalize
430 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000431 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000432 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Chris Lattner8d741b82004-06-20 06:23:15 +0000433 return LHS->getSCEVType() < RHS->getSCEVType();
434 }
435 };
436}
437
438/// GroupByComplexity - Given a list of SCEV objects, order them by their
439/// complexity, and group objects of the same complexity together by value.
440/// When this routine is finished, we know that any duplicates in the vector are
441/// consecutive and that complexity is monotonically increasing.
442///
443/// Note that we go take special precautions to ensure that we get determinstic
444/// results from this routine. In other words, we don't want the results of
445/// this to depend on where the addresses of various SCEV objects happened to
446/// land in memory.
447///
448static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
449 if (Ops.size() < 2) return; // Noop
450 if (Ops.size() == 2) {
451 // This is the common case, which also happens to be trivially simple.
452 // Special case it.
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000453 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000454 std::swap(Ops[0], Ops[1]);
455 return;
456 }
457
458 // Do the rough sort by complexity.
459 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
460
461 // Now that we are sorted by complexity, group elements of the same
462 // complexity. Note that this is, at worst, N^2, but the vector is likely to
463 // be extremely short in practice. Note that we take this approach because we
464 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000465 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000466 SCEV *S = Ops[i];
467 unsigned Complexity = S->getSCEVType();
468
469 // If there are any objects of the same complexity and same value as this
470 // one, group them.
471 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
472 if (Ops[j] == S) { // Found a duplicate.
473 // Move it to immediately after i'th element.
474 std::swap(Ops[i+1], Ops[j]);
475 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000476 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000477 }
478 }
479 }
480}
481
Chris Lattner53e677a2004-04-02 20:23:17 +0000482
Chris Lattner53e677a2004-04-02 20:23:17 +0000483
484//===----------------------------------------------------------------------===//
485// Simple SCEV method implementations
486//===----------------------------------------------------------------------===//
487
488/// getIntegerSCEV - Given an integer or FP type, create a constant for the
489/// specified signed integer value and return a SCEV for the constant.
Dan Gohman246b2562007-10-22 18:31:58 +0000490SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000491 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000492 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000493 C = Constant::getNullValue(Ty);
494 else if (Ty->isFloatingPoint())
Chris Lattner02a260a2008-04-20 00:41:09 +0000495 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
496 APFloat::IEEEdouble, Val));
Reid Spencere4d87aa2006-12-23 06:05:41 +0000497 else
Reid Spencerb83eb642006-10-20 07:07:24 +0000498 C = ConstantInt::get(Ty, Val);
Dan Gohman246b2562007-10-22 18:31:58 +0000499 return getUnknown(C);
Chris Lattner53e677a2004-04-02 20:23:17 +0000500}
501
502/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
503/// input value to the specified type. If the type must be extended, it is zero
504/// extended.
Dan Gohman246b2562007-10-22 18:31:58 +0000505static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty,
506 ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000507 const Type *SrcTy = V->getType();
Chris Lattner42a75512007-01-15 02:27:26 +0000508 assert(SrcTy->isInteger() && Ty->isInteger() &&
Chris Lattner53e677a2004-04-02 20:23:17 +0000509 "Cannot truncate or zero extend with non-integer arguments!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000510 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
Chris Lattner53e677a2004-04-02 20:23:17 +0000511 return V; // No conversion
Reid Spencere7ca0422007-01-08 01:26:33 +0000512 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
Dan Gohman246b2562007-10-22 18:31:58 +0000513 return SE.getTruncateExpr(V, Ty);
514 return SE.getZeroExtendExpr(V, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000515}
516
517/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
518///
Dan Gohman246b2562007-10-22 18:31:58 +0000519SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000520 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman246b2562007-10-22 18:31:58 +0000521 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000522
Nick Lewycky178f20a2008-02-20 06:58:55 +0000523 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
Nick Lewycky3e630762008-02-20 06:48:22 +0000524}
525
526/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
527SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
528 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
529 return getUnknown(ConstantExpr::getNot(VC->getValue()));
530
Nick Lewycky178f20a2008-02-20 06:58:55 +0000531 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
Nick Lewycky3e630762008-02-20 06:48:22 +0000532 return getMinusSCEV(AllOnes, V);
Chris Lattner53e677a2004-04-02 20:23:17 +0000533}
534
535/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
536///
Dan Gohman246b2562007-10-22 18:31:58 +0000537SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
538 const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000539 // X - Y --> X + -Y
Dan Gohman246b2562007-10-22 18:31:58 +0000540 return getAddExpr(LHS, getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000541}
542
543
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000544/// BinomialCoefficient - Compute BC(It, K). The result is of the same type as
545/// It. Assume, K > 0.
546static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
547 ScalarEvolution &SE) {
548 // We are using the following formula for BC(It, K):
549 //
550 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
551 //
552 // Suppose, W is the bitwidth of It (and of the return value as well). We
553 // must be prepared for overflow. Hence, we must assure that the result of
554 // our computation is equal to the accurate one modulo 2^W. Unfortunately,
555 // division isn't safe in modular arithmetic. This means we must perform the
556 // whole computation accurately and then truncate the result to W bits.
557 //
558 // The dividend of the formula is a multiplication of K integers of bitwidth
559 // W. K*W bits suffice to compute it accurately.
560 //
561 // FIXME: We assume the divisor can be accurately computed using 16-bit
562 // unsigned integer type. It is true up to K = 8 (AddRecs of length 9). In
563 // future we may use APInt to use the minimum number of bits necessary to
564 // compute it accurately.
565 //
566 // It is safe to use unsigned division here: the dividend is nonnegative and
567 // the divisor is positive.
568
569 // Handle the simplest case efficiently.
570 if (K == 1)
571 return It;
572
573 assert(K < 9 && "We cannot handle such long AddRecs yet.");
574
575 // FIXME: A temporary hack to remove in future. Arbitrary precision integers
576 // aren't supported by the code generator yet. For the dividend, the bitwidth
577 // we use is the smallest power of 2 greater or equal to K*W and less or equal
578 // to 64. Note that setting the upper bound for bitwidth may still lead to
579 // miscompilation in some cases.
580 unsigned DividendBits = 1U << Log2_32_Ceil(K * It->getBitWidth());
581 if (DividendBits > 64)
582 DividendBits = 64;
583#if 0 // Waiting for the APInt support in the code generator...
584 unsigned DividendBits = K * It->getBitWidth();
585#endif
586
587 const IntegerType *DividendTy = IntegerType::get(DividendBits);
588 const SCEVHandle ExIt = SE.getZeroExtendExpr(It, DividendTy);
589
590 // The final number of bits we need to perform the division is the maximum of
591 // dividend and divisor bitwidths.
592 const IntegerType *DivisionTy =
593 IntegerType::get(std::max(DividendBits, 16U));
594
595 // Compute K! We know K >= 2 here.
596 unsigned F = 2;
597 for (unsigned i = 3; i <= K; ++i)
598 F *= i;
599 APInt Divisor(DivisionTy->getBitWidth(), F);
600
Chris Lattner53e677a2004-04-02 20:23:17 +0000601 // Handle this case efficiently, it is common to have constant iteration
602 // counts while computing loop exit values.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000603 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(ExIt)) {
604 const APInt& N = SC->getValue()->getValue();
605 APInt Dividend(N.getBitWidth(), 1);
606 for (; K; --K)
607 Dividend *= N-(K-1);
608 if (DividendTy != DivisionTy)
609 Dividend = Dividend.zext(DivisionTy->getBitWidth());
610 return SE.getConstant(Dividend.udiv(Divisor).trunc(It->getBitWidth()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000611 }
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000612
613 SCEVHandle Dividend = ExIt;
614 for (unsigned i = 1; i != K; ++i)
615 Dividend =
616 SE.getMulExpr(Dividend,
617 SE.getMinusSCEV(ExIt, SE.getIntegerSCEV(i, DividendTy)));
618 if (DividendTy != DivisionTy)
619 Dividend = SE.getZeroExtendExpr(Dividend, DivisionTy);
620 return
621 SE.getTruncateExpr(SE.getUDivExpr(Dividend, SE.getConstant(Divisor)),
622 It->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +0000623}
624
Chris Lattner53e677a2004-04-02 20:23:17 +0000625/// evaluateAtIteration - Return the value of this chain of recurrences at
626/// the specified iteration number. We can evaluate this recurrence by
627/// multiplying each element in the chain by the binomial coefficient
628/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
629///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000630/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000631///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000632/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000633///
Dan Gohman246b2562007-10-22 18:31:58 +0000634SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
635 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000636 SCEVHandle Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000637 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000638 // The computation is correct in the face of overflow provided that the
639 // multiplication is performed _after_ the evaluation of the binomial
640 // coefficient.
641 SCEVHandle Val = SE.getMulExpr(getOperand(i),
642 BinomialCoefficient(It, i, SE));
Dan Gohman246b2562007-10-22 18:31:58 +0000643 Result = SE.getAddExpr(Result, Val);
Chris Lattner53e677a2004-04-02 20:23:17 +0000644 }
645 return Result;
646}
647
Chris Lattner53e677a2004-04-02 20:23:17 +0000648//===----------------------------------------------------------------------===//
649// SCEV Expression folder implementations
650//===----------------------------------------------------------------------===//
651
Dan Gohman246b2562007-10-22 18:31:58 +0000652SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000653 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000654 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000655 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000656
657 // If the input value is a chrec scev made out of constants, truncate
658 // all of the constants.
659 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
660 std::vector<SCEVHandle> Operands;
661 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
662 // FIXME: This should allow truncation of other expression types!
663 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman246b2562007-10-22 18:31:58 +0000664 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000665 else
666 break;
667 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman246b2562007-10-22 18:31:58 +0000668 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000669 }
670
Chris Lattnerb3364092006-10-04 21:49:37 +0000671 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000672 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
673 return Result;
674}
675
Dan Gohman246b2562007-10-22 18:31:58 +0000676SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000677 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000678 return getUnknown(
Reid Spencerd977d862006-12-12 23:36:14 +0000679 ConstantExpr::getZExt(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000680
681 // FIXME: If the input value is a chrec scev, and we can prove that the value
682 // did not overflow the old, smaller, value, we can zero extend all of the
683 // operands (often constants). This would allow analysis of something like
684 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
685
Chris Lattnerb3364092006-10-04 21:49:37 +0000686 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000687 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
688 return Result;
689}
690
Dan Gohman246b2562007-10-22 18:31:58 +0000691SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmand19534a2007-06-15 14:38:12 +0000692 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000693 return getUnknown(
Dan Gohmand19534a2007-06-15 14:38:12 +0000694 ConstantExpr::getSExt(SC->getValue(), Ty));
695
696 // FIXME: If the input value is a chrec scev, and we can prove that the value
697 // did not overflow the old, smaller, value, we can sign extend all of the
698 // operands (often constants). This would allow analysis of something like
699 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
700
701 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
702 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
703 return Result;
704}
705
Chris Lattner53e677a2004-04-02 20:23:17 +0000706// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman246b2562007-10-22 18:31:58 +0000707SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000708 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000709 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000710
711 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000712 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000713
714 // If there are any constants, fold them together.
715 unsigned Idx = 0;
716 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
717 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000718 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000719 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
720 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000721 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
722 RHSC->getValue()->getValue());
723 Ops[0] = getConstant(Fold);
724 Ops.erase(Ops.begin()+1); // Erase the folded element
725 if (Ops.size() == 1) return Ops[0];
726 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000727 }
728
729 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +0000730 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000731 Ops.erase(Ops.begin());
732 --Idx;
733 }
734 }
735
Chris Lattner627018b2004-04-07 16:16:11 +0000736 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000737
Chris Lattner53e677a2004-04-02 20:23:17 +0000738 // Okay, check to see if the same value occurs in the operand list twice. If
739 // so, merge them together into an multiply expression. Since we sorted the
740 // list, these values are required to be adjacent.
741 const Type *Ty = Ops[0]->getType();
742 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
743 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
744 // Found a match, merge the two values into a multiply, and add any
745 // remaining values to the result.
Dan Gohman246b2562007-10-22 18:31:58 +0000746 SCEVHandle Two = getIntegerSCEV(2, Ty);
747 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +0000748 if (Ops.size() == 2)
749 return Mul;
750 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
751 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +0000752 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000753 }
754
Dan Gohmanf50cd742007-06-18 19:30:09 +0000755 // Now we know the first non-constant operand. Skip past any cast SCEVs.
756 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
757 ++Idx;
758
759 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +0000760 if (Idx < Ops.size()) {
761 bool DeletedAdd = false;
762 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
763 // If we have an add, expand the add operands onto the end of the operands
764 // list.
765 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
766 Ops.erase(Ops.begin()+Idx);
767 DeletedAdd = true;
768 }
769
770 // If we deleted at least one add, we added operands to the end of the list,
771 // and they are not necessarily sorted. Recurse to resort and resimplify
772 // any operands we just aquired.
773 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +0000774 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000775 }
776
777 // Skip over the add expression until we get to a multiply.
778 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
779 ++Idx;
780
781 // If we are adding something to a multiply expression, make sure the
782 // something is not already an operand of the multiply. If so, merge it into
783 // the multiply.
784 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
785 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
786 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
787 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
788 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000789 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000790 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
791 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
792 if (Mul->getNumOperands() != 2) {
793 // If the multiply has more than two operands, we must get the
794 // Y*Z term.
795 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
796 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000797 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000798 }
Dan Gohman246b2562007-10-22 18:31:58 +0000799 SCEVHandle One = getIntegerSCEV(1, Ty);
800 SCEVHandle AddOne = getAddExpr(InnerMul, One);
801 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000802 if (Ops.size() == 2) return OuterMul;
803 if (AddOp < Idx) {
804 Ops.erase(Ops.begin()+AddOp);
805 Ops.erase(Ops.begin()+Idx-1);
806 } else {
807 Ops.erase(Ops.begin()+Idx);
808 Ops.erase(Ops.begin()+AddOp-1);
809 }
810 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000811 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000812 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000813
Chris Lattner53e677a2004-04-02 20:23:17 +0000814 // Check this multiply against other multiplies being added together.
815 for (unsigned OtherMulIdx = Idx+1;
816 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
817 ++OtherMulIdx) {
818 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
819 // If MulOp occurs in OtherMul, we can fold the two multiplies
820 // together.
821 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
822 OMulOp != e; ++OMulOp)
823 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
824 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
825 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
826 if (Mul->getNumOperands() != 2) {
827 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
828 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000829 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000830 }
831 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
832 if (OtherMul->getNumOperands() != 2) {
833 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
834 OtherMul->op_end());
835 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000836 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000837 }
Dan Gohman246b2562007-10-22 18:31:58 +0000838 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
839 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +0000840 if (Ops.size() == 2) return OuterMul;
841 Ops.erase(Ops.begin()+Idx);
842 Ops.erase(Ops.begin()+OtherMulIdx-1);
843 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000844 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000845 }
846 }
847 }
848 }
849
850 // If there are any add recurrences in the operands list, see if any other
851 // added values are loop invariant. If so, we can fold them into the
852 // recurrence.
853 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
854 ++Idx;
855
856 // Scan over all recurrences, trying to fold loop invariants into them.
857 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
858 // Scan all of the other operands to this add and add them to the vector if
859 // they are loop invariant w.r.t. the recurrence.
860 std::vector<SCEVHandle> LIOps;
861 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
862 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
863 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
864 LIOps.push_back(Ops[i]);
865 Ops.erase(Ops.begin()+i);
866 --i; --e;
867 }
868
869 // If we found some loop invariants, fold them into the recurrence.
870 if (!LIOps.empty()) {
871 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
872 LIOps.push_back(AddRec->getStart());
873
874 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +0000875 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000876
Dan Gohman246b2562007-10-22 18:31:58 +0000877 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000878 // If all of the other operands were loop invariant, we are done.
879 if (Ops.size() == 1) return NewRec;
880
881 // Otherwise, add the folded AddRec by the non-liv parts.
882 for (unsigned i = 0;; ++i)
883 if (Ops[i] == AddRec) {
884 Ops[i] = NewRec;
885 break;
886 }
Dan Gohman246b2562007-10-22 18:31:58 +0000887 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000888 }
889
890 // Okay, if there weren't any loop invariants to be folded, check to see if
891 // there are multiple AddRec's with the same loop induction variable being
892 // added together. If so, we can fold them.
893 for (unsigned OtherIdx = Idx+1;
894 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
895 if (OtherIdx != Idx) {
896 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
897 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
898 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
899 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
900 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
901 if (i >= NewOps.size()) {
902 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
903 OtherAddRec->op_end());
904 break;
905 }
Dan Gohman246b2562007-10-22 18:31:58 +0000906 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +0000907 }
Dan Gohman246b2562007-10-22 18:31:58 +0000908 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000909
910 if (Ops.size() == 2) return NewAddRec;
911
912 Ops.erase(Ops.begin()+Idx);
913 Ops.erase(Ops.begin()+OtherIdx-1);
914 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +0000915 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000916 }
917 }
918
919 // Otherwise couldn't fold anything into this recurrence. Move onto the
920 // next one.
921 }
922
923 // Okay, it looks like we really DO need an add expr. Check to see if we
924 // already have one, otherwise create a new one.
925 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000926 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
927 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000928 if (Result == 0) Result = new SCEVAddExpr(Ops);
929 return Result;
930}
931
932
Dan Gohman246b2562007-10-22 18:31:58 +0000933SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000934 assert(!Ops.empty() && "Cannot get empty mul!");
935
936 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000937 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000938
939 // If there are any constants, fold them together.
940 unsigned Idx = 0;
941 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
942
943 // C1*(C2+V) -> C1*C2 + C1*V
944 if (Ops.size() == 2)
945 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
946 if (Add->getNumOperands() == 2 &&
947 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +0000948 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
949 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000950
951
952 ++Idx;
953 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
954 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000955 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
956 RHSC->getValue()->getValue());
957 Ops[0] = getConstant(Fold);
958 Ops.erase(Ops.begin()+1); // Erase the folded element
959 if (Ops.size() == 1) return Ops[0];
960 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000961 }
962
963 // If we are left with a constant one being multiplied, strip it off.
964 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
965 Ops.erase(Ops.begin());
966 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +0000967 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000968 // If we have a multiply of zero, it will always be zero.
969 return Ops[0];
970 }
971 }
972
973 // Skip over the add expression until we get to a multiply.
974 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
975 ++Idx;
976
977 if (Ops.size() == 1)
978 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000979
Chris Lattner53e677a2004-04-02 20:23:17 +0000980 // If there are mul operands inline them all into this expression.
981 if (Idx < Ops.size()) {
982 bool DeletedMul = false;
983 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
984 // If we have an mul, expand the mul operands onto the end of the operands
985 // list.
986 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
987 Ops.erase(Ops.begin()+Idx);
988 DeletedMul = true;
989 }
990
991 // If we deleted at least one mul, we added operands to the end of the list,
992 // and they are not necessarily sorted. Recurse to resort and resimplify
993 // any operands we just aquired.
994 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +0000995 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000996 }
997
998 // If there are any add recurrences in the operands list, see if any other
999 // added values are loop invariant. If so, we can fold them into the
1000 // recurrence.
1001 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1002 ++Idx;
1003
1004 // Scan over all recurrences, trying to fold loop invariants into them.
1005 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1006 // Scan all of the other operands to this mul and add them to the vector if
1007 // they are loop invariant w.r.t. the recurrence.
1008 std::vector<SCEVHandle> LIOps;
1009 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1010 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1011 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1012 LIOps.push_back(Ops[i]);
1013 Ops.erase(Ops.begin()+i);
1014 --i; --e;
1015 }
1016
1017 // If we found some loop invariants, fold them into the recurrence.
1018 if (!LIOps.empty()) {
1019 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
1020 std::vector<SCEVHandle> NewOps;
1021 NewOps.reserve(AddRec->getNumOperands());
1022 if (LIOps.size() == 1) {
1023 SCEV *Scale = LIOps[0];
1024 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001025 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001026 } else {
1027 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1028 std::vector<SCEVHandle> MulOps(LIOps);
1029 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001030 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001031 }
1032 }
1033
Dan Gohman246b2562007-10-22 18:31:58 +00001034 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001035
1036 // If all of the other operands were loop invariant, we are done.
1037 if (Ops.size() == 1) return NewRec;
1038
1039 // Otherwise, multiply the folded AddRec by the non-liv parts.
1040 for (unsigned i = 0;; ++i)
1041 if (Ops[i] == AddRec) {
1042 Ops[i] = NewRec;
1043 break;
1044 }
Dan Gohman246b2562007-10-22 18:31:58 +00001045 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001046 }
1047
1048 // Okay, if there weren't any loop invariants to be folded, check to see if
1049 // there are multiple AddRec's with the same loop induction variable being
1050 // multiplied together. If so, we can fold them.
1051 for (unsigned OtherIdx = Idx+1;
1052 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1053 if (OtherIdx != Idx) {
1054 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1055 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1056 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1057 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman246b2562007-10-22 18:31:58 +00001058 SCEVHandle NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001059 G->getStart());
Dan Gohman246b2562007-10-22 18:31:58 +00001060 SCEVHandle B = F->getStepRecurrence(*this);
1061 SCEVHandle D = G->getStepRecurrence(*this);
1062 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1063 getMulExpr(G, B),
1064 getMulExpr(B, D));
1065 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1066 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001067 if (Ops.size() == 2) return NewAddRec;
1068
1069 Ops.erase(Ops.begin()+Idx);
1070 Ops.erase(Ops.begin()+OtherIdx-1);
1071 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001072 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001073 }
1074 }
1075
1076 // Otherwise couldn't fold anything into this recurrence. Move onto the
1077 // next one.
1078 }
1079
1080 // Okay, it looks like we really DO need an mul expr. Check to see if we
1081 // already have one, otherwise create a new one.
1082 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001083 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1084 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001085 if (Result == 0)
1086 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001087 return Result;
1088}
1089
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001090SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001091 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1092 if (RHSC->getValue()->equalsInt(1))
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001093 return LHS; // X udiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +00001094
1095 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1096 Constant *LHSCV = LHSC->getValue();
1097 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001098 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001099 }
1100 }
1101
1102 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1103
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001104 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1105 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001106 return Result;
1107}
1108
1109
1110/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1111/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001112SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Chris Lattner53e677a2004-04-02 20:23:17 +00001113 const SCEVHandle &Step, const Loop *L) {
1114 std::vector<SCEVHandle> Operands;
1115 Operands.push_back(Start);
1116 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1117 if (StepChrec->getLoop() == L) {
1118 Operands.insert(Operands.end(), StepChrec->op_begin(),
1119 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001120 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001121 }
1122
1123 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001124 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001125}
1126
1127/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1128/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001129SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Chris Lattner53e677a2004-04-02 20:23:17 +00001130 const Loop *L) {
1131 if (Operands.size() == 1) return Operands[0];
1132
1133 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
Reid Spencercae57542007-03-02 00:28:52 +00001134 if (StepC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001135 Operands.pop_back();
Dan Gohman246b2562007-10-22 18:31:58 +00001136 return getAddRecExpr(Operands, L); // { X,+,0 } --> X
Chris Lattner53e677a2004-04-02 20:23:17 +00001137 }
1138
1139 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001140 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1141 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001142 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1143 return Result;
1144}
1145
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001146SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1147 const SCEVHandle &RHS) {
1148 std::vector<SCEVHandle> Ops;
1149 Ops.push_back(LHS);
1150 Ops.push_back(RHS);
1151 return getSMaxExpr(Ops);
1152}
1153
1154SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1155 assert(!Ops.empty() && "Cannot get empty smax!");
1156 if (Ops.size() == 1) return Ops[0];
1157
1158 // Sort by complexity, this groups all similar expression types together.
1159 GroupByComplexity(Ops);
1160
1161 // If there are any constants, fold them together.
1162 unsigned Idx = 0;
1163 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1164 ++Idx;
1165 assert(Idx < Ops.size());
1166 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1167 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001168 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001169 APIntOps::smax(LHSC->getValue()->getValue(),
1170 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001171 Ops[0] = getConstant(Fold);
1172 Ops.erase(Ops.begin()+1); // Erase the folded element
1173 if (Ops.size() == 1) return Ops[0];
1174 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001175 }
1176
1177 // If we are left with a constant -inf, strip it off.
1178 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1179 Ops.erase(Ops.begin());
1180 --Idx;
1181 }
1182 }
1183
1184 if (Ops.size() == 1) return Ops[0];
1185
1186 // Find the first SMax
1187 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1188 ++Idx;
1189
1190 // Check to see if one of the operands is an SMax. If so, expand its operands
1191 // onto our operand list, and recurse to simplify.
1192 if (Idx < Ops.size()) {
1193 bool DeletedSMax = false;
1194 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1195 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1196 Ops.erase(Ops.begin()+Idx);
1197 DeletedSMax = true;
1198 }
1199
1200 if (DeletedSMax)
1201 return getSMaxExpr(Ops);
1202 }
1203
1204 // Okay, check to see if the same value occurs in the operand list twice. If
1205 // so, delete one. Since we sorted the list, these values are required to
1206 // be adjacent.
1207 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1208 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1209 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1210 --i; --e;
1211 }
1212
1213 if (Ops.size() == 1) return Ops[0];
1214
1215 assert(!Ops.empty() && "Reduced smax down to nothing!");
1216
Nick Lewycky3e630762008-02-20 06:48:22 +00001217 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001218 // already have one, otherwise create a new one.
1219 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1220 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1221 SCEVOps)];
1222 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1223 return Result;
1224}
1225
Nick Lewycky3e630762008-02-20 06:48:22 +00001226SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1227 const SCEVHandle &RHS) {
1228 std::vector<SCEVHandle> Ops;
1229 Ops.push_back(LHS);
1230 Ops.push_back(RHS);
1231 return getUMaxExpr(Ops);
1232}
1233
1234SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1235 assert(!Ops.empty() && "Cannot get empty umax!");
1236 if (Ops.size() == 1) return Ops[0];
1237
1238 // Sort by complexity, this groups all similar expression types together.
1239 GroupByComplexity(Ops);
1240
1241 // If there are any constants, fold them together.
1242 unsigned Idx = 0;
1243 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1244 ++Idx;
1245 assert(Idx < Ops.size());
1246 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1247 // We found two constants, fold them together!
1248 ConstantInt *Fold = ConstantInt::get(
1249 APIntOps::umax(LHSC->getValue()->getValue(),
1250 RHSC->getValue()->getValue()));
1251 Ops[0] = getConstant(Fold);
1252 Ops.erase(Ops.begin()+1); // Erase the folded element
1253 if (Ops.size() == 1) return Ops[0];
1254 LHSC = cast<SCEVConstant>(Ops[0]);
1255 }
1256
1257 // If we are left with a constant zero, strip it off.
1258 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1259 Ops.erase(Ops.begin());
1260 --Idx;
1261 }
1262 }
1263
1264 if (Ops.size() == 1) return Ops[0];
1265
1266 // Find the first UMax
1267 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1268 ++Idx;
1269
1270 // Check to see if one of the operands is a UMax. If so, expand its operands
1271 // onto our operand list, and recurse to simplify.
1272 if (Idx < Ops.size()) {
1273 bool DeletedUMax = false;
1274 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1275 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1276 Ops.erase(Ops.begin()+Idx);
1277 DeletedUMax = true;
1278 }
1279
1280 if (DeletedUMax)
1281 return getUMaxExpr(Ops);
1282 }
1283
1284 // Okay, check to see if the same value occurs in the operand list twice. If
1285 // so, delete one. Since we sorted the list, these values are required to
1286 // be adjacent.
1287 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1288 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1289 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1290 --i; --e;
1291 }
1292
1293 if (Ops.size() == 1) return Ops[0];
1294
1295 assert(!Ops.empty() && "Reduced umax down to nothing!");
1296
1297 // Okay, it looks like we really DO need a umax expr. Check to see if we
1298 // already have one, otherwise create a new one.
1299 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1300 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1301 SCEVOps)];
1302 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1303 return Result;
1304}
1305
Dan Gohman246b2562007-10-22 18:31:58 +00001306SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001307 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001308 return getConstant(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001309 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001310 if (Result == 0) Result = new SCEVUnknown(V);
1311 return Result;
1312}
1313
Chris Lattner53e677a2004-04-02 20:23:17 +00001314
1315//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001316// ScalarEvolutionsImpl Definition and Implementation
1317//===----------------------------------------------------------------------===//
1318//
1319/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1320/// evolution code.
1321///
1322namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001323 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohman246b2562007-10-22 18:31:58 +00001324 /// SE - A reference to the public ScalarEvolution object.
1325 ScalarEvolution &SE;
1326
Chris Lattner53e677a2004-04-02 20:23:17 +00001327 /// F - The function we are analyzing.
1328 ///
1329 Function &F;
1330
1331 /// LI - The loop information for the function we are currently analyzing.
1332 ///
1333 LoopInfo &LI;
1334
1335 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1336 /// things.
1337 SCEVHandle UnknownValue;
1338
1339 /// Scalars - This is a cache of the scalars we have analyzed so far.
1340 ///
1341 std::map<Value*, SCEVHandle> Scalars;
1342
1343 /// IterationCounts - Cache the iteration count of the loops for this
1344 /// function as they are computed.
1345 std::map<const Loop*, SCEVHandle> IterationCounts;
1346
Chris Lattner3221ad02004-04-17 22:58:41 +00001347 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1348 /// the PHI instructions that we attempt to compute constant evolutions for.
1349 /// This allows us to avoid potentially expensive recomputation of these
1350 /// properties. An instruction maps to null if we are unable to compute its
1351 /// exit value.
1352 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001353
Chris Lattner53e677a2004-04-02 20:23:17 +00001354 public:
Dan Gohman246b2562007-10-22 18:31:58 +00001355 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1356 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
Chris Lattner53e677a2004-04-02 20:23:17 +00001357
1358 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1359 /// expression and create a new one.
1360 SCEVHandle getSCEV(Value *V);
1361
Chris Lattnera0740fb2005-08-09 23:36:33 +00001362 /// hasSCEV - Return true if the SCEV for this value has already been
1363 /// computed.
1364 bool hasSCEV(Value *V) const {
1365 return Scalars.count(V);
1366 }
1367
1368 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1369 /// the specified value.
1370 void setSCEV(Value *V, const SCEVHandle &H) {
1371 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1372 assert(isNew && "This entry already existed!");
1373 }
1374
1375
Chris Lattner53e677a2004-04-02 20:23:17 +00001376 /// getSCEVAtScope - Compute the value of the specified expression within
1377 /// the indicated loop (which may be null to indicate in no loop). If the
1378 /// expression cannot be evaluated, return UnknownValue itself.
1379 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1380
1381
1382 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1383 /// an analyzable loop-invariant iteration count.
1384 bool hasLoopInvariantIterationCount(const Loop *L);
1385
1386 /// getIterationCount - If the specified loop has a predictable iteration
1387 /// count, return it. Note that it is not valid to call this method on a
1388 /// loop without a loop-invariant iteration count.
1389 SCEVHandle getIterationCount(const Loop *L);
1390
Dan Gohman5cec4db2007-06-19 14:28:31 +00001391 /// deleteValueFromRecords - This method should be called by the
1392 /// client before it removes a value from the program, to make sure
Chris Lattner53e677a2004-04-02 20:23:17 +00001393 /// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001394 void deleteValueFromRecords(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001395
1396 private:
1397 /// createSCEV - We know that there is no SCEV for the specified value.
1398 /// Analyze the expression.
1399 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001400
1401 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1402 /// SCEVs.
1403 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001404
1405 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1406 /// for the specified instruction and replaces any references to the
1407 /// symbolic value SymName with the specified value. This is used during
1408 /// PHI resolution.
1409 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1410 const SCEVHandle &SymName,
1411 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001412
1413 /// ComputeIterationCount - Compute the number of times the specified loop
1414 /// will iterate.
1415 SCEVHandle ComputeIterationCount(const Loop *L);
1416
Chris Lattner673e02b2004-10-12 01:49:27 +00001417 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001418 /// 'icmp op load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00001419 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1420 Constant *RHS,
1421 const Loop *L,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001422 ICmpInst::Predicate p);
Chris Lattner673e02b2004-10-12 01:49:27 +00001423
Chris Lattner7980fb92004-04-17 18:36:24 +00001424 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1425 /// constant number of times (the condition evolves only from constants),
1426 /// try to evaluate a few iterations of the loop until we get the exit
1427 /// condition gets a value of ExitWhen (true or false). If we cannot
1428 /// evaluate the trip count of the loop, return UnknownValue.
1429 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1430 bool ExitWhen);
1431
Chris Lattner53e677a2004-04-02 20:23:17 +00001432 /// HowFarToZero - Return the number of times a backedge comparing the
1433 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001434 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001435 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1436
1437 /// HowFarToNonZero - Return the number of times a backedge checking the
1438 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001439 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001440 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001441
Chris Lattnerdb25de42005-08-15 23:33:51 +00001442 /// HowManyLessThans - Return the number of times a backedge containing the
1443 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001444 /// UnknownValue. isSigned specifies whether the less-than is signed.
1445 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1446 bool isSigned);
Chris Lattnerdb25de42005-08-15 23:33:51 +00001447
Chris Lattner3221ad02004-04-17 22:58:41 +00001448 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1449 /// in the header of its containing loop, we know the loop executes a
1450 /// constant number of times, and the PHI node is just a recurrence
1451 /// involving constants, fold it.
Reid Spencere8019bb2007-03-01 07:25:48 +00001452 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
Chris Lattner3221ad02004-04-17 22:58:41 +00001453 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001454 };
1455}
1456
1457//===----------------------------------------------------------------------===//
1458// Basic SCEV Analysis and PHI Idiom Recognition Code
1459//
1460
Dan Gohman5cec4db2007-06-19 14:28:31 +00001461/// deleteValueFromRecords - This method should be called by the
Chris Lattner53e677a2004-04-02 20:23:17 +00001462/// client before it removes an instruction from the program, to make sure
1463/// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001464void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1465 SmallVector<Value *, 16> Worklist;
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001466
Dan Gohman5cec4db2007-06-19 14:28:31 +00001467 if (Scalars.erase(V)) {
1468 if (PHINode *PN = dyn_cast<PHINode>(V))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001469 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman5cec4db2007-06-19 14:28:31 +00001470 Worklist.push_back(V);
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001471 }
1472
1473 while (!Worklist.empty()) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001474 Value *VV = Worklist.back();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001475 Worklist.pop_back();
1476
Dan Gohman5cec4db2007-06-19 14:28:31 +00001477 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001478 UI != UE; ++UI) {
Nick Lewycky51e844b2007-06-06 11:26:20 +00001479 Instruction *Inst = cast<Instruction>(*UI);
1480 if (Scalars.erase(Inst)) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001481 if (PHINode *PN = dyn_cast<PHINode>(VV))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001482 ConstantEvolutionLoopExitValue.erase(PN);
1483 Worklist.push_back(Inst);
1484 }
1485 }
1486 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001487}
1488
1489
1490/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1491/// expression and create a new one.
1492SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1493 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1494
1495 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1496 if (I != Scalars.end()) return I->second;
1497 SCEVHandle S = createSCEV(V);
1498 Scalars.insert(std::make_pair(V, S));
1499 return S;
1500}
1501
Chris Lattner4dc534c2005-02-13 04:37:18 +00001502/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1503/// the specified instruction and replaces any references to the symbolic value
1504/// SymName with the specified value. This is used during PHI resolution.
1505void ScalarEvolutionsImpl::
1506ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1507 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001508 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001509 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001510
Chris Lattner4dc534c2005-02-13 04:37:18 +00001511 SCEVHandle NV =
Dan Gohman246b2562007-10-22 18:31:58 +00001512 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001513 if (NV == SI->second) return; // No change.
1514
1515 SI->second = NV; // Update the scalars map!
1516
1517 // Any instruction values that use this instruction might also need to be
1518 // updated!
1519 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1520 UI != E; ++UI)
1521 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1522}
Chris Lattner53e677a2004-04-02 20:23:17 +00001523
1524/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1525/// a loop header, making it a potential recurrence, or it doesn't.
1526///
1527SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1528 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1529 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1530 if (L->getHeader() == PN->getParent()) {
1531 // If it lives in the loop header, it has two incoming values, one
1532 // from outside the loop, and one from inside.
1533 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1534 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001535
Chris Lattner53e677a2004-04-02 20:23:17 +00001536 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman246b2562007-10-22 18:31:58 +00001537 SCEVHandle SymbolicName = SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001538 assert(Scalars.find(PN) == Scalars.end() &&
1539 "PHI node already processed?");
1540 Scalars.insert(std::make_pair(PN, SymbolicName));
1541
1542 // Using this symbolic name for the PHI, analyze the value coming around
1543 // the back-edge.
1544 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1545
1546 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1547 // has a special value for the first iteration of the loop.
1548
1549 // If the value coming around the backedge is an add with the symbolic
1550 // value we just inserted, then we found a simple induction variable!
1551 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1552 // If there is a single occurrence of the symbolic value, replace it
1553 // with a recurrence.
1554 unsigned FoundIndex = Add->getNumOperands();
1555 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1556 if (Add->getOperand(i) == SymbolicName)
1557 if (FoundIndex == e) {
1558 FoundIndex = i;
1559 break;
1560 }
1561
1562 if (FoundIndex != Add->getNumOperands()) {
1563 // Create an add with everything but the specified operand.
1564 std::vector<SCEVHandle> Ops;
1565 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1566 if (i != FoundIndex)
1567 Ops.push_back(Add->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001568 SCEVHandle Accum = SE.getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001569
1570 // This is not a valid addrec if the step amount is varying each
1571 // loop iteration, but is not itself an addrec in this loop.
1572 if (Accum->isLoopInvariant(L) ||
1573 (isa<SCEVAddRecExpr>(Accum) &&
1574 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1575 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman246b2562007-10-22 18:31:58 +00001576 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001577
1578 // Okay, for the entire analysis of this edge we assumed the PHI
1579 // to be symbolic. We now need to go back and update all of the
1580 // entries for the scalars that use the PHI (except for the PHI
1581 // itself) to use the new analyzed value instead of the "symbolic"
1582 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001583 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001584 return PHISCEV;
1585 }
1586 }
Chris Lattner97156e72006-04-26 18:34:07 +00001587 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1588 // Otherwise, this could be a loop like this:
1589 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1590 // In this case, j = {1,+,1} and BEValue is j.
1591 // Because the other in-value of i (0) fits the evolution of BEValue
1592 // i really is an addrec evolution.
1593 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1594 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1595
1596 // If StartVal = j.start - j.stride, we can use StartVal as the
1597 // initial step of the addrec evolution.
Dan Gohman246b2562007-10-22 18:31:58 +00001598 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1599 AddRec->getOperand(1))) {
Chris Lattner97156e72006-04-26 18:34:07 +00001600 SCEVHandle PHISCEV =
Dan Gohman246b2562007-10-22 18:31:58 +00001601 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00001602
1603 // Okay, for the entire analysis of this edge we assumed the PHI
1604 // to be symbolic. We now need to go back and update all of the
1605 // entries for the scalars that use the PHI (except for the PHI
1606 // itself) to use the new analyzed value instead of the "symbolic"
1607 // value.
1608 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1609 return PHISCEV;
1610 }
1611 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001612 }
1613
1614 return SymbolicName;
1615 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001616
Chris Lattner53e677a2004-04-02 20:23:17 +00001617 // If it's not a loop phi, we can't handle it yet.
Dan Gohman246b2562007-10-22 18:31:58 +00001618 return SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001619}
1620
Nick Lewycky83bb0052007-11-22 07:59:40 +00001621/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1622/// guaranteed to end in (at every loop iteration). It is, at the same time,
1623/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1624/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1625static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1626 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00001627 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00001628
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001629 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Nick Lewycky83bb0052007-11-22 07:59:40 +00001630 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1631
1632 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1633 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1634 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1635 }
1636
1637 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1638 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1639 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1640 }
1641
Chris Lattnera17f0392006-12-12 02:26:09 +00001642 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001643 // The result is the min of all operands results.
1644 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1645 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1646 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1647 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001648 }
1649
1650 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001651 // The result is the sum of all operands results.
1652 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1653 uint32_t BitWidth = M->getBitWidth();
1654 for (unsigned i = 1, e = M->getNumOperands();
1655 SumOpRes != BitWidth && i != e; ++i)
1656 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1657 BitWidth);
1658 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001659 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001660
Chris Lattnera17f0392006-12-12 02:26:09 +00001661 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001662 // The result is the min of all operands results.
1663 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1664 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1665 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1666 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001667 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001668
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001669 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1670 // The result is the min of all operands results.
1671 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1672 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1673 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1674 return MinOpRes;
1675 }
1676
Nick Lewycky3e630762008-02-20 06:48:22 +00001677 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1678 // The result is the min of all operands results.
1679 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1680 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1681 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1682 return MinOpRes;
1683 }
1684
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001685 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky83bb0052007-11-22 07:59:40 +00001686 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00001687}
Chris Lattner53e677a2004-04-02 20:23:17 +00001688
1689/// createSCEV - We know that there is no SCEV for the specified value.
1690/// Analyze the expression.
1691///
1692SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
Chris Lattner42b5e082007-11-23 08:46:22 +00001693 if (!isa<IntegerType>(V->getType()))
1694 return SE.getUnknown(V);
1695
Chris Lattner53e677a2004-04-02 20:23:17 +00001696 if (Instruction *I = dyn_cast<Instruction>(V)) {
1697 switch (I->getOpcode()) {
1698 case Instruction::Add:
Dan Gohman246b2562007-10-22 18:31:58 +00001699 return SE.getAddExpr(getSCEV(I->getOperand(0)),
1700 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001701 case Instruction::Mul:
Dan Gohman246b2562007-10-22 18:31:58 +00001702 return SE.getMulExpr(getSCEV(I->getOperand(0)),
1703 getSCEV(I->getOperand(1)));
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001704 case Instruction::UDiv:
1705 return SE.getUDivExpr(getSCEV(I->getOperand(0)),
Dan Gohman246b2562007-10-22 18:31:58 +00001706 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001707 case Instruction::Sub:
Dan Gohman246b2562007-10-22 18:31:58 +00001708 return SE.getMinusSCEV(getSCEV(I->getOperand(0)),
1709 getSCEV(I->getOperand(1)));
Chris Lattnera17f0392006-12-12 02:26:09 +00001710 case Instruction::Or:
1711 // If the RHS of the Or is a constant, we may have something like:
Nick Lewyckycf96db22007-11-20 08:24:44 +00001712 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
Chris Lattnera17f0392006-12-12 02:26:09 +00001713 // optimizations will transparently handle this case.
Nick Lewyckycf96db22007-11-20 08:24:44 +00001714 //
1715 // In order for this transformation to be safe, the LHS must be of the
1716 // form X*(2^n) and the Or constant must be less than 2^n.
Chris Lattnera17f0392006-12-12 02:26:09 +00001717 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1718 SCEVHandle LHS = getSCEV(I->getOperand(0));
Nick Lewyckycf96db22007-11-20 08:24:44 +00001719 const APInt &CIVal = CI->getValue();
Nick Lewycky83bb0052007-11-22 07:59:40 +00001720 if (GetMinTrailingZeros(LHS) >=
Nick Lewyckycf96db22007-11-20 08:24:44 +00001721 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Nick Lewycky83bb0052007-11-22 07:59:40 +00001722 return SE.getAddExpr(LHS, getSCEV(I->getOperand(1)));
Chris Lattnera17f0392006-12-12 02:26:09 +00001723 }
1724 break;
Chris Lattner2811f2a2007-04-02 05:41:38 +00001725 case Instruction::Xor:
1726 // If the RHS of the xor is a signbit, then this is just an add.
1727 // Instcombine turns add of signbit into xor as a strength reduction step.
1728 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1729 if (CI->getValue().isSignBit())
Dan Gohman246b2562007-10-22 18:31:58 +00001730 return SE.getAddExpr(getSCEV(I->getOperand(0)),
1731 getSCEV(I->getOperand(1)));
Nick Lewycky3e630762008-02-20 06:48:22 +00001732 else if (CI->isAllOnesValue())
1733 return SE.getNotSCEV(getSCEV(I->getOperand(0)));
Chris Lattner2811f2a2007-04-02 05:41:38 +00001734 }
1735 break;
1736
Chris Lattner53e677a2004-04-02 20:23:17 +00001737 case Instruction::Shl:
1738 // Turn shift left of a constant amount into a multiply.
1739 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfdc1e162007-04-07 17:40:57 +00001740 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1741 Constant *X = ConstantInt::get(
1742 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohman246b2562007-10-22 18:31:58 +00001743 return SE.getMulExpr(getSCEV(I->getOperand(0)), getSCEV(X));
Chris Lattner53e677a2004-04-02 20:23:17 +00001744 }
1745 break;
1746
Reid Spencer3da59db2006-11-27 01:05:10 +00001747 case Instruction::Trunc:
Dan Gohman246b2562007-10-22 18:31:58 +00001748 return SE.getTruncateExpr(getSCEV(I->getOperand(0)), I->getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001749
1750 case Instruction::ZExt:
Dan Gohman246b2562007-10-22 18:31:58 +00001751 return SE.getZeroExtendExpr(getSCEV(I->getOperand(0)), I->getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001752
Dan Gohmand19534a2007-06-15 14:38:12 +00001753 case Instruction::SExt:
Dan Gohman246b2562007-10-22 18:31:58 +00001754 return SE.getSignExtendExpr(getSCEV(I->getOperand(0)), I->getType());
Dan Gohmand19534a2007-06-15 14:38:12 +00001755
Reid Spencer3da59db2006-11-27 01:05:10 +00001756 case Instruction::BitCast:
1757 // BitCasts are no-op casts so we just eliminate the cast.
Chris Lattner42a75512007-01-15 02:27:26 +00001758 if (I->getType()->isInteger() &&
1759 I->getOperand(0)->getType()->isInteger())
Chris Lattner82e8a8f2006-12-11 00:12:31 +00001760 return getSCEV(I->getOperand(0));
1761 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001762
1763 case Instruction::PHI:
1764 return createNodeForPHI(cast<PHINode>(I));
1765
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001766 case Instruction::Select:
Nick Lewycky3e630762008-02-20 06:48:22 +00001767 // This could be a smax or umax that was lowered earlier.
1768 // Try to recover it.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001769 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I->getOperand(0))) {
1770 Value *LHS = ICI->getOperand(0);
1771 Value *RHS = ICI->getOperand(1);
1772 switch (ICI->getPredicate()) {
1773 case ICmpInst::ICMP_SLT:
1774 case ICmpInst::ICMP_SLE:
1775 std::swap(LHS, RHS);
1776 // fall through
1777 case ICmpInst::ICMP_SGT:
1778 case ICmpInst::ICMP_SGE:
1779 if (LHS == I->getOperand(1) && RHS == I->getOperand(2))
1780 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Nick Lewycky3e630762008-02-20 06:48:22 +00001781 else if (LHS == I->getOperand(2) && RHS == I->getOperand(1))
1782 // -smax(-x, -y) == smin(x, y).
1783 return SE.getNegativeSCEV(SE.getSMaxExpr(
1784 SE.getNegativeSCEV(getSCEV(LHS)),
1785 SE.getNegativeSCEV(getSCEV(RHS))));
1786 break;
1787 case ICmpInst::ICMP_ULT:
1788 case ICmpInst::ICMP_ULE:
1789 std::swap(LHS, RHS);
1790 // fall through
1791 case ICmpInst::ICMP_UGT:
1792 case ICmpInst::ICMP_UGE:
1793 if (LHS == I->getOperand(1) && RHS == I->getOperand(2))
1794 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1795 else if (LHS == I->getOperand(2) && RHS == I->getOperand(1))
1796 // ~umax(~x, ~y) == umin(x, y)
1797 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
1798 SE.getNotSCEV(getSCEV(RHS))));
1799 break;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001800 default:
1801 break;
1802 }
1803 }
1804
Chris Lattner53e677a2004-04-02 20:23:17 +00001805 default: // We cannot analyze this expression.
1806 break;
1807 }
1808 }
1809
Dan Gohman246b2562007-10-22 18:31:58 +00001810 return SE.getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001811}
1812
1813
1814
1815//===----------------------------------------------------------------------===//
1816// Iteration Count Computation Code
1817//
1818
1819/// getIterationCount - If the specified loop has a predictable iteration
1820/// count, return it. Note that it is not valid to call this method on a
1821/// loop without a loop-invariant iteration count.
1822SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1823 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1824 if (I == IterationCounts.end()) {
1825 SCEVHandle ItCount = ComputeIterationCount(L);
1826 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1827 if (ItCount != UnknownValue) {
1828 assert(ItCount->isLoopInvariant(L) &&
1829 "Computed trip count isn't loop invariant for loop!");
1830 ++NumTripCountsComputed;
1831 } else if (isa<PHINode>(L->getHeader()->begin())) {
1832 // Only count loops that have phi nodes as not being computable.
1833 ++NumTripCountsNotComputed;
1834 }
1835 }
1836 return I->second;
1837}
1838
1839/// ComputeIterationCount - Compute the number of times the specified loop
1840/// will iterate.
1841SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1842 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patelb7211a22007-08-21 00:31:24 +00001843 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001844 L->getExitBlocks(ExitBlocks);
1845 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001846
1847 // Okay, there is one exit block. Try to find the condition that causes the
1848 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001849 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001850
1851 BasicBlock *ExitingBlock = 0;
1852 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1853 PI != E; ++PI)
1854 if (L->contains(*PI)) {
1855 if (ExitingBlock == 0)
1856 ExitingBlock = *PI;
1857 else
1858 return UnknownValue; // More than one block exiting!
1859 }
1860 assert(ExitingBlock && "No exits from loop, something is broken!");
1861
1862 // Okay, we've computed the exiting block. See what condition causes us to
1863 // exit.
1864 //
1865 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00001866 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1867 if (ExitBr == 0) return UnknownValue;
1868 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00001869
1870 // At this point, we know we have a conditional branch that determines whether
1871 // the loop is exited. However, we don't know if the branch is executed each
1872 // time through the loop. If not, then the execution count of the branch will
1873 // not be equal to the trip count of the loop.
1874 //
1875 // Currently we check for this by checking to see if the Exit branch goes to
1876 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00001877 // times as the loop. We also handle the case where the exit block *is* the
1878 // loop header. This is common for un-rotated loops. More extensive analysis
1879 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001880 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00001881 ExitBr->getSuccessor(1) != L->getHeader() &&
1882 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00001883 return UnknownValue;
1884
Reid Spencere4d87aa2006-12-23 06:05:41 +00001885 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1886
Nick Lewycky3b711652008-02-21 08:34:02 +00001887 // If it's not an integer comparison then compute it the hard way.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001888 // Note that ICmpInst deals with pointer comparisons too so we must check
1889 // the type of the operand.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001890 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Chris Lattner7980fb92004-04-17 18:36:24 +00001891 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1892 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001893
Reid Spencere4d87aa2006-12-23 06:05:41 +00001894 // If the condition was exit on true, convert the condition to exit on false
1895 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00001896 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001897 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001898 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00001899 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001900
1901 // Handle common loops like: for (X = "string"; *X; ++X)
1902 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1903 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1904 SCEVHandle ItCnt =
1905 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1906 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1907 }
1908
Chris Lattner53e677a2004-04-02 20:23:17 +00001909 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1910 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1911
1912 // Try to evaluate any dependencies out of the loop.
1913 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1914 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1915 Tmp = getSCEVAtScope(RHS, L);
1916 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1917
Reid Spencere4d87aa2006-12-23 06:05:41 +00001918 // At this point, we would like to compute how many iterations of the
1919 // loop the predicate will return true for these inputs.
Evan Chengb9a90572008-02-25 03:57:32 +00001920 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1921 // If there is a constant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00001922 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001923 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00001924 }
1925
1926 // FIXME: think about handling pointer comparisons! i.e.:
1927 // while (P != P+100) ++P;
1928
1929 // If we have a comparison of a chrec against a constant, try to use value
1930 // ranges to answer this query.
1931 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1932 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1933 if (AddRec->getLoop() == L) {
1934 // Form the comparison range using the constant of the correct type so
1935 // that the ConstantRange class knows to do a signed or unsigned
1936 // comparison.
1937 ConstantInt *CompVal = RHSC->getValue();
1938 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00001939 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00001940 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00001941 if (CompVal) {
1942 // Form the constant range.
Reid Spencerc6aedf72007-02-28 22:03:51 +00001943 ConstantRange CompRange(
1944 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001945
Dan Gohman246b2562007-10-22 18:31:58 +00001946 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00001947 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1948 }
1949 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001950
Chris Lattner53e677a2004-04-02 20:23:17 +00001951 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001952 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00001953 // Convert to: while (X-Y != 0)
Dan Gohman246b2562007-10-22 18:31:58 +00001954 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001955 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00001956 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001957 }
1958 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00001959 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman246b2562007-10-22 18:31:58 +00001960 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001961 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00001962 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001963 }
1964 case ICmpInst::ICMP_SLT: {
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001965 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001966 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001967 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001968 }
1969 case ICmpInst::ICMP_SGT: {
Dan Gohman246b2562007-10-22 18:31:58 +00001970 SCEVHandle TC = HowManyLessThans(SE.getNegativeSCEV(LHS),
1971 SE.getNegativeSCEV(RHS), L, true);
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001972 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1973 break;
1974 }
1975 case ICmpInst::ICMP_ULT: {
1976 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
1977 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1978 break;
1979 }
1980 case ICmpInst::ICMP_UGT: {
Dale Johannesena0c8fc62008-04-20 16:58:57 +00001981 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky08de6132008-05-06 04:03:18 +00001982 SE.getNotSCEV(RHS), L, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001983 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001984 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001985 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001986 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001987#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001988 cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00001989 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendlinge8156192006-12-07 01:30:32 +00001990 cerr << "[unsigned] ";
1991 cerr << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00001992 << Instruction::getOpcodeName(Instruction::ICmp)
1993 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001994#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00001995 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001996 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001997 return ComputeIterationCountExhaustively(L, ExitCond,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001998 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00001999}
2000
Chris Lattner673e02b2004-10-12 01:49:27 +00002001static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00002002EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2003 ScalarEvolution &SE) {
2004 SCEVHandle InVal = SE.getConstant(C);
2005 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002006 assert(isa<SCEVConstant>(Val) &&
2007 "Evaluation of SCEV at constant didn't fold correctly?");
2008 return cast<SCEVConstant>(Val)->getValue();
2009}
2010
2011/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2012/// and a GEP expression (missing the pointer index) indexing into it, return
2013/// the addressed element of the initializer or null if the index expression is
2014/// invalid.
2015static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002016GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00002017 const std::vector<ConstantInt*> &Indices) {
2018 Constant *Init = GV->getInitializer();
2019 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002020 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00002021 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2022 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2023 Init = cast<Constant>(CS->getOperand(Idx));
2024 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2025 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2026 Init = cast<Constant>(CA->getOperand(Idx));
2027 } else if (isa<ConstantAggregateZero>(Init)) {
2028 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2029 assert(Idx < STy->getNumElements() && "Bad struct index!");
2030 Init = Constant::getNullValue(STy->getElementType(Idx));
2031 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2032 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2033 Init = Constant::getNullValue(ATy->getElementType());
2034 } else {
2035 assert(0 && "Unknown constant aggregate type!");
2036 }
2037 return 0;
2038 } else {
2039 return 0; // Unknown initializer type
2040 }
2041 }
2042 return Init;
2043}
2044
2045/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky08de6132008-05-06 04:03:18 +00002046/// 'icmp op load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00002047SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002048ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002049 const Loop *L,
2050 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002051 if (LI->isVolatile()) return UnknownValue;
2052
2053 // Check to see if the loaded pointer is a getelementptr of a global.
2054 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2055 if (!GEP) return UnknownValue;
2056
2057 // Make sure that it is really a constant global we are gepping, with an
2058 // initializer, and make sure the first IDX is really 0.
2059 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2060 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2061 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2062 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2063 return UnknownValue;
2064
2065 // Okay, we allow one non-constant index into the GEP instruction.
2066 Value *VarIdx = 0;
2067 std::vector<ConstantInt*> Indexes;
2068 unsigned VarIdxNum = 0;
2069 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2070 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2071 Indexes.push_back(CI);
2072 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2073 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2074 VarIdx = GEP->getOperand(i);
2075 VarIdxNum = i-2;
2076 Indexes.push_back(0);
2077 }
2078
2079 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2080 // Check to see if X is a loop variant variable value now.
2081 SCEVHandle Idx = getSCEV(VarIdx);
2082 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2083 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2084
2085 // We can only recognize very limited forms of loop index expressions, in
2086 // particular, only affine AddRec's like {C1,+,C2}.
2087 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2088 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2089 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2090 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2091 return UnknownValue;
2092
2093 unsigned MaxSteps = MaxBruteForceIterations;
2094 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002095 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00002096 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohman246b2562007-10-22 18:31:58 +00002097 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002098
2099 // Form the GEP offset.
2100 Indexes[VarIdxNum] = Val;
2101
2102 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2103 if (Result == 0) break; // Cannot compute!
2104
2105 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002106 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002107 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00002108 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002109#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002110 cerr << "\n***\n*** Computed loop count " << *ItCst
2111 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2112 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00002113#endif
2114 ++NumArrayLenItCounts;
Dan Gohman246b2562007-10-22 18:31:58 +00002115 return SE.getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00002116 }
2117 }
2118 return UnknownValue;
2119}
2120
2121
Chris Lattner3221ad02004-04-17 22:58:41 +00002122/// CanConstantFold - Return true if we can constant fold an instruction of the
2123/// specified type, assuming that all operands were constants.
2124static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00002125 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00002126 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2127 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002128
Chris Lattner3221ad02004-04-17 22:58:41 +00002129 if (const CallInst *CI = dyn_cast<CallInst>(I))
2130 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00002131 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00002132 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00002133}
2134
Chris Lattner3221ad02004-04-17 22:58:41 +00002135/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2136/// in the loop that V is derived from. We allow arbitrary operations along the
2137/// way, but the operands of an operation must either be constants or a value
2138/// derived from a constant PHI. If this expression does not fit with these
2139/// constraints, return null.
2140static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2141 // If this is not an instruction, or if this is an instruction outside of the
2142 // loop, it can't be derived from a loop PHI.
2143 Instruction *I = dyn_cast<Instruction>(V);
2144 if (I == 0 || !L->contains(I->getParent())) return 0;
2145
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002146 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002147 if (L->getHeader() == I->getParent())
2148 return PN;
2149 else
2150 // We don't currently keep track of the control flow needed to evaluate
2151 // PHIs, so we cannot handle PHIs inside of loops.
2152 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002153 }
Chris Lattner3221ad02004-04-17 22:58:41 +00002154
2155 // If we won't be able to constant fold this expression even if the operands
2156 // are constants, return early.
2157 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002158
Chris Lattner3221ad02004-04-17 22:58:41 +00002159 // Otherwise, we can evaluate this instruction if all of its operands are
2160 // constant or derived from a PHI node themselves.
2161 PHINode *PHI = 0;
2162 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2163 if (!(isa<Constant>(I->getOperand(Op)) ||
2164 isa<GlobalValue>(I->getOperand(Op)))) {
2165 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2166 if (P == 0) return 0; // Not evolving from PHI
2167 if (PHI == 0)
2168 PHI = P;
2169 else if (PHI != P)
2170 return 0; // Evolving from multiple different PHIs.
2171 }
2172
2173 // This is a expression evolving from a constant PHI!
2174 return PHI;
2175}
2176
2177/// EvaluateExpression - Given an expression that passes the
2178/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2179/// in the loop has the value PHIVal. If we can't fold this expression for some
2180/// reason, return null.
2181static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2182 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00002183 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00002184 Instruction *I = cast<Instruction>(V);
2185
2186 std::vector<Constant*> Operands;
2187 Operands.resize(I->getNumOperands());
2188
2189 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2190 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2191 if (Operands[i] == 0) return 0;
2192 }
2193
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002194 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2195 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2196 &Operands[0], Operands.size());
2197 else
2198 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2199 &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00002200}
2201
2202/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2203/// in the header of its containing loop, we know the loop executes a
2204/// constant number of times, and the PHI node is just a recurrence
2205/// involving constants, fold it.
2206Constant *ScalarEvolutionsImpl::
Reid Spencere8019bb2007-03-01 07:25:48 +00002207getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00002208 std::map<PHINode*, Constant*>::iterator I =
2209 ConstantEvolutionLoopExitValue.find(PN);
2210 if (I != ConstantEvolutionLoopExitValue.end())
2211 return I->second;
2212
Reid Spencere8019bb2007-03-01 07:25:48 +00002213 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00002214 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2215
2216 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2217
2218 // Since the loop is canonicalized, the PHI node must have two entries. One
2219 // entry must be a constant (coming in from outside of the loop), and the
2220 // second must be derived from the same PHI.
2221 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2222 Constant *StartCST =
2223 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2224 if (StartCST == 0)
2225 return RetVal = 0; // Must be a constant.
2226
2227 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2228 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2229 if (PN2 != PN)
2230 return RetVal = 0; // Not derived from same PHI.
2231
2232 // Execute the loop symbolically to determine the exit value.
Reid Spencere8019bb2007-03-01 07:25:48 +00002233 if (Its.getActiveBits() >= 32)
2234 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00002235
Reid Spencere8019bb2007-03-01 07:25:48 +00002236 unsigned NumIterations = Its.getZExtValue(); // must be in range
2237 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00002238 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2239 if (IterationNum == NumIterations)
2240 return RetVal = PHIVal; // Got exit value!
2241
2242 // Compute the value of the PHI node for the next iteration.
2243 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2244 if (NextPHI == PHIVal)
2245 return RetVal = NextPHI; // Stopped evolving!
2246 if (NextPHI == 0)
2247 return 0; // Couldn't evaluate!
2248 PHIVal = NextPHI;
2249 }
2250}
2251
Chris Lattner7980fb92004-04-17 18:36:24 +00002252/// ComputeIterationCountExhaustively - If the trip is known to execute a
2253/// constant number of times (the condition evolves only from constants),
2254/// try to evaluate a few iterations of the loop until we get the exit
2255/// condition gets a value of ExitWhen (true or false). If we cannot
2256/// evaluate the trip count of the loop, return UnknownValue.
2257SCEVHandle ScalarEvolutionsImpl::
2258ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2259 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2260 if (PN == 0) return UnknownValue;
2261
2262 // Since the loop is canonicalized, the PHI node must have two entries. One
2263 // entry must be a constant (coming in from outside of the loop), and the
2264 // second must be derived from the same PHI.
2265 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2266 Constant *StartCST =
2267 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2268 if (StartCST == 0) return UnknownValue; // Must be a constant.
2269
2270 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2271 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2272 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2273
2274 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2275 // the loop symbolically to determine when the condition gets a value of
2276 // "ExitWhen".
2277 unsigned IterationNum = 0;
2278 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2279 for (Constant *PHIVal = StartCST;
2280 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002281 ConstantInt *CondVal =
2282 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00002283
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002284 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00002285 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002286
Reid Spencere8019bb2007-03-01 07:25:48 +00002287 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002288 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00002289 ++NumBruteForceTripCountsComputed;
Dan Gohman246b2562007-10-22 18:31:58 +00002290 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00002291 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002292
Chris Lattner3221ad02004-04-17 22:58:41 +00002293 // Compute the value of the PHI node for the next iteration.
2294 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2295 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00002296 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00002297 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00002298 }
2299
2300 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00002301 return UnknownValue;
2302}
2303
2304/// getSCEVAtScope - Compute the value of the specified expression within the
2305/// indicated loop (which may be null to indicate in no loop). If the
2306/// expression cannot be evaluated, return UnknownValue.
2307SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2308 // FIXME: this should be turned into a virtual method on SCEV!
2309
Chris Lattner3221ad02004-04-17 22:58:41 +00002310 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002311
Nick Lewycky3e630762008-02-20 06:48:22 +00002312 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00002313 // exit value from the loop without using SCEVs.
2314 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2315 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2316 const Loop *LI = this->LI[I->getParent()];
2317 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2318 if (PHINode *PN = dyn_cast<PHINode>(I))
2319 if (PN->getParent() == LI->getHeader()) {
2320 // Okay, there is no closed form solution for the PHI node. Check
2321 // to see if the loop that contains it has a known iteration count.
2322 // If so, we may be able to force computation of the exit value.
2323 SCEVHandle IterationCount = getIterationCount(LI);
2324 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2325 // Okay, we know how many times the containing loop executes. If
2326 // this is a constant evolving PHI node, get the final value at
2327 // the specified iteration number.
2328 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencere8019bb2007-03-01 07:25:48 +00002329 ICC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00002330 LI);
Dan Gohman246b2562007-10-22 18:31:58 +00002331 if (RV) return SE.getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00002332 }
2333 }
2334
Reid Spencer09906f32006-12-04 21:33:23 +00002335 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00002336 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00002337 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00002338 // result. This is particularly useful for computing loop exit values.
2339 if (CanConstantFold(I)) {
2340 std::vector<Constant*> Operands;
2341 Operands.reserve(I->getNumOperands());
2342 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2343 Value *Op = I->getOperand(i);
2344 if (Constant *C = dyn_cast<Constant>(Op)) {
2345 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002346 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00002347 // If any of the operands is non-constant and if they are
2348 // non-integer, don't even try to analyze them with scev techniques.
2349 if (!isa<IntegerType>(Op->getType()))
2350 return V;
2351
Chris Lattner3221ad02004-04-17 22:58:41 +00002352 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2353 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
Reid Spencerd977d862006-12-12 23:36:14 +00002354 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2355 Op->getType(),
2356 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002357 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2358 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
Reid Spencerd977d862006-12-12 23:36:14 +00002359 Operands.push_back(ConstantExpr::getIntegerCast(C,
2360 Op->getType(),
2361 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002362 else
2363 return V;
2364 } else {
2365 return V;
2366 }
2367 }
2368 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002369
2370 Constant *C;
2371 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2372 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2373 &Operands[0], Operands.size());
2374 else
2375 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2376 &Operands[0], Operands.size());
Dan Gohman246b2562007-10-22 18:31:58 +00002377 return SE.getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002378 }
2379 }
2380
2381 // This is some other type of SCEVUnknown, just return it.
2382 return V;
2383 }
2384
Chris Lattner53e677a2004-04-02 20:23:17 +00002385 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2386 // Avoid performing the look-up in the common case where the specified
2387 // expression has no loop-variant portions.
2388 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2389 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2390 if (OpAtScope != Comm->getOperand(i)) {
2391 if (OpAtScope == UnknownValue) return UnknownValue;
2392 // Okay, at least one of these operands is loop variant but might be
2393 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002394 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002395 NewOps.push_back(OpAtScope);
2396
2397 for (++i; i != e; ++i) {
2398 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2399 if (OpAtScope == UnknownValue) return UnknownValue;
2400 NewOps.push_back(OpAtScope);
2401 }
2402 if (isa<SCEVAddExpr>(Comm))
Dan Gohman246b2562007-10-22 18:31:58 +00002403 return SE.getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002404 if (isa<SCEVMulExpr>(Comm))
2405 return SE.getMulExpr(NewOps);
2406 if (isa<SCEVSMaxExpr>(Comm))
2407 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00002408 if (isa<SCEVUMaxExpr>(Comm))
2409 return SE.getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002410 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002411 }
2412 }
2413 // If we got here, all operands are loop invariant.
2414 return Comm;
2415 }
2416
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00002417 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Chris Lattner60a05cc2006-04-01 04:48:52 +00002418 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002419 if (LHS == UnknownValue) return LHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002420 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002421 if (RHS == UnknownValue) return RHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002422 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2423 return Div; // must be loop invariant
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00002424 return SE.getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002425 }
2426
2427 // If this is a loop recurrence for a loop that does not contain L, then we
2428 // are dealing with the final value computed by the loop.
2429 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2430 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2431 // To evaluate this recurrence, we need to know how many times the AddRec
2432 // loop iterates. Compute this now.
2433 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2434 if (IterationCount == UnknownValue) return UnknownValue;
2435 IterationCount = getTruncateOrZeroExtend(IterationCount,
Dan Gohman246b2562007-10-22 18:31:58 +00002436 AddRec->getType(), SE);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002437
Chris Lattner53e677a2004-04-02 20:23:17 +00002438 // If the value is affine, simplify the expression evaluation to just
2439 // Start + Step*IterationCount.
2440 if (AddRec->isAffine())
Dan Gohman246b2562007-10-22 18:31:58 +00002441 return SE.getAddExpr(AddRec->getStart(),
2442 SE.getMulExpr(IterationCount,
2443 AddRec->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00002444
2445 // Otherwise, evaluate it the hard way.
Dan Gohman246b2562007-10-22 18:31:58 +00002446 return AddRec->evaluateAtIteration(IterationCount, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002447 }
2448 return UnknownValue;
2449 }
2450
2451 //assert(0 && "Unknown SCEV type!");
2452 return UnknownValue;
2453}
2454
2455
2456/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2457/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2458/// might be the same) or two SCEVCouldNotCompute objects.
2459///
2460static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman246b2562007-10-22 18:31:58 +00002461SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002462 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Reid Spencere8019bb2007-03-01 07:25:48 +00002463 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2464 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2465 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002466
Chris Lattner53e677a2004-04-02 20:23:17 +00002467 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00002468 if (!LC || !MC || !NC) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002469 SCEV *CNC = new SCEVCouldNotCompute();
2470 return std::make_pair(CNC, CNC);
2471 }
2472
Reid Spencere8019bb2007-03-01 07:25:48 +00002473 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00002474 const APInt &L = LC->getValue()->getValue();
2475 const APInt &M = MC->getValue()->getValue();
2476 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00002477 APInt Two(BitWidth, 2);
2478 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002479
Reid Spencere8019bb2007-03-01 07:25:48 +00002480 {
2481 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00002482 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00002483 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2484 // The B coefficient is M-N/2
2485 APInt B(M);
2486 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002487
Reid Spencere8019bb2007-03-01 07:25:48 +00002488 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00002489 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00002490
Reid Spencere8019bb2007-03-01 07:25:48 +00002491 // Compute the B^2-4ac term.
2492 APInt SqrtTerm(B);
2493 SqrtTerm *= B;
2494 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00002495
Reid Spencere8019bb2007-03-01 07:25:48 +00002496 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2497 // integer value or else APInt::sqrt() will assert.
2498 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002499
Reid Spencere8019bb2007-03-01 07:25:48 +00002500 // Compute the two solutions for the quadratic formula.
2501 // The divisions must be performed as signed divisions.
2502 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00002503 APInt TwoA( A << 1 );
Reid Spencere8019bb2007-03-01 07:25:48 +00002504 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2505 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002506
Dan Gohman246b2562007-10-22 18:31:58 +00002507 return std::make_pair(SE.getConstant(Solution1),
2508 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00002509 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00002510}
2511
2512/// HowFarToZero - Return the number of times a backedge comparing the specified
2513/// value to zero will execute. If not computable, return UnknownValue
2514SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2515 // If the value is a constant
2516 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2517 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00002518 if (C->getValue()->isZero()) return C;
Chris Lattner53e677a2004-04-02 20:23:17 +00002519 return UnknownValue; // Otherwise it will loop infinitely.
2520 }
2521
2522 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2523 if (!AddRec || AddRec->getLoop() != L)
2524 return UnknownValue;
2525
2526 if (AddRec->isAffine()) {
2527 // If this is an affine expression the execution count of this branch is
2528 // equal to:
2529 //
2530 // (0 - Start/Step) iff Start % Step == 0
2531 //
2532 // Get the initial value for the loop.
2533 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002534 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002535 SCEVHandle Step = AddRec->getOperand(1);
2536
2537 Step = getSCEVAtScope(Step, L->getParentLoop());
2538
2539 // Figure out if Start % Step == 0.
2540 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2541 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2542 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
Dan Gohman246b2562007-10-22 18:31:58 +00002543 return SE.getNegativeSCEV(Start); // 0 - Start/1 == -Start
Chris Lattner53e677a2004-04-02 20:23:17 +00002544 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2545 return Start; // 0 - Start/-1 == Start
2546
2547 // Check to see if Start is divisible by SC with no remainder.
2548 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2549 ConstantInt *StartCC = StartC->getValue();
2550 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
Reid Spencer0a783f72006-11-02 01:53:59 +00002551 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002552 if (Rem->isNullValue()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002553 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
Dan Gohman246b2562007-10-22 18:31:58 +00002554 return SE.getUnknown(Result);
Chris Lattner53e677a2004-04-02 20:23:17 +00002555 }
2556 }
2557 }
Chris Lattner42a75512007-01-15 02:27:26 +00002558 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002559 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2560 // the quadratic equation to solve it.
Dan Gohman246b2562007-10-22 18:31:58 +00002561 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002562 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2563 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2564 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002565#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002566 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2567 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002568#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002569 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002570 if (ConstantInt *CB =
2571 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002572 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002573 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002574 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002575
Chris Lattner53e677a2004-04-02 20:23:17 +00002576 // We can only use this value if the chrec ends up with an exact zero
2577 // value at this index. When solving for "X*X != 5", for example, we
2578 // should not accept a root of 2.
Dan Gohman246b2562007-10-22 18:31:58 +00002579 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002580 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
Reid Spencercae57542007-03-02 00:28:52 +00002581 if (EvalVal->getValue()->isZero())
Chris Lattner53e677a2004-04-02 20:23:17 +00002582 return R1; // We found a quadratic root!
2583 }
2584 }
2585 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002586
Chris Lattner53e677a2004-04-02 20:23:17 +00002587 return UnknownValue;
2588}
2589
2590/// HowFarToNonZero - Return the number of times a backedge checking the
2591/// specified value for nonzero will execute. If not computable, return
2592/// UnknownValue
2593SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2594 // Loops that look like: while (X == 0) are very strange indeed. We don't
2595 // handle them yet except for the trivial case. This could be expanded in the
2596 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002597
Chris Lattner53e677a2004-04-02 20:23:17 +00002598 // If the value is a constant, check to see if it is known to be non-zero
2599 // already. If so, the backedge will execute zero times.
2600 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00002601 if (!C->getValue()->isNullValue())
2602 return SE.getIntegerSCEV(0, C->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002603 return UnknownValue; // Otherwise it will loop infinitely.
2604 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002605
Chris Lattner53e677a2004-04-02 20:23:17 +00002606 // We could implement others, but I really doubt anyone writes loops like
2607 // this, and if they did, they would already be constant folded.
2608 return UnknownValue;
2609}
2610
Chris Lattnerdb25de42005-08-15 23:33:51 +00002611/// HowManyLessThans - Return the number of times a backedge containing the
2612/// specified less-than comparison will execute. If not computable, return
2613/// UnknownValue.
2614SCEVHandle ScalarEvolutionsImpl::
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002615HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00002616 // Only handle: "ADDREC < LoopInvariant".
2617 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2618
2619 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2620 if (!AddRec || AddRec->getLoop() != L)
2621 return UnknownValue;
2622
2623 if (AddRec->isAffine()) {
2624 // FORNOW: We only support unit strides.
Dan Gohman246b2562007-10-22 18:31:58 +00002625 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
Chris Lattnerdb25de42005-08-15 23:33:51 +00002626 if (AddRec->getOperand(1) != One)
2627 return UnknownValue;
2628
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002629 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
2630 // m. So, we count the number of iterations in which {n,+,1} < m is true.
2631 // Note that we cannot simply return max(m-n,0) because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00002632 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00002633
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002634 // First, we get the value of the LHS in the first iteration: n
2635 SCEVHandle Start = AddRec->getOperand(0);
2636
2637 // Then, we get the value of the LHS in the first iteration in which the
2638 // above condition doesn't hold. This equals to max(m,n).
Nick Lewycky3e630762008-02-20 06:48:22 +00002639 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
2640 : SE.getUMaxExpr(RHS, Start);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002641
2642 // Finally, we subtract these two values to get the number of times the
2643 // backedge is executed: max(m,n)-n.
Wojciech Matyjewicz7b5b7682008-02-12 15:09:36 +00002644 return SE.getMinusSCEV(End, Start);
Chris Lattnerdb25de42005-08-15 23:33:51 +00002645 }
2646
2647 return UnknownValue;
2648}
2649
Chris Lattner53e677a2004-04-02 20:23:17 +00002650/// getNumIterationsInRange - Return the number of iterations of this loop that
2651/// produce values in the specified constant range. Another way of looking at
2652/// this is that it returns the first iteration number where the value is not in
2653/// the condition, thus computing the exit count. If the iteration count can't
2654/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman246b2562007-10-22 18:31:58 +00002655SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2656 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002657 if (Range.isFullSet()) // Infinite loop.
2658 return new SCEVCouldNotCompute();
2659
2660 // If the start is a non-zero constant, shift the range to simplify things.
2661 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00002662 if (!SC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002663 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00002664 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2665 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002666 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2667 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00002668 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002669 // This is strange and shouldn't happen.
2670 return new SCEVCouldNotCompute();
2671 }
2672
2673 // The only time we can solve this is when we have all constant indices.
2674 // Otherwise, we cannot determine the overflow conditions.
2675 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2676 if (!isa<SCEVConstant>(getOperand(i)))
2677 return new SCEVCouldNotCompute();
2678
2679
2680 // Okay at this point we know that all elements of the chrec are constants and
2681 // that the start element is zero.
2682
2683 // First check to see if the range contains zero. If not, the first
2684 // iteration exits.
Reid Spencera6e8a952007-03-01 07:54:15 +00002685 if (!Range.contains(APInt(getBitWidth(),0)))
Dan Gohman246b2562007-10-22 18:31:58 +00002686 return SE.getConstant(ConstantInt::get(getType(),0));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002687
Chris Lattner53e677a2004-04-02 20:23:17 +00002688 if (isAffine()) {
2689 // If this is an affine expression then we have this situation:
2690 // Solve {0,+,A} in Range === Ax in Range
2691
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002692 // We know that zero is in the range. If A is positive then we know that
2693 // the upper value of the range must be the first possible exit value.
2694 // If A is negative then the lower of the range is the last possible loop
2695 // value. Also note that we already checked for a full range.
Reid Spencer581b0d42007-02-28 19:57:34 +00002696 APInt One(getBitWidth(),1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002697 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2698 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00002699
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002700 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00002701 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00002702 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002703
2704 // Evaluate at the exit value. If we really did fall out of the valid
2705 // range, then we computed our trip count, otherwise wrap around or other
2706 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00002707 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002708 if (Range.contains(Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002709 return new SCEVCouldNotCompute(); // Something strange happened
2710
2711 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00002712 assert(Range.contains(
2713 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00002714 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002715 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00002716 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00002717 } else if (isQuadratic()) {
2718 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2719 // quadratic equation to solve it. To do this, we must frame our problem in
2720 // terms of figuring out when zero is crossed, instead of when
2721 // Range.getUpper() is crossed.
2722 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00002723 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
2724 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002725
2726 // Next, solve the constructed addrec
2727 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00002728 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002729 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2730 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2731 if (R1) {
2732 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002733 if (ConstantInt *CB =
2734 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002735 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002736 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002737 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002738
Chris Lattner53e677a2004-04-02 20:23:17 +00002739 // Make sure the root is not off by one. The returned iteration should
2740 // not be in the range, but the previous one should be. When solving
2741 // for "X*X < 5", for example, we should not return a root of 2.
2742 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00002743 R1->getValue(),
2744 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002745 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002746 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00002747 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002748
Dan Gohman246b2562007-10-22 18:31:58 +00002749 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002750 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00002751 return SE.getConstant(NextVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002752 return new SCEVCouldNotCompute(); // Something strange happened
2753 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002754
Chris Lattner53e677a2004-04-02 20:23:17 +00002755 // If R1 was not in the range, then it is a good return value. Make
2756 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00002757 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00002758 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002759 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002760 return R1;
2761 return new SCEVCouldNotCompute(); // Something strange happened
2762 }
2763 }
2764 }
2765
2766 // Fallback, if this is a general polynomial, figure out the progression
2767 // through brute force: evaluate until we find an iteration that fails the
2768 // test. This is likely to be slow, but getting an accurate trip count is
2769 // incredibly important, we will be able to simplify the exit test a lot, and
2770 // we are almost guaranteed to get a trip count in this case.
2771 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00002772 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2773 do {
2774 ++NumBruteForceEvaluations;
Dan Gohman246b2562007-10-22 18:31:58 +00002775 SCEVHandle Val = evaluateAtIteration(SE.getConstant(TestVal), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002776 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2777 return new SCEVCouldNotCompute();
2778
2779 // Check to see if we found the value!
Reid Spencera6e8a952007-03-01 07:54:15 +00002780 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00002781 return SE.getConstant(TestVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002782
2783 // Increment to test the next index.
Zhou Shengfdc1e162007-04-07 17:40:57 +00002784 TestVal = ConstantInt::get(TestVal->getValue()+1);
Chris Lattner53e677a2004-04-02 20:23:17 +00002785 } while (TestVal != EndVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002786
Chris Lattner53e677a2004-04-02 20:23:17 +00002787 return new SCEVCouldNotCompute();
2788}
2789
2790
2791
2792//===----------------------------------------------------------------------===//
2793// ScalarEvolution Class Implementation
2794//===----------------------------------------------------------------------===//
2795
2796bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohman246b2562007-10-22 18:31:58 +00002797 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
Chris Lattner53e677a2004-04-02 20:23:17 +00002798 return false;
2799}
2800
2801void ScalarEvolution::releaseMemory() {
2802 delete (ScalarEvolutionsImpl*)Impl;
2803 Impl = 0;
2804}
2805
2806void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2807 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00002808 AU.addRequiredTransitive<LoopInfo>();
2809}
2810
2811SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2812 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2813}
2814
Chris Lattnera0740fb2005-08-09 23:36:33 +00002815/// hasSCEV - Return true if the SCEV for this value has already been
2816/// computed.
2817bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00002818 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00002819}
2820
2821
2822/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2823/// the specified value.
2824void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2825 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2826}
2827
2828
Chris Lattner53e677a2004-04-02 20:23:17 +00002829SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2830 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2831}
2832
2833bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2834 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2835}
2836
2837SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2838 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2839}
2840
Dan Gohman5cec4db2007-06-19 14:28:31 +00002841void ScalarEvolution::deleteValueFromRecords(Value *V) const {
2842 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002843}
2844
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002845static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00002846 const Loop *L) {
2847 // Print all inner loops first
2848 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2849 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002850
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00002851 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002852
Devang Patelb7211a22007-08-21 00:31:24 +00002853 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002854 L->getExitBlocks(ExitBlocks);
2855 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00002856 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002857
2858 if (SE->hasLoopInvariantIterationCount(L)) {
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00002859 OS << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002860 } else {
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00002861 OS << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002862 }
2863
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00002864 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00002865}
2866
Reid Spencerce9653c2004-12-07 04:03:45 +00002867void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002868 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2869 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2870
2871 OS << "Classifying expressions for: " << F.getName() << "\n";
2872 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner42a75512007-01-15 02:27:26 +00002873 if (I->getType()->isInteger()) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00002874 OS << *I;
Chris Lattner53e677a2004-04-02 20:23:17 +00002875 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002876 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00002877 SV->print(OS);
2878 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002879
Chris Lattner42a75512007-01-15 02:27:26 +00002880 if ((*I).getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002881 ConstantRange Bounds = SV->getValueRange();
2882 if (!Bounds.isFullSet())
2883 OS << "Bounds: " << Bounds << " ";
2884 }
2885
Chris Lattner6ffe5512004-04-27 15:13:33 +00002886 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002887 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002888 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002889 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2890 OS << "<<Unknown>>";
2891 } else {
2892 OS << *ExitValue;
2893 }
2894 }
2895
2896
2897 OS << "\n";
2898 }
2899
2900 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2901 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2902 PrintLoopInfo(OS, this, *I);
2903}