blob: 6e506174cfb1563d206dc19463b7586f0fa781a5 [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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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
98cl::opt<unsigned>
99MaxBruteForceIterations("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
Chris Lattner53e677a2004-04-02 20:23:17 +0000104namespace {
Chris Lattner5d8925c2006-08-27 22:30:17 +0000105 RegisterPass<ScalarEvolution>
Chris Lattner45a1cf82004-04-19 03:42:32 +0000106 R("scalar-evolution", "Scalar Evolution Analysis");
Chris Lattner53e677a2004-04-02 20:23:17 +0000107}
Devang Patel19974732007-05-03 01:11:54 +0000108char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000109
110//===----------------------------------------------------------------------===//
111// SCEV class definitions
112//===----------------------------------------------------------------------===//
113
114//===----------------------------------------------------------------------===//
115// Implementation of the SCEV class.
116//
Chris Lattner53e677a2004-04-02 20:23:17 +0000117SCEV::~SCEV() {}
118void SCEV::dump() const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000119 print(cerr);
Chris Lattner53e677a2004-04-02 20:23:17 +0000120}
121
122/// getValueRange - Return the tightest constant bounds that this value is
123/// known to have. This method is only valid on integer SCEV objects.
124ConstantRange SCEV::getValueRange() const {
125 const Type *Ty = getType();
Chris Lattner42a75512007-01-15 02:27:26 +0000126 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000127 // Default to a full range if no better information is available.
Reid Spencerc6aedf72007-02-28 22:03:51 +0000128 return ConstantRange(getBitWidth());
Chris Lattner53e677a2004-04-02 20:23:17 +0000129}
130
Reid Spencer581b0d42007-02-28 19:57:34 +0000131uint32_t SCEV::getBitWidth() const {
132 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
133 return ITy->getBitWidth();
134 return 0;
135}
136
Chris Lattner53e677a2004-04-02 20:23:17 +0000137
138SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
139
140bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000142 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000143}
144
145const Type *SCEVCouldNotCompute::getType() const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000147 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000148}
149
150bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
151 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
152 return false;
153}
154
Chris Lattner4dc534c2005-02-13 04:37:18 +0000155SCEVHandle SCEVCouldNotCompute::
156replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000157 const SCEVHandle &Conc,
158 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000159 return this;
160}
161
Chris Lattner53e677a2004-04-02 20:23:17 +0000162void SCEVCouldNotCompute::print(std::ostream &OS) const {
163 OS << "***COULDNOTCOMPUTE***";
164}
165
166bool SCEVCouldNotCompute::classof(const SCEV *S) {
167 return S->getSCEVType() == scCouldNotCompute;
168}
169
170
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000171// SCEVConstants - Only allow the creation of one SCEVConstant for any
172// particular value. Don't use a SCEVHandle here, or else the object will
173// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000174static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000175
Chris Lattner53e677a2004-04-02 20:23:17 +0000176
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000177SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000178 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000179}
Chris Lattner53e677a2004-04-02 20:23:17 +0000180
Dan Gohman246b2562007-10-22 18:31:58 +0000181SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Chris Lattnerb3364092006-10-04 21:49:37 +0000182 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000183 if (R == 0) R = new SCEVConstant(V);
184 return R;
185}
Chris Lattner53e677a2004-04-02 20:23:17 +0000186
Dan Gohman246b2562007-10-22 18:31:58 +0000187SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
188 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000189}
190
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000191ConstantRange SCEVConstant::getValueRange() const {
Reid Spencerdc5c1592007-02-28 18:57:32 +0000192 return ConstantRange(V->getValue());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000193}
Chris Lattner53e677a2004-04-02 20:23:17 +0000194
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000195const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000196
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000197void SCEVConstant::print(std::ostream &OS) const {
198 WriteAsOperand(OS, V, false);
199}
Chris Lattner53e677a2004-04-02 20:23:17 +0000200
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000201// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
202// particular input. Don't use a SCEVHandle here, or else the object will
203// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000204static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
205 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000206
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000207SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
208 : SCEV(scTruncate), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000209 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000210 "Cannot truncate non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000211 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
212 && "This is not a truncating conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000213}
Chris Lattner53e677a2004-04-02 20:23:17 +0000214
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000215SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000216 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000217}
Chris Lattner53e677a2004-04-02 20:23:17 +0000218
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219ConstantRange SCEVTruncateExpr::getValueRange() const {
Reid Spencerc6aedf72007-02-28 22:03:51 +0000220 return getOperand()->getValueRange().truncate(getBitWidth());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000221}
Chris Lattner53e677a2004-04-02 20:23:17 +0000222
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000223void SCEVTruncateExpr::print(std::ostream &OS) const {
224 OS << "(truncate " << *Op << " to " << *Ty << ")";
225}
226
227// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
228// particular input. Don't use a SCEVHandle here, or else the object will never
229// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000230static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
231 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000232
233SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000234 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000235 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000236 "Cannot zero extend non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000237 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
238 && "This is not an extending conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000239}
240
241SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000242 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000243}
244
245ConstantRange SCEVZeroExtendExpr::getValueRange() const {
Reid Spencerc6aedf72007-02-28 22:03:51 +0000246 return getOperand()->getValueRange().zeroExtend(getBitWidth());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000247}
248
249void SCEVZeroExtendExpr::print(std::ostream &OS) const {
250 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
251}
252
Dan Gohmand19534a2007-06-15 14:38:12 +0000253// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
254// particular input. Don't use a SCEVHandle here, or else the object will never
255// be deleted!
256static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
257 SCEVSignExtendExpr*> > SCEVSignExtends;
258
259SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
260 : SCEV(scSignExtend), Op(op), Ty(ty) {
261 assert(Op->getType()->isInteger() && Ty->isInteger() &&
262 "Cannot sign extend non-integer value!");
263 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
264 && "This is not an extending conversion!");
265}
266
267SCEVSignExtendExpr::~SCEVSignExtendExpr() {
268 SCEVSignExtends->erase(std::make_pair(Op, Ty));
269}
270
271ConstantRange SCEVSignExtendExpr::getValueRange() const {
272 return getOperand()->getValueRange().signExtend(getBitWidth());
273}
274
275void SCEVSignExtendExpr::print(std::ostream &OS) const {
276 OS << "(signextend " << *Op << " to " << *Ty << ")";
277}
278
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000279// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
280// particular input. Don't use a SCEVHandle here, or else the object will never
281// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000282static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
283 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000284
285SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000286 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
287 std::vector<SCEV*>(Operands.begin(),
288 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000289}
290
291void SCEVCommutativeExpr::print(std::ostream &OS) const {
292 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
293 const char *OpStr = getOperationStr();
294 OS << "(" << *Operands[0];
295 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
296 OS << OpStr << *Operands[i];
297 OS << ")";
298}
299
Chris Lattner4dc534c2005-02-13 04:37:18 +0000300SCEVHandle SCEVCommutativeExpr::
301replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000302 const SCEVHandle &Conc,
303 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000304 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000305 SCEVHandle H =
306 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000307 if (H != getOperand(i)) {
308 std::vector<SCEVHandle> NewOps;
309 NewOps.reserve(getNumOperands());
310 for (unsigned j = 0; j != i; ++j)
311 NewOps.push_back(getOperand(j));
312 NewOps.push_back(H);
313 for (++i; i != e; ++i)
314 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000315 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000316
317 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000318 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000319 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000320 return SE.getMulExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000321 else
322 assert(0 && "Unknown commutative expr!");
323 }
324 }
325 return this;
326}
327
328
Chris Lattner60a05cc2006-04-01 04:48:52 +0000329// SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000330// input. Don't use a SCEVHandle here, or else the object will never be
331// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000332static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
333 SCEVSDivExpr*> > SCEVSDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000334
Chris Lattner60a05cc2006-04-01 04:48:52 +0000335SCEVSDivExpr::~SCEVSDivExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000336 SCEVSDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000337}
338
Chris Lattner60a05cc2006-04-01 04:48:52 +0000339void SCEVSDivExpr::print(std::ostream &OS) const {
340 OS << "(" << *LHS << " /s " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000341}
342
Chris Lattner60a05cc2006-04-01 04:48:52 +0000343const Type *SCEVSDivExpr::getType() const {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000344 return LHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000345}
346
347// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
348// particular input. Don't use a SCEVHandle here, or else the object will never
349// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000350static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
351 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000352
353SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000354 SCEVAddRecExprs->erase(std::make_pair(L,
355 std::vector<SCEV*>(Operands.begin(),
356 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000357}
358
Chris Lattner4dc534c2005-02-13 04:37:18 +0000359SCEVHandle SCEVAddRecExpr::
360replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000361 const SCEVHandle &Conc,
362 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000363 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000364 SCEVHandle H =
365 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000366 if (H != getOperand(i)) {
367 std::vector<SCEVHandle> NewOps;
368 NewOps.reserve(getNumOperands());
369 for (unsigned j = 0; j != i; ++j)
370 NewOps.push_back(getOperand(j));
371 NewOps.push_back(H);
372 for (++i; i != e; ++i)
373 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000374 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000375
Dan Gohman246b2562007-10-22 18:31:58 +0000376 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000377 }
378 }
379 return this;
380}
381
382
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000383bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
384 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000385 // contain L and if the start is invariant.
386 return !QueryLoop->contains(L->getHeader()) &&
387 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000388}
389
390
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000391void SCEVAddRecExpr::print(std::ostream &OS) const {
392 OS << "{" << *Operands[0];
393 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
394 OS << ",+," << *Operands[i];
395 OS << "}<" << L->getHeader()->getName() + ">";
396}
Chris Lattner53e677a2004-04-02 20:23:17 +0000397
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000398// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
399// value. Don't use a SCEVHandle here, or else the object will never be
400// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000401static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000402
Chris Lattnerb3364092006-10-04 21:49:37 +0000403SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000404
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000405bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
406 // All non-instruction values are loop invariant. All instructions are loop
407 // invariant if they are not contained in the specified loop.
408 if (Instruction *I = dyn_cast<Instruction>(V))
409 return !L->contains(I->getParent());
410 return true;
411}
Chris Lattner53e677a2004-04-02 20:23:17 +0000412
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000413const Type *SCEVUnknown::getType() const {
414 return V->getType();
415}
Chris Lattner53e677a2004-04-02 20:23:17 +0000416
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000417void SCEVUnknown::print(std::ostream &OS) const {
418 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000419}
420
Chris Lattner8d741b82004-06-20 06:23:15 +0000421//===----------------------------------------------------------------------===//
422// SCEV Utilities
423//===----------------------------------------------------------------------===//
424
425namespace {
426 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
427 /// than the complexity of the RHS. This comparator is used to canonicalize
428 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000429 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Chris Lattner8d741b82004-06-20 06:23:15 +0000430 bool operator()(SCEV *LHS, SCEV *RHS) {
431 return LHS->getSCEVType() < RHS->getSCEVType();
432 }
433 };
434}
435
436/// GroupByComplexity - Given a list of SCEV objects, order them by their
437/// complexity, and group objects of the same complexity together by value.
438/// When this routine is finished, we know that any duplicates in the vector are
439/// consecutive and that complexity is monotonically increasing.
440///
441/// Note that we go take special precautions to ensure that we get determinstic
442/// results from this routine. In other words, we don't want the results of
443/// this to depend on where the addresses of various SCEV objects happened to
444/// land in memory.
445///
446static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
447 if (Ops.size() < 2) return; // Noop
448 if (Ops.size() == 2) {
449 // This is the common case, which also happens to be trivially simple.
450 // Special case it.
451 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
452 std::swap(Ops[0], Ops[1]);
453 return;
454 }
455
456 // Do the rough sort by complexity.
457 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
458
459 // Now that we are sorted by complexity, group elements of the same
460 // complexity. Note that this is, at worst, N^2, but the vector is likely to
461 // be extremely short in practice. Note that we take this approach because we
462 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000463 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000464 SCEV *S = Ops[i];
465 unsigned Complexity = S->getSCEVType();
466
467 // If there are any objects of the same complexity and same value as this
468 // one, group them.
469 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
470 if (Ops[j] == S) { // Found a duplicate.
471 // Move it to immediately after i'th element.
472 std::swap(Ops[i+1], Ops[j]);
473 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000474 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000475 }
476 }
477 }
478}
479
Chris Lattner53e677a2004-04-02 20:23:17 +0000480
Chris Lattner53e677a2004-04-02 20:23:17 +0000481
482//===----------------------------------------------------------------------===//
483// Simple SCEV method implementations
484//===----------------------------------------------------------------------===//
485
486/// getIntegerSCEV - Given an integer or FP type, create a constant for the
487/// specified signed integer value and return a SCEV for the constant.
Dan Gohman246b2562007-10-22 18:31:58 +0000488SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000489 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000490 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000491 C = Constant::getNullValue(Ty);
492 else if (Ty->isFloatingPoint())
Dale Johannesen43421b32007-09-06 18:13:44 +0000493 C = ConstantFP::get(Ty, APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
494 APFloat::IEEEdouble, Val));
Reid Spencere4d87aa2006-12-23 06:05:41 +0000495 else
Reid Spencerb83eb642006-10-20 07:07:24 +0000496 C = ConstantInt::get(Ty, Val);
Dan Gohman246b2562007-10-22 18:31:58 +0000497 return getUnknown(C);
Chris Lattner53e677a2004-04-02 20:23:17 +0000498}
499
500/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
501/// input value to the specified type. If the type must be extended, it is zero
502/// extended.
Dan Gohman246b2562007-10-22 18:31:58 +0000503static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty,
504 ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000505 const Type *SrcTy = V->getType();
Chris Lattner42a75512007-01-15 02:27:26 +0000506 assert(SrcTy->isInteger() && Ty->isInteger() &&
Chris Lattner53e677a2004-04-02 20:23:17 +0000507 "Cannot truncate or zero extend with non-integer arguments!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000508 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
Chris Lattner53e677a2004-04-02 20:23:17 +0000509 return V; // No conversion
Reid Spencere7ca0422007-01-08 01:26:33 +0000510 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
Dan Gohman246b2562007-10-22 18:31:58 +0000511 return SE.getTruncateExpr(V, Ty);
512 return SE.getZeroExtendExpr(V, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000513}
514
515/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
516///
Dan Gohman246b2562007-10-22 18:31:58 +0000517SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000518 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman246b2562007-10-22 18:31:58 +0000519 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000520
Dan Gohman246b2562007-10-22 18:31:58 +0000521 return getMulExpr(V, getIntegerSCEV(-1, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000522}
523
524/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
525///
Dan Gohman246b2562007-10-22 18:31:58 +0000526SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
527 const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000528 // X - Y --> X + -Y
Dan Gohman246b2562007-10-22 18:31:58 +0000529 return getAddExpr(LHS, getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000530}
531
532
Chris Lattner53e677a2004-04-02 20:23:17 +0000533/// PartialFact - Compute V!/(V-NumSteps)!
Dan Gohman246b2562007-10-22 18:31:58 +0000534static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps,
535 ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000536 // Handle this case efficiently, it is common to have constant iteration
537 // counts while computing loop exit values.
538 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Zhou Sheng414de4d2007-04-07 17:48:27 +0000539 const APInt& Val = SC->getValue()->getValue();
Reid Spencerdc5c1592007-02-28 18:57:32 +0000540 APInt Result(Val.getBitWidth(), 1);
Chris Lattner53e677a2004-04-02 20:23:17 +0000541 for (; NumSteps; --NumSteps)
542 Result *= Val-(NumSteps-1);
Dan Gohman246b2562007-10-22 18:31:58 +0000543 return SE.getConstant(Result);
Chris Lattner53e677a2004-04-02 20:23:17 +0000544 }
545
546 const Type *Ty = V->getType();
547 if (NumSteps == 0)
Dan Gohman246b2562007-10-22 18:31:58 +0000548 return SE.getIntegerSCEV(1, Ty);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000549
Chris Lattner53e677a2004-04-02 20:23:17 +0000550 SCEVHandle Result = V;
551 for (unsigned i = 1; i != NumSteps; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +0000552 Result = SE.getMulExpr(Result, SE.getMinusSCEV(V,
553 SE.getIntegerSCEV(i, Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000554 return Result;
555}
556
557
558/// evaluateAtIteration - Return the value of this chain of recurrences at
559/// the specified iteration number. We can evaluate this recurrence by
560/// multiplying each element in the chain by the binomial coefficient
561/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
562///
563/// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
564///
565/// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
566/// Is the binomial equation safe using modular arithmetic??
567///
Dan Gohman246b2562007-10-22 18:31:58 +0000568SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
569 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000570 SCEVHandle Result = getStart();
571 int Divisor = 1;
572 const Type *Ty = It->getType();
573 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000574 SCEVHandle BC = PartialFact(It, i, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +0000575 Divisor *= i;
Anton Korobeynikov4e1a0e32007-11-15 18:33:16 +0000576 SCEVHandle Val = SE.getSDivExpr(SE.getMulExpr(BC, getOperand(i)),
Dan Gohman246b2562007-10-22 18:31:58 +0000577 SE.getIntegerSCEV(Divisor,Ty));
578 Result = SE.getAddExpr(Result, Val);
Chris Lattner53e677a2004-04-02 20:23:17 +0000579 }
580 return Result;
581}
582
583
584//===----------------------------------------------------------------------===//
585// SCEV Expression folder implementations
586//===----------------------------------------------------------------------===//
587
Dan Gohman246b2562007-10-22 18:31:58 +0000588SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000589 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000590 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000591 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000592
593 // If the input value is a chrec scev made out of constants, truncate
594 // all of the constants.
595 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
596 std::vector<SCEVHandle> Operands;
597 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
598 // FIXME: This should allow truncation of other expression types!
599 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman246b2562007-10-22 18:31:58 +0000600 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000601 else
602 break;
603 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman246b2562007-10-22 18:31:58 +0000604 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000605 }
606
Chris Lattnerb3364092006-10-04 21:49:37 +0000607 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000608 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
609 return Result;
610}
611
Dan Gohman246b2562007-10-22 18:31:58 +0000612SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000613 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000614 return getUnknown(
Reid Spencerd977d862006-12-12 23:36:14 +0000615 ConstantExpr::getZExt(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000616
617 // FIXME: If the input value is a chrec scev, and we can prove that the value
618 // did not overflow the old, smaller, value, we can zero extend all of the
619 // operands (often constants). This would allow analysis of something like
620 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
621
Chris Lattnerb3364092006-10-04 21:49:37 +0000622 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000623 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
624 return Result;
625}
626
Dan Gohman246b2562007-10-22 18:31:58 +0000627SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmand19534a2007-06-15 14:38:12 +0000628 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000629 return getUnknown(
Dan Gohmand19534a2007-06-15 14:38:12 +0000630 ConstantExpr::getSExt(SC->getValue(), Ty));
631
632 // FIXME: If the input value is a chrec scev, and we can prove that the value
633 // did not overflow the old, smaller, value, we can sign extend all of the
634 // operands (often constants). This would allow analysis of something like
635 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
636
637 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
638 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
639 return Result;
640}
641
Chris Lattner53e677a2004-04-02 20:23:17 +0000642// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman246b2562007-10-22 18:31:58 +0000643SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000644 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000645 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000646
647 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000648 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000649
650 // If there are any constants, fold them together.
651 unsigned Idx = 0;
652 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
653 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000654 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000655 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
656 // We found two constants, fold them together!
Zhou Shengfdc1e162007-04-07 17:40:57 +0000657 Constant *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
658 RHSC->getValue()->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +0000659 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
Dan Gohman246b2562007-10-22 18:31:58 +0000660 Ops[0] = getConstant(CI);
Chris Lattner53e677a2004-04-02 20:23:17 +0000661 Ops.erase(Ops.begin()+1); // Erase the folded element
662 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000663 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000664 } else {
665 // If we couldn't fold the expression, move to the next constant. Note
666 // that this is impossible to happen in practice because we always
667 // constant fold constant ints to constant ints.
668 ++Idx;
669 }
670 }
671
672 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +0000673 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000674 Ops.erase(Ops.begin());
675 --Idx;
676 }
677 }
678
Chris Lattner627018b2004-04-07 16:16:11 +0000679 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000680
Chris Lattner53e677a2004-04-02 20:23:17 +0000681 // Okay, check to see if the same value occurs in the operand list twice. If
682 // so, merge them together into an multiply expression. Since we sorted the
683 // list, these values are required to be adjacent.
684 const Type *Ty = Ops[0]->getType();
685 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
686 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
687 // Found a match, merge the two values into a multiply, and add any
688 // remaining values to the result.
Dan Gohman246b2562007-10-22 18:31:58 +0000689 SCEVHandle Two = getIntegerSCEV(2, Ty);
690 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +0000691 if (Ops.size() == 2)
692 return Mul;
693 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
694 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +0000695 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000696 }
697
Dan Gohmanf50cd742007-06-18 19:30:09 +0000698 // Now we know the first non-constant operand. Skip past any cast SCEVs.
699 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
700 ++Idx;
701
702 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +0000703 if (Idx < Ops.size()) {
704 bool DeletedAdd = false;
705 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
706 // If we have an add, expand the add operands onto the end of the operands
707 // list.
708 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
709 Ops.erase(Ops.begin()+Idx);
710 DeletedAdd = true;
711 }
712
713 // If we deleted at least one add, we added operands to the end of the list,
714 // and they are not necessarily sorted. Recurse to resort and resimplify
715 // any operands we just aquired.
716 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +0000717 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000718 }
719
720 // Skip over the add expression until we get to a multiply.
721 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
722 ++Idx;
723
724 // If we are adding something to a multiply expression, make sure the
725 // something is not already an operand of the multiply. If so, merge it into
726 // the multiply.
727 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
728 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
729 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
730 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
731 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000732 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000733 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
734 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
735 if (Mul->getNumOperands() != 2) {
736 // If the multiply has more than two operands, we must get the
737 // Y*Z term.
738 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
739 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000740 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000741 }
Dan Gohman246b2562007-10-22 18:31:58 +0000742 SCEVHandle One = getIntegerSCEV(1, Ty);
743 SCEVHandle AddOne = getAddExpr(InnerMul, One);
744 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000745 if (Ops.size() == 2) return OuterMul;
746 if (AddOp < Idx) {
747 Ops.erase(Ops.begin()+AddOp);
748 Ops.erase(Ops.begin()+Idx-1);
749 } else {
750 Ops.erase(Ops.begin()+Idx);
751 Ops.erase(Ops.begin()+AddOp-1);
752 }
753 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000754 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000755 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000756
Chris Lattner53e677a2004-04-02 20:23:17 +0000757 // Check this multiply against other multiplies being added together.
758 for (unsigned OtherMulIdx = Idx+1;
759 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
760 ++OtherMulIdx) {
761 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
762 // If MulOp occurs in OtherMul, we can fold the two multiplies
763 // together.
764 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
765 OMulOp != e; ++OMulOp)
766 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
767 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
768 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
769 if (Mul->getNumOperands() != 2) {
770 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
771 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000772 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000773 }
774 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
775 if (OtherMul->getNumOperands() != 2) {
776 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
777 OtherMul->op_end());
778 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000779 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000780 }
Dan Gohman246b2562007-10-22 18:31:58 +0000781 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
782 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +0000783 if (Ops.size() == 2) return OuterMul;
784 Ops.erase(Ops.begin()+Idx);
785 Ops.erase(Ops.begin()+OtherMulIdx-1);
786 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000787 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000788 }
789 }
790 }
791 }
792
793 // If there are any add recurrences in the operands list, see if any other
794 // added values are loop invariant. If so, we can fold them into the
795 // recurrence.
796 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
797 ++Idx;
798
799 // Scan over all recurrences, trying to fold loop invariants into them.
800 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
801 // Scan all of the other operands to this add and add them to the vector if
802 // they are loop invariant w.r.t. the recurrence.
803 std::vector<SCEVHandle> LIOps;
804 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
805 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
806 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
807 LIOps.push_back(Ops[i]);
808 Ops.erase(Ops.begin()+i);
809 --i; --e;
810 }
811
812 // If we found some loop invariants, fold them into the recurrence.
813 if (!LIOps.empty()) {
814 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
815 LIOps.push_back(AddRec->getStart());
816
817 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +0000818 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000819
Dan Gohman246b2562007-10-22 18:31:58 +0000820 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000821 // If all of the other operands were loop invariant, we are done.
822 if (Ops.size() == 1) return NewRec;
823
824 // Otherwise, add the folded AddRec by the non-liv parts.
825 for (unsigned i = 0;; ++i)
826 if (Ops[i] == AddRec) {
827 Ops[i] = NewRec;
828 break;
829 }
Dan Gohman246b2562007-10-22 18:31:58 +0000830 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000831 }
832
833 // Okay, if there weren't any loop invariants to be folded, check to see if
834 // there are multiple AddRec's with the same loop induction variable being
835 // added together. If so, we can fold them.
836 for (unsigned OtherIdx = Idx+1;
837 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
838 if (OtherIdx != Idx) {
839 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
840 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
841 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
842 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
843 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
844 if (i >= NewOps.size()) {
845 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
846 OtherAddRec->op_end());
847 break;
848 }
Dan Gohman246b2562007-10-22 18:31:58 +0000849 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +0000850 }
Dan Gohman246b2562007-10-22 18:31:58 +0000851 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000852
853 if (Ops.size() == 2) return NewAddRec;
854
855 Ops.erase(Ops.begin()+Idx);
856 Ops.erase(Ops.begin()+OtherIdx-1);
857 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +0000858 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000859 }
860 }
861
862 // Otherwise couldn't fold anything into this recurrence. Move onto the
863 // next one.
864 }
865
866 // Okay, it looks like we really DO need an add expr. Check to see if we
867 // already have one, otherwise create a new one.
868 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000869 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
870 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000871 if (Result == 0) Result = new SCEVAddExpr(Ops);
872 return Result;
873}
874
875
Dan Gohman246b2562007-10-22 18:31:58 +0000876SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000877 assert(!Ops.empty() && "Cannot get empty mul!");
878
879 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000880 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000881
882 // If there are any constants, fold them together.
883 unsigned Idx = 0;
884 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
885
886 // C1*(C2+V) -> C1*C2 + C1*V
887 if (Ops.size() == 2)
888 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
889 if (Add->getNumOperands() == 2 &&
890 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +0000891 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
892 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000893
894
895 ++Idx;
896 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
897 // We found two constants, fold them together!
Zhou Shengfdc1e162007-04-07 17:40:57 +0000898 Constant *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
899 RHSC->getValue()->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +0000900 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
Dan Gohman246b2562007-10-22 18:31:58 +0000901 Ops[0] = getConstant(CI);
Chris Lattner53e677a2004-04-02 20:23:17 +0000902 Ops.erase(Ops.begin()+1); // Erase the folded element
903 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000904 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000905 } else {
906 // If we couldn't fold the expression, move to the next constant. Note
907 // that this is impossible to happen in practice because we always
908 // constant fold constant ints to constant ints.
909 ++Idx;
910 }
911 }
912
913 // If we are left with a constant one being multiplied, strip it off.
914 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
915 Ops.erase(Ops.begin());
916 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +0000917 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000918 // If we have a multiply of zero, it will always be zero.
919 return Ops[0];
920 }
921 }
922
923 // Skip over the add expression until we get to a multiply.
924 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
925 ++Idx;
926
927 if (Ops.size() == 1)
928 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000929
Chris Lattner53e677a2004-04-02 20:23:17 +0000930 // If there are mul operands inline them all into this expression.
931 if (Idx < Ops.size()) {
932 bool DeletedMul = false;
933 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
934 // If we have an mul, expand the mul operands onto the end of the operands
935 // list.
936 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
937 Ops.erase(Ops.begin()+Idx);
938 DeletedMul = true;
939 }
940
941 // If we deleted at least one mul, we added operands to the end of the list,
942 // and they are not necessarily sorted. Recurse to resort and resimplify
943 // any operands we just aquired.
944 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +0000945 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000946 }
947
948 // If there are any add recurrences in the operands list, see if any other
949 // added values are loop invariant. If so, we can fold them into the
950 // recurrence.
951 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
952 ++Idx;
953
954 // Scan over all recurrences, trying to fold loop invariants into them.
955 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
956 // Scan all of the other operands to this mul and add them to the vector if
957 // they are loop invariant w.r.t. the recurrence.
958 std::vector<SCEVHandle> LIOps;
959 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
960 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
961 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
962 LIOps.push_back(Ops[i]);
963 Ops.erase(Ops.begin()+i);
964 --i; --e;
965 }
966
967 // If we found some loop invariants, fold them into the recurrence.
968 if (!LIOps.empty()) {
969 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
970 std::vector<SCEVHandle> NewOps;
971 NewOps.reserve(AddRec->getNumOperands());
972 if (LIOps.size() == 1) {
973 SCEV *Scale = LIOps[0];
974 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +0000975 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000976 } else {
977 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
978 std::vector<SCEVHandle> MulOps(LIOps);
979 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +0000980 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +0000981 }
982 }
983
Dan Gohman246b2562007-10-22 18:31:58 +0000984 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000985
986 // If all of the other operands were loop invariant, we are done.
987 if (Ops.size() == 1) return NewRec;
988
989 // Otherwise, multiply the folded AddRec by the non-liv parts.
990 for (unsigned i = 0;; ++i)
991 if (Ops[i] == AddRec) {
992 Ops[i] = NewRec;
993 break;
994 }
Dan Gohman246b2562007-10-22 18:31:58 +0000995 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000996 }
997
998 // Okay, if there weren't any loop invariants to be folded, check to see if
999 // there are multiple AddRec's with the same loop induction variable being
1000 // multiplied together. If so, we can fold them.
1001 for (unsigned OtherIdx = Idx+1;
1002 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1003 if (OtherIdx != Idx) {
1004 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1005 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1006 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1007 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman246b2562007-10-22 18:31:58 +00001008 SCEVHandle NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001009 G->getStart());
Dan Gohman246b2562007-10-22 18:31:58 +00001010 SCEVHandle B = F->getStepRecurrence(*this);
1011 SCEVHandle D = G->getStepRecurrence(*this);
1012 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1013 getMulExpr(G, B),
1014 getMulExpr(B, D));
1015 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1016 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001017 if (Ops.size() == 2) return NewAddRec;
1018
1019 Ops.erase(Ops.begin()+Idx);
1020 Ops.erase(Ops.begin()+OtherIdx-1);
1021 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001022 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001023 }
1024 }
1025
1026 // Otherwise couldn't fold anything into this recurrence. Move onto the
1027 // next one.
1028 }
1029
1030 // Okay, it looks like we really DO need an mul expr. Check to see if we
1031 // already have one, otherwise create a new one.
1032 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001033 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1034 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001035 if (Result == 0)
1036 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001037 return Result;
1038}
1039
Anton Korobeynikov4e1a0e32007-11-15 18:33:16 +00001040SCEVHandle ScalarEvolution::getSDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001041 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1042 if (RHSC->getValue()->equalsInt(1))
Reid Spencer1628cec2006-10-26 06:15:43 +00001043 return LHS; // X sdiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +00001044 if (RHSC->getValue()->isAllOnesValue())
Dan Gohman246b2562007-10-22 18:31:58 +00001045 return getNegativeSCEV(LHS); // X sdiv -1 --> -x
Chris Lattner53e677a2004-04-02 20:23:17 +00001046
1047 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1048 Constant *LHSCV = LHSC->getValue();
1049 Constant *RHSCV = RHSC->getValue();
Dan Gohman246b2562007-10-22 18:31:58 +00001050 return getUnknown(ConstantExpr::getSDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001051 }
1052 }
1053
1054 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1055
Chris Lattnerb3364092006-10-04 21:49:37 +00001056 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
Chris Lattner60a05cc2006-04-01 04:48:52 +00001057 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001058 return Result;
1059}
1060
1061
1062/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1063/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001064SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Chris Lattner53e677a2004-04-02 20:23:17 +00001065 const SCEVHandle &Step, const Loop *L) {
1066 std::vector<SCEVHandle> Operands;
1067 Operands.push_back(Start);
1068 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1069 if (StepChrec->getLoop() == L) {
1070 Operands.insert(Operands.end(), StepChrec->op_begin(),
1071 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001072 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001073 }
1074
1075 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001076 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001077}
1078
1079/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1080/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001081SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Chris Lattner53e677a2004-04-02 20:23:17 +00001082 const Loop *L) {
1083 if (Operands.size() == 1) return Operands[0];
1084
1085 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
Reid Spencercae57542007-03-02 00:28:52 +00001086 if (StepC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001087 Operands.pop_back();
Dan Gohman246b2562007-10-22 18:31:58 +00001088 return getAddRecExpr(Operands, L); // { X,+,0 } --> X
Chris Lattner53e677a2004-04-02 20:23:17 +00001089 }
1090
1091 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001092 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1093 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001094 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1095 return Result;
1096}
1097
Dan Gohman246b2562007-10-22 18:31:58 +00001098SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001099 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001100 return getConstant(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001101 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001102 if (Result == 0) Result = new SCEVUnknown(V);
1103 return Result;
1104}
1105
Chris Lattner53e677a2004-04-02 20:23:17 +00001106
1107//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001108// ScalarEvolutionsImpl Definition and Implementation
1109//===----------------------------------------------------------------------===//
1110//
1111/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1112/// evolution code.
1113///
1114namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001115 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohman246b2562007-10-22 18:31:58 +00001116 /// SE - A reference to the public ScalarEvolution object.
1117 ScalarEvolution &SE;
1118
Chris Lattner53e677a2004-04-02 20:23:17 +00001119 /// F - The function we are analyzing.
1120 ///
1121 Function &F;
1122
1123 /// LI - The loop information for the function we are currently analyzing.
1124 ///
1125 LoopInfo &LI;
1126
1127 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1128 /// things.
1129 SCEVHandle UnknownValue;
1130
1131 /// Scalars - This is a cache of the scalars we have analyzed so far.
1132 ///
1133 std::map<Value*, SCEVHandle> Scalars;
1134
1135 /// IterationCounts - Cache the iteration count of the loops for this
1136 /// function as they are computed.
1137 std::map<const Loop*, SCEVHandle> IterationCounts;
1138
Chris Lattner3221ad02004-04-17 22:58:41 +00001139 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1140 /// the PHI instructions that we attempt to compute constant evolutions for.
1141 /// This allows us to avoid potentially expensive recomputation of these
1142 /// properties. An instruction maps to null if we are unable to compute its
1143 /// exit value.
1144 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001145
Chris Lattner53e677a2004-04-02 20:23:17 +00001146 public:
Dan Gohman246b2562007-10-22 18:31:58 +00001147 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1148 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
Chris Lattner53e677a2004-04-02 20:23:17 +00001149
1150 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1151 /// expression and create a new one.
1152 SCEVHandle getSCEV(Value *V);
1153
Chris Lattnera0740fb2005-08-09 23:36:33 +00001154 /// hasSCEV - Return true if the SCEV for this value has already been
1155 /// computed.
1156 bool hasSCEV(Value *V) const {
1157 return Scalars.count(V);
1158 }
1159
1160 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1161 /// the specified value.
1162 void setSCEV(Value *V, const SCEVHandle &H) {
1163 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1164 assert(isNew && "This entry already existed!");
1165 }
1166
1167
Chris Lattner53e677a2004-04-02 20:23:17 +00001168 /// getSCEVAtScope - Compute the value of the specified expression within
1169 /// the indicated loop (which may be null to indicate in no loop). If the
1170 /// expression cannot be evaluated, return UnknownValue itself.
1171 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1172
1173
1174 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1175 /// an analyzable loop-invariant iteration count.
1176 bool hasLoopInvariantIterationCount(const Loop *L);
1177
1178 /// getIterationCount - If the specified loop has a predictable iteration
1179 /// count, return it. Note that it is not valid to call this method on a
1180 /// loop without a loop-invariant iteration count.
1181 SCEVHandle getIterationCount(const Loop *L);
1182
Dan Gohman5cec4db2007-06-19 14:28:31 +00001183 /// deleteValueFromRecords - This method should be called by the
1184 /// client before it removes a value from the program, to make sure
Chris Lattner53e677a2004-04-02 20:23:17 +00001185 /// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001186 void deleteValueFromRecords(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001187
1188 private:
1189 /// createSCEV - We know that there is no SCEV for the specified value.
1190 /// Analyze the expression.
1191 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001192
1193 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1194 /// SCEVs.
1195 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001196
1197 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1198 /// for the specified instruction and replaces any references to the
1199 /// symbolic value SymName with the specified value. This is used during
1200 /// PHI resolution.
1201 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1202 const SCEVHandle &SymName,
1203 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001204
1205 /// ComputeIterationCount - Compute the number of times the specified loop
1206 /// will iterate.
1207 SCEVHandle ComputeIterationCount(const Loop *L);
1208
Chris Lattner673e02b2004-10-12 01:49:27 +00001209 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Zhou Sheng83428362007-04-07 17:12:38 +00001210 /// 'setcc load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00001211 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1212 Constant *RHS,
1213 const Loop *L,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001214 ICmpInst::Predicate p);
Chris Lattner673e02b2004-10-12 01:49:27 +00001215
Chris Lattner7980fb92004-04-17 18:36:24 +00001216 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1217 /// constant number of times (the condition evolves only from constants),
1218 /// try to evaluate a few iterations of the loop until we get the exit
1219 /// condition gets a value of ExitWhen (true or false). If we cannot
1220 /// evaluate the trip count of the loop, return UnknownValue.
1221 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1222 bool ExitWhen);
1223
Chris Lattner53e677a2004-04-02 20:23:17 +00001224 /// HowFarToZero - Return the number of times a backedge comparing the
1225 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001226 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001227 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1228
1229 /// HowFarToNonZero - Return the number of times a backedge checking the
1230 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001231 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001232 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001233
Chris Lattnerdb25de42005-08-15 23:33:51 +00001234 /// HowManyLessThans - Return the number of times a backedge containing the
1235 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001236 /// UnknownValue. isSigned specifies whether the less-than is signed.
1237 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1238 bool isSigned);
Chris Lattnerdb25de42005-08-15 23:33:51 +00001239
Chris Lattner3221ad02004-04-17 22:58:41 +00001240 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1241 /// in the header of its containing loop, we know the loop executes a
1242 /// constant number of times, and the PHI node is just a recurrence
1243 /// involving constants, fold it.
Reid Spencere8019bb2007-03-01 07:25:48 +00001244 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
Chris Lattner3221ad02004-04-17 22:58:41 +00001245 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001246 };
1247}
1248
1249//===----------------------------------------------------------------------===//
1250// Basic SCEV Analysis and PHI Idiom Recognition Code
1251//
1252
Dan Gohman5cec4db2007-06-19 14:28:31 +00001253/// deleteValueFromRecords - This method should be called by the
Chris Lattner53e677a2004-04-02 20:23:17 +00001254/// client before it removes an instruction from the program, to make sure
1255/// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001256void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1257 SmallVector<Value *, 16> Worklist;
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001258
Dan Gohman5cec4db2007-06-19 14:28:31 +00001259 if (Scalars.erase(V)) {
1260 if (PHINode *PN = dyn_cast<PHINode>(V))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001261 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman5cec4db2007-06-19 14:28:31 +00001262 Worklist.push_back(V);
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001263 }
1264
1265 while (!Worklist.empty()) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001266 Value *VV = Worklist.back();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001267 Worklist.pop_back();
1268
Dan Gohman5cec4db2007-06-19 14:28:31 +00001269 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001270 UI != UE; ++UI) {
Nick Lewycky51e844b2007-06-06 11:26:20 +00001271 Instruction *Inst = cast<Instruction>(*UI);
1272 if (Scalars.erase(Inst)) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001273 if (PHINode *PN = dyn_cast<PHINode>(VV))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001274 ConstantEvolutionLoopExitValue.erase(PN);
1275 Worklist.push_back(Inst);
1276 }
1277 }
1278 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001279}
1280
1281
1282/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1283/// expression and create a new one.
1284SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1285 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1286
1287 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1288 if (I != Scalars.end()) return I->second;
1289 SCEVHandle S = createSCEV(V);
1290 Scalars.insert(std::make_pair(V, S));
1291 return S;
1292}
1293
Chris Lattner4dc534c2005-02-13 04:37:18 +00001294/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1295/// the specified instruction and replaces any references to the symbolic value
1296/// SymName with the specified value. This is used during PHI resolution.
1297void ScalarEvolutionsImpl::
1298ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1299 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001300 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001301 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001302
Chris Lattner4dc534c2005-02-13 04:37:18 +00001303 SCEVHandle NV =
Dan Gohman246b2562007-10-22 18:31:58 +00001304 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001305 if (NV == SI->second) return; // No change.
1306
1307 SI->second = NV; // Update the scalars map!
1308
1309 // Any instruction values that use this instruction might also need to be
1310 // updated!
1311 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1312 UI != E; ++UI)
1313 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1314}
Chris Lattner53e677a2004-04-02 20:23:17 +00001315
1316/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1317/// a loop header, making it a potential recurrence, or it doesn't.
1318///
1319SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1320 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1321 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1322 if (L->getHeader() == PN->getParent()) {
1323 // If it lives in the loop header, it has two incoming values, one
1324 // from outside the loop, and one from inside.
1325 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1326 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001327
Chris Lattner53e677a2004-04-02 20:23:17 +00001328 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman246b2562007-10-22 18:31:58 +00001329 SCEVHandle SymbolicName = SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001330 assert(Scalars.find(PN) == Scalars.end() &&
1331 "PHI node already processed?");
1332 Scalars.insert(std::make_pair(PN, SymbolicName));
1333
1334 // Using this symbolic name for the PHI, analyze the value coming around
1335 // the back-edge.
1336 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1337
1338 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1339 // has a special value for the first iteration of the loop.
1340
1341 // If the value coming around the backedge is an add with the symbolic
1342 // value we just inserted, then we found a simple induction variable!
1343 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1344 // If there is a single occurrence of the symbolic value, replace it
1345 // with a recurrence.
1346 unsigned FoundIndex = Add->getNumOperands();
1347 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1348 if (Add->getOperand(i) == SymbolicName)
1349 if (FoundIndex == e) {
1350 FoundIndex = i;
1351 break;
1352 }
1353
1354 if (FoundIndex != Add->getNumOperands()) {
1355 // Create an add with everything but the specified operand.
1356 std::vector<SCEVHandle> Ops;
1357 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1358 if (i != FoundIndex)
1359 Ops.push_back(Add->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001360 SCEVHandle Accum = SE.getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001361
1362 // This is not a valid addrec if the step amount is varying each
1363 // loop iteration, but is not itself an addrec in this loop.
1364 if (Accum->isLoopInvariant(L) ||
1365 (isa<SCEVAddRecExpr>(Accum) &&
1366 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1367 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman246b2562007-10-22 18:31:58 +00001368 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001369
1370 // Okay, for the entire analysis of this edge we assumed the PHI
1371 // to be symbolic. We now need to go back and update all of the
1372 // entries for the scalars that use the PHI (except for the PHI
1373 // itself) to use the new analyzed value instead of the "symbolic"
1374 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001375 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001376 return PHISCEV;
1377 }
1378 }
Chris Lattner97156e72006-04-26 18:34:07 +00001379 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1380 // Otherwise, this could be a loop like this:
1381 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1382 // In this case, j = {1,+,1} and BEValue is j.
1383 // Because the other in-value of i (0) fits the evolution of BEValue
1384 // i really is an addrec evolution.
1385 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1386 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1387
1388 // If StartVal = j.start - j.stride, we can use StartVal as the
1389 // initial step of the addrec evolution.
Dan Gohman246b2562007-10-22 18:31:58 +00001390 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1391 AddRec->getOperand(1))) {
Chris Lattner97156e72006-04-26 18:34:07 +00001392 SCEVHandle PHISCEV =
Dan Gohman246b2562007-10-22 18:31:58 +00001393 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00001394
1395 // Okay, for the entire analysis of this edge we assumed the PHI
1396 // to be symbolic. We now need to go back and update all of the
1397 // entries for the scalars that use the PHI (except for the PHI
1398 // itself) to use the new analyzed value instead of the "symbolic"
1399 // value.
1400 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1401 return PHISCEV;
1402 }
1403 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001404 }
1405
1406 return SymbolicName;
1407 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001408
Chris Lattner53e677a2004-04-02 20:23:17 +00001409 // If it's not a loop phi, we can't handle it yet.
Dan Gohman246b2562007-10-22 18:31:58 +00001410 return SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001411}
1412
Chris Lattnera17f0392006-12-12 02:26:09 +00001413/// GetConstantFactor - Determine the largest constant factor that S has. For
1414/// example, turn {4,+,8} -> 4. (S umod result) should always equal zero.
Reid Spencer6263cba2007-02-28 23:31:17 +00001415static APInt GetConstantFactor(SCEVHandle S) {
Chris Lattnera17f0392006-12-12 02:26:09 +00001416 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Zhou Sheng414de4d2007-04-07 17:48:27 +00001417 const APInt& V = C->getValue()->getValue();
Reid Spencer6263cba2007-02-28 23:31:17 +00001418 if (!V.isMinValue())
Chris Lattnera17f0392006-12-12 02:26:09 +00001419 return V;
1420 else // Zero is a multiple of everything.
Reid Spencer6263cba2007-02-28 23:31:17 +00001421 return APInt(C->getBitWidth(), 1).shl(C->getBitWidth()-1);
Chris Lattnera17f0392006-12-12 02:26:09 +00001422 }
1423
Reid Spencer9b4aeb32007-03-02 02:59:25 +00001424 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) {
Zhou Sheng83428362007-04-07 17:12:38 +00001425 return GetConstantFactor(T->getOperand()).trunc(
1426 cast<IntegerType>(T->getType())->getBitWidth());
Reid Spencer9b4aeb32007-03-02 02:59:25 +00001427 }
Chris Lattnera17f0392006-12-12 02:26:09 +00001428 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S))
Zhou Sheng83428362007-04-07 17:12:38 +00001429 return GetConstantFactor(E->getOperand()).zext(
1430 cast<IntegerType>(E->getType())->getBitWidth());
Dan Gohmand19534a2007-06-15 14:38:12 +00001431 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S))
1432 return GetConstantFactor(E->getOperand()).sext(
1433 cast<IntegerType>(E->getType())->getBitWidth());
Chris Lattnera17f0392006-12-12 02:26:09 +00001434
1435 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1436 // The result is the min of all operands.
Zhou Sheng83428362007-04-07 17:12:38 +00001437 APInt Res(GetConstantFactor(A->getOperand(0)));
Reid Spencer6263cba2007-02-28 23:31:17 +00001438 for (unsigned i = 1, e = A->getNumOperands();
Reid Spencer07976052007-03-04 01:25:35 +00001439 i != e && Res.ugt(APInt(Res.getBitWidth(),1)); ++i) {
1440 APInt Tmp(GetConstantFactor(A->getOperand(i)));
Reid Spencer07976052007-03-04 01:25:35 +00001441 Res = APIntOps::umin(Res, Tmp);
1442 }
Chris Lattnera17f0392006-12-12 02:26:09 +00001443 return Res;
1444 }
1445
1446 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1447 // The result is the product of all the operands.
Zhou Sheng83428362007-04-07 17:12:38 +00001448 APInt Res(GetConstantFactor(M->getOperand(0)));
Reid Spencer07976052007-03-04 01:25:35 +00001449 for (unsigned i = 1, e = M->getNumOperands(); i != e; ++i) {
1450 APInt Tmp(GetConstantFactor(M->getOperand(i)));
Reid Spencer07976052007-03-04 01:25:35 +00001451 Res *= Tmp;
1452 }
Chris Lattnera17f0392006-12-12 02:26:09 +00001453 return Res;
1454 }
1455
1456 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Chris Lattner75de5ab2006-12-19 01:16:02 +00001457 // For now, we just handle linear expressions.
1458 if (A->getNumOperands() == 2) {
1459 // We want the GCD between the start and the stride value.
Zhou Sheng83428362007-04-07 17:12:38 +00001460 APInt Start(GetConstantFactor(A->getOperand(0)));
Reid Spencer6263cba2007-02-28 23:31:17 +00001461 if (Start == 1)
Zhou Sheng83428362007-04-07 17:12:38 +00001462 return Start;
1463 APInt Stride(GetConstantFactor(A->getOperand(1)));
Reid Spencer6263cba2007-02-28 23:31:17 +00001464 return APIntOps::GreatestCommonDivisor(Start, Stride);
Chris Lattner75de5ab2006-12-19 01:16:02 +00001465 }
Chris Lattnera17f0392006-12-12 02:26:09 +00001466 }
1467
1468 // SCEVSDivExpr, SCEVUnknown.
Reid Spencer6263cba2007-02-28 23:31:17 +00001469 return APInt(S->getBitWidth(), 1);
Chris Lattnera17f0392006-12-12 02:26:09 +00001470}
Chris Lattner53e677a2004-04-02 20:23:17 +00001471
1472/// createSCEV - We know that there is no SCEV for the specified value.
1473/// Analyze the expression.
1474///
1475SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1476 if (Instruction *I = dyn_cast<Instruction>(V)) {
1477 switch (I->getOpcode()) {
1478 case Instruction::Add:
Dan Gohman246b2562007-10-22 18:31:58 +00001479 return SE.getAddExpr(getSCEV(I->getOperand(0)),
1480 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001481 case Instruction::Mul:
Dan Gohman246b2562007-10-22 18:31:58 +00001482 return SE.getMulExpr(getSCEV(I->getOperand(0)),
1483 getSCEV(I->getOperand(1)));
Reid Spencer1628cec2006-10-26 06:15:43 +00001484 case Instruction::SDiv:
Dan Gohman246b2562007-10-22 18:31:58 +00001485 return SE.getSDivExpr(getSCEV(I->getOperand(0)),
1486 getSCEV(I->getOperand(1)));
Anton Korobeynikov4e1a0e32007-11-15 18:33:16 +00001487 break;
1488
Chris Lattner53e677a2004-04-02 20:23:17 +00001489 case Instruction::Sub:
Dan Gohman246b2562007-10-22 18:31:58 +00001490 return SE.getMinusSCEV(getSCEV(I->getOperand(0)),
1491 getSCEV(I->getOperand(1)));
Chris Lattnera17f0392006-12-12 02:26:09 +00001492 case Instruction::Or:
1493 // If the RHS of the Or is a constant, we may have something like:
1494 // X*4+1 which got turned into X*4|1. Handle this as an add so loop
1495 // optimizations will transparently handle this case.
1496 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1497 SCEVHandle LHS = getSCEV(I->getOperand(0));
Zhou Shengfdc1e162007-04-07 17:40:57 +00001498 APInt CommonFact(GetConstantFactor(LHS));
Reid Spencer6263cba2007-02-28 23:31:17 +00001499 assert(!CommonFact.isMinValue() &&
1500 "Common factor should at least be 1!");
1501 if (CommonFact.ugt(CI->getValue())) {
Chris Lattnera17f0392006-12-12 02:26:09 +00001502 // If the LHS is a multiple that is larger than the RHS, use +.
Dan Gohman246b2562007-10-22 18:31:58 +00001503 return SE.getAddExpr(LHS,
1504 getSCEV(I->getOperand(1)));
Chris Lattnera17f0392006-12-12 02:26:09 +00001505 }
1506 }
1507 break;
Chris Lattner2811f2a2007-04-02 05:41:38 +00001508 case Instruction::Xor:
1509 // If the RHS of the xor is a signbit, then this is just an add.
1510 // Instcombine turns add of signbit into xor as a strength reduction step.
1511 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1512 if (CI->getValue().isSignBit())
Dan Gohman246b2562007-10-22 18:31:58 +00001513 return SE.getAddExpr(getSCEV(I->getOperand(0)),
1514 getSCEV(I->getOperand(1)));
Chris Lattner2811f2a2007-04-02 05:41:38 +00001515 }
1516 break;
1517
Chris Lattner53e677a2004-04-02 20:23:17 +00001518 case Instruction::Shl:
1519 // Turn shift left of a constant amount into a multiply.
1520 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfdc1e162007-04-07 17:40:57 +00001521 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1522 Constant *X = ConstantInt::get(
1523 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohman246b2562007-10-22 18:31:58 +00001524 return SE.getMulExpr(getSCEV(I->getOperand(0)), getSCEV(X));
Chris Lattner53e677a2004-04-02 20:23:17 +00001525 }
1526 break;
1527
Reid Spencer3da59db2006-11-27 01:05:10 +00001528 case Instruction::Trunc:
Dan Gohman246b2562007-10-22 18:31:58 +00001529 return SE.getTruncateExpr(getSCEV(I->getOperand(0)), I->getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001530
1531 case Instruction::ZExt:
Dan Gohman246b2562007-10-22 18:31:58 +00001532 return SE.getZeroExtendExpr(getSCEV(I->getOperand(0)), I->getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001533
Dan Gohmand19534a2007-06-15 14:38:12 +00001534 case Instruction::SExt:
Dan Gohman246b2562007-10-22 18:31:58 +00001535 return SE.getSignExtendExpr(getSCEV(I->getOperand(0)), I->getType());
Dan Gohmand19534a2007-06-15 14:38:12 +00001536
Reid Spencer3da59db2006-11-27 01:05:10 +00001537 case Instruction::BitCast:
1538 // BitCasts are no-op casts so we just eliminate the cast.
Chris Lattner42a75512007-01-15 02:27:26 +00001539 if (I->getType()->isInteger() &&
1540 I->getOperand(0)->getType()->isInteger())
Chris Lattner82e8a8f2006-12-11 00:12:31 +00001541 return getSCEV(I->getOperand(0));
1542 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001543
1544 case Instruction::PHI:
1545 return createNodeForPHI(cast<PHINode>(I));
1546
1547 default: // We cannot analyze this expression.
1548 break;
1549 }
1550 }
1551
Dan Gohman246b2562007-10-22 18:31:58 +00001552 return SE.getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001553}
1554
1555
1556
1557//===----------------------------------------------------------------------===//
1558// Iteration Count Computation Code
1559//
1560
1561/// getIterationCount - If the specified loop has a predictable iteration
1562/// count, return it. Note that it is not valid to call this method on a
1563/// loop without a loop-invariant iteration count.
1564SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1565 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1566 if (I == IterationCounts.end()) {
1567 SCEVHandle ItCount = ComputeIterationCount(L);
1568 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1569 if (ItCount != UnknownValue) {
1570 assert(ItCount->isLoopInvariant(L) &&
1571 "Computed trip count isn't loop invariant for loop!");
1572 ++NumTripCountsComputed;
1573 } else if (isa<PHINode>(L->getHeader()->begin())) {
1574 // Only count loops that have phi nodes as not being computable.
1575 ++NumTripCountsNotComputed;
1576 }
1577 }
1578 return I->second;
1579}
1580
1581/// ComputeIterationCount - Compute the number of times the specified loop
1582/// will iterate.
1583SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1584 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patelb7211a22007-08-21 00:31:24 +00001585 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001586 L->getExitBlocks(ExitBlocks);
1587 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001588
1589 // Okay, there is one exit block. Try to find the condition that causes the
1590 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001591 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001592
1593 BasicBlock *ExitingBlock = 0;
1594 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1595 PI != E; ++PI)
1596 if (L->contains(*PI)) {
1597 if (ExitingBlock == 0)
1598 ExitingBlock = *PI;
1599 else
1600 return UnknownValue; // More than one block exiting!
1601 }
1602 assert(ExitingBlock && "No exits from loop, something is broken!");
1603
1604 // Okay, we've computed the exiting block. See what condition causes us to
1605 // exit.
1606 //
1607 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00001608 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1609 if (ExitBr == 0) return UnknownValue;
1610 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00001611
1612 // At this point, we know we have a conditional branch that determines whether
1613 // the loop is exited. However, we don't know if the branch is executed each
1614 // time through the loop. If not, then the execution count of the branch will
1615 // not be equal to the trip count of the loop.
1616 //
1617 // Currently we check for this by checking to see if the Exit branch goes to
1618 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00001619 // times as the loop. We also handle the case where the exit block *is* the
1620 // loop header. This is common for un-rotated loops. More extensive analysis
1621 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001622 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00001623 ExitBr->getSuccessor(1) != L->getHeader() &&
1624 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00001625 return UnknownValue;
1626
Reid Spencere4d87aa2006-12-23 06:05:41 +00001627 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1628
1629 // If its not an integer comparison then compute it the hard way.
1630 // Note that ICmpInst deals with pointer comparisons too so we must check
1631 // the type of the operand.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001632 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Chris Lattner7980fb92004-04-17 18:36:24 +00001633 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1634 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001635
Reid Spencere4d87aa2006-12-23 06:05:41 +00001636 // If the condition was exit on true, convert the condition to exit on false
1637 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00001638 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001639 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001640 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00001641 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001642
1643 // Handle common loops like: for (X = "string"; *X; ++X)
1644 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1645 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1646 SCEVHandle ItCnt =
1647 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1648 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1649 }
1650
Chris Lattner53e677a2004-04-02 20:23:17 +00001651 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1652 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1653
1654 // Try to evaluate any dependencies out of the loop.
1655 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1656 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1657 Tmp = getSCEVAtScope(RHS, L);
1658 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1659
Reid Spencere4d87aa2006-12-23 06:05:41 +00001660 // At this point, we would like to compute how many iterations of the
1661 // loop the predicate will return true for these inputs.
Chris Lattner53e677a2004-04-02 20:23:17 +00001662 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1663 // If there is a constant, force it into the RHS.
1664 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001665 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00001666 }
1667
1668 // FIXME: think about handling pointer comparisons! i.e.:
1669 // while (P != P+100) ++P;
1670
1671 // If we have a comparison of a chrec against a constant, try to use value
1672 // ranges to answer this query.
1673 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1674 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1675 if (AddRec->getLoop() == L) {
1676 // Form the comparison range using the constant of the correct type so
1677 // that the ConstantRange class knows to do a signed or unsigned
1678 // comparison.
1679 ConstantInt *CompVal = RHSC->getValue();
1680 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00001681 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00001682 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00001683 if (CompVal) {
1684 // Form the constant range.
Reid Spencerc6aedf72007-02-28 22:03:51 +00001685 ConstantRange CompRange(
1686 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001687
Dan Gohman246b2562007-10-22 18:31:58 +00001688 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00001689 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1690 }
1691 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001692
Chris Lattner53e677a2004-04-02 20:23:17 +00001693 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001694 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00001695 // Convert to: while (X-Y != 0)
Dan Gohman246b2562007-10-22 18:31:58 +00001696 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001697 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00001698 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001699 }
1700 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00001701 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman246b2562007-10-22 18:31:58 +00001702 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001703 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00001704 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001705 }
1706 case ICmpInst::ICMP_SLT: {
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001707 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001708 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001709 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001710 }
1711 case ICmpInst::ICMP_SGT: {
Dan Gohman246b2562007-10-22 18:31:58 +00001712 SCEVHandle TC = HowManyLessThans(SE.getNegativeSCEV(LHS),
1713 SE.getNegativeSCEV(RHS), L, true);
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001714 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1715 break;
1716 }
1717 case ICmpInst::ICMP_ULT: {
1718 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
1719 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1720 break;
1721 }
1722 case ICmpInst::ICMP_UGT: {
Dan Gohman246b2562007-10-22 18:31:58 +00001723 SCEVHandle TC = HowManyLessThans(SE.getNegativeSCEV(LHS),
1724 SE.getNegativeSCEV(RHS), L, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001725 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001726 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001727 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001728 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001729#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001730 cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00001731 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendlinge8156192006-12-07 01:30:32 +00001732 cerr << "[unsigned] ";
1733 cerr << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00001734 << Instruction::getOpcodeName(Instruction::ICmp)
1735 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001736#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00001737 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001738 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001739 return ComputeIterationCountExhaustively(L, ExitCond,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001740 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00001741}
1742
Chris Lattner673e02b2004-10-12 01:49:27 +00001743static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00001744EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
1745 ScalarEvolution &SE) {
1746 SCEVHandle InVal = SE.getConstant(C);
1747 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00001748 assert(isa<SCEVConstant>(Val) &&
1749 "Evaluation of SCEV at constant didn't fold correctly?");
1750 return cast<SCEVConstant>(Val)->getValue();
1751}
1752
1753/// GetAddressedElementFromGlobal - Given a global variable with an initializer
1754/// and a GEP expression (missing the pointer index) indexing into it, return
1755/// the addressed element of the initializer or null if the index expression is
1756/// invalid.
1757static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001758GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00001759 const std::vector<ConstantInt*> &Indices) {
1760 Constant *Init = GV->getInitializer();
1761 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001762 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00001763 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1764 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1765 Init = cast<Constant>(CS->getOperand(Idx));
1766 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1767 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1768 Init = cast<Constant>(CA->getOperand(Idx));
1769 } else if (isa<ConstantAggregateZero>(Init)) {
1770 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1771 assert(Idx < STy->getNumElements() && "Bad struct index!");
1772 Init = Constant::getNullValue(STy->getElementType(Idx));
1773 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1774 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1775 Init = Constant::getNullValue(ATy->getElementType());
1776 } else {
1777 assert(0 && "Unknown constant aggregate type!");
1778 }
1779 return 0;
1780 } else {
1781 return 0; // Unknown initializer type
1782 }
1783 }
1784 return Init;
1785}
1786
1787/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1788/// 'setcc load X, cst', try to se if we can compute the trip count.
1789SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001790ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001791 const Loop *L,
1792 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00001793 if (LI->isVolatile()) return UnknownValue;
1794
1795 // Check to see if the loaded pointer is a getelementptr of a global.
1796 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1797 if (!GEP) return UnknownValue;
1798
1799 // Make sure that it is really a constant global we are gepping, with an
1800 // initializer, and make sure the first IDX is really 0.
1801 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1802 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1803 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1804 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1805 return UnknownValue;
1806
1807 // Okay, we allow one non-constant index into the GEP instruction.
1808 Value *VarIdx = 0;
1809 std::vector<ConstantInt*> Indexes;
1810 unsigned VarIdxNum = 0;
1811 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1812 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1813 Indexes.push_back(CI);
1814 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1815 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1816 VarIdx = GEP->getOperand(i);
1817 VarIdxNum = i-2;
1818 Indexes.push_back(0);
1819 }
1820
1821 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1822 // Check to see if X is a loop variant variable value now.
1823 SCEVHandle Idx = getSCEV(VarIdx);
1824 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1825 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1826
1827 // We can only recognize very limited forms of loop index expressions, in
1828 // particular, only affine AddRec's like {C1,+,C2}.
1829 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1830 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1831 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1832 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1833 return UnknownValue;
1834
1835 unsigned MaxSteps = MaxBruteForceIterations;
1836 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001837 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00001838 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohman246b2562007-10-22 18:31:58 +00001839 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00001840
1841 // Form the GEP offset.
1842 Indexes[VarIdxNum] = Val;
1843
1844 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1845 if (Result == 0) break; // Cannot compute!
1846
1847 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001848 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001849 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00001850 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00001851#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001852 cerr << "\n***\n*** Computed loop count " << *ItCst
1853 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1854 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00001855#endif
1856 ++NumArrayLenItCounts;
Dan Gohman246b2562007-10-22 18:31:58 +00001857 return SE.getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00001858 }
1859 }
1860 return UnknownValue;
1861}
1862
1863
Chris Lattner3221ad02004-04-17 22:58:41 +00001864/// CanConstantFold - Return true if we can constant fold an instruction of the
1865/// specified type, assuming that all operands were constants.
1866static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00001867 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00001868 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1869 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001870
Chris Lattner3221ad02004-04-17 22:58:41 +00001871 if (const CallInst *CI = dyn_cast<CallInst>(I))
1872 if (const Function *F = CI->getCalledFunction())
1873 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1874 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00001875}
1876
Chris Lattner3221ad02004-04-17 22:58:41 +00001877/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1878/// in the loop that V is derived from. We allow arbitrary operations along the
1879/// way, but the operands of an operation must either be constants or a value
1880/// derived from a constant PHI. If this expression does not fit with these
1881/// constraints, return null.
1882static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1883 // If this is not an instruction, or if this is an instruction outside of the
1884 // loop, it can't be derived from a loop PHI.
1885 Instruction *I = dyn_cast<Instruction>(V);
1886 if (I == 0 || !L->contains(I->getParent())) return 0;
1887
1888 if (PHINode *PN = dyn_cast<PHINode>(I))
1889 if (L->getHeader() == I->getParent())
1890 return PN;
1891 else
1892 // We don't currently keep track of the control flow needed to evaluate
1893 // PHIs, so we cannot handle PHIs inside of loops.
1894 return 0;
1895
1896 // If we won't be able to constant fold this expression even if the operands
1897 // are constants, return early.
1898 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001899
Chris Lattner3221ad02004-04-17 22:58:41 +00001900 // Otherwise, we can evaluate this instruction if all of its operands are
1901 // constant or derived from a PHI node themselves.
1902 PHINode *PHI = 0;
1903 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1904 if (!(isa<Constant>(I->getOperand(Op)) ||
1905 isa<GlobalValue>(I->getOperand(Op)))) {
1906 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1907 if (P == 0) return 0; // Not evolving from PHI
1908 if (PHI == 0)
1909 PHI = P;
1910 else if (PHI != P)
1911 return 0; // Evolving from multiple different PHIs.
1912 }
1913
1914 // This is a expression evolving from a constant PHI!
1915 return PHI;
1916}
1917
1918/// EvaluateExpression - Given an expression that passes the
1919/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1920/// in the loop has the value PHIVal. If we can't fold this expression for some
1921/// reason, return null.
1922static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1923 if (isa<PHINode>(V)) return PHIVal;
Chris Lattner3221ad02004-04-17 22:58:41 +00001924 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
Reid Spencere8404342004-07-18 00:18:30 +00001925 return GV;
1926 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00001927 Instruction *I = cast<Instruction>(V);
1928
1929 std::vector<Constant*> Operands;
1930 Operands.resize(I->getNumOperands());
1931
1932 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1933 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1934 if (Operands[i] == 0) return 0;
1935 }
1936
Chris Lattner2e3a1d12007-01-30 23:52:44 +00001937 return ConstantFoldInstOperands(I, &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00001938}
1939
1940/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1941/// in the header of its containing loop, we know the loop executes a
1942/// constant number of times, and the PHI node is just a recurrence
1943/// involving constants, fold it.
1944Constant *ScalarEvolutionsImpl::
Reid Spencere8019bb2007-03-01 07:25:48 +00001945getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00001946 std::map<PHINode*, Constant*>::iterator I =
1947 ConstantEvolutionLoopExitValue.find(PN);
1948 if (I != ConstantEvolutionLoopExitValue.end())
1949 return I->second;
1950
Reid Spencere8019bb2007-03-01 07:25:48 +00001951 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00001952 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1953
1954 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1955
1956 // Since the loop is canonicalized, the PHI node must have two entries. One
1957 // entry must be a constant (coming in from outside of the loop), and the
1958 // second must be derived from the same PHI.
1959 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1960 Constant *StartCST =
1961 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1962 if (StartCST == 0)
1963 return RetVal = 0; // Must be a constant.
1964
1965 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1966 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1967 if (PN2 != PN)
1968 return RetVal = 0; // Not derived from same PHI.
1969
1970 // Execute the loop symbolically to determine the exit value.
Reid Spencere8019bb2007-03-01 07:25:48 +00001971 if (Its.getActiveBits() >= 32)
1972 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00001973
Reid Spencere8019bb2007-03-01 07:25:48 +00001974 unsigned NumIterations = Its.getZExtValue(); // must be in range
1975 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00001976 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1977 if (IterationNum == NumIterations)
1978 return RetVal = PHIVal; // Got exit value!
1979
1980 // Compute the value of the PHI node for the next iteration.
1981 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1982 if (NextPHI == PHIVal)
1983 return RetVal = NextPHI; // Stopped evolving!
1984 if (NextPHI == 0)
1985 return 0; // Couldn't evaluate!
1986 PHIVal = NextPHI;
1987 }
1988}
1989
Chris Lattner7980fb92004-04-17 18:36:24 +00001990/// ComputeIterationCountExhaustively - If the trip is known to execute a
1991/// constant number of times (the condition evolves only from constants),
1992/// try to evaluate a few iterations of the loop until we get the exit
1993/// condition gets a value of ExitWhen (true or false). If we cannot
1994/// evaluate the trip count of the loop, return UnknownValue.
1995SCEVHandle ScalarEvolutionsImpl::
1996ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1997 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1998 if (PN == 0) return UnknownValue;
1999
2000 // Since the loop is canonicalized, the PHI node must have two entries. One
2001 // entry must be a constant (coming in from outside of the loop), and the
2002 // second must be derived from the same PHI.
2003 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2004 Constant *StartCST =
2005 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2006 if (StartCST == 0) return UnknownValue; // Must be a constant.
2007
2008 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2009 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2010 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2011
2012 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2013 // the loop symbolically to determine when the condition gets a value of
2014 // "ExitWhen".
2015 unsigned IterationNum = 0;
2016 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2017 for (Constant *PHIVal = StartCST;
2018 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002019 ConstantInt *CondVal =
2020 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00002021
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002022 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00002023 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002024
Reid Spencere8019bb2007-03-01 07:25:48 +00002025 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002026 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00002027 ++NumBruteForceTripCountsComputed;
Dan Gohman246b2562007-10-22 18:31:58 +00002028 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00002029 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002030
Chris Lattner3221ad02004-04-17 22:58:41 +00002031 // Compute the value of the PHI node for the next iteration.
2032 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2033 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00002034 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00002035 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00002036 }
2037
2038 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00002039 return UnknownValue;
2040}
2041
2042/// getSCEVAtScope - Compute the value of the specified expression within the
2043/// indicated loop (which may be null to indicate in no loop). If the
2044/// expression cannot be evaluated, return UnknownValue.
2045SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2046 // FIXME: this should be turned into a virtual method on SCEV!
2047
Chris Lattner3221ad02004-04-17 22:58:41 +00002048 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002049
Chris Lattner3221ad02004-04-17 22:58:41 +00002050 // If this instruction is evolves from a constant-evolving PHI, compute the
2051 // exit value from the loop without using SCEVs.
2052 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2053 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2054 const Loop *LI = this->LI[I->getParent()];
2055 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2056 if (PHINode *PN = dyn_cast<PHINode>(I))
2057 if (PN->getParent() == LI->getHeader()) {
2058 // Okay, there is no closed form solution for the PHI node. Check
2059 // to see if the loop that contains it has a known iteration count.
2060 // If so, we may be able to force computation of the exit value.
2061 SCEVHandle IterationCount = getIterationCount(LI);
2062 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2063 // Okay, we know how many times the containing loop executes. If
2064 // this is a constant evolving PHI node, get the final value at
2065 // the specified iteration number.
2066 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencere8019bb2007-03-01 07:25:48 +00002067 ICC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00002068 LI);
Dan Gohman246b2562007-10-22 18:31:58 +00002069 if (RV) return SE.getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00002070 }
2071 }
2072
Reid Spencer09906f32006-12-04 21:33:23 +00002073 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00002074 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00002075 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00002076 // result. This is particularly useful for computing loop exit values.
2077 if (CanConstantFold(I)) {
2078 std::vector<Constant*> Operands;
2079 Operands.reserve(I->getNumOperands());
2080 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2081 Value *Op = I->getOperand(i);
2082 if (Constant *C = dyn_cast<Constant>(Op)) {
2083 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002084 } else {
2085 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2086 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
Reid Spencerd977d862006-12-12 23:36:14 +00002087 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2088 Op->getType(),
2089 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002090 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2091 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
Reid Spencerd977d862006-12-12 23:36:14 +00002092 Operands.push_back(ConstantExpr::getIntegerCast(C,
2093 Op->getType(),
2094 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002095 else
2096 return V;
2097 } else {
2098 return V;
2099 }
2100 }
2101 }
Chris Lattner2e3a1d12007-01-30 23:52:44 +00002102 Constant *C =ConstantFoldInstOperands(I, &Operands[0], Operands.size());
Dan Gohman246b2562007-10-22 18:31:58 +00002103 return SE.getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002104 }
2105 }
2106
2107 // This is some other type of SCEVUnknown, just return it.
2108 return V;
2109 }
2110
Chris Lattner53e677a2004-04-02 20:23:17 +00002111 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2112 // Avoid performing the look-up in the common case where the specified
2113 // expression has no loop-variant portions.
2114 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2115 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2116 if (OpAtScope != Comm->getOperand(i)) {
2117 if (OpAtScope == UnknownValue) return UnknownValue;
2118 // Okay, at least one of these operands is loop variant but might be
2119 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002120 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002121 NewOps.push_back(OpAtScope);
2122
2123 for (++i; i != e; ++i) {
2124 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2125 if (OpAtScope == UnknownValue) return UnknownValue;
2126 NewOps.push_back(OpAtScope);
2127 }
2128 if (isa<SCEVAddExpr>(Comm))
Dan Gohman246b2562007-10-22 18:31:58 +00002129 return SE.getAddExpr(NewOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00002130 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
Dan Gohman246b2562007-10-22 18:31:58 +00002131 return SE.getMulExpr(NewOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00002132 }
2133 }
2134 // If we got here, all operands are loop invariant.
2135 return Comm;
2136 }
2137
Chris Lattner60a05cc2006-04-01 04:48:52 +00002138 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
2139 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002140 if (LHS == UnknownValue) return LHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002141 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002142 if (RHS == UnknownValue) return RHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002143 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2144 return Div; // must be loop invariant
Dan Gohman246b2562007-10-22 18:31:58 +00002145 return SE.getSDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002146 }
2147
2148 // If this is a loop recurrence for a loop that does not contain L, then we
2149 // are dealing with the final value computed by the loop.
2150 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2151 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2152 // To evaluate this recurrence, we need to know how many times the AddRec
2153 // loop iterates. Compute this now.
2154 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2155 if (IterationCount == UnknownValue) return UnknownValue;
2156 IterationCount = getTruncateOrZeroExtend(IterationCount,
Dan Gohman246b2562007-10-22 18:31:58 +00002157 AddRec->getType(), SE);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002158
Chris Lattner53e677a2004-04-02 20:23:17 +00002159 // If the value is affine, simplify the expression evaluation to just
2160 // Start + Step*IterationCount.
2161 if (AddRec->isAffine())
Dan Gohman246b2562007-10-22 18:31:58 +00002162 return SE.getAddExpr(AddRec->getStart(),
2163 SE.getMulExpr(IterationCount,
2164 AddRec->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00002165
2166 // Otherwise, evaluate it the hard way.
Dan Gohman246b2562007-10-22 18:31:58 +00002167 return AddRec->evaluateAtIteration(IterationCount, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002168 }
2169 return UnknownValue;
2170 }
2171
2172 //assert(0 && "Unknown SCEV type!");
2173 return UnknownValue;
2174}
2175
2176
2177/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2178/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2179/// might be the same) or two SCEVCouldNotCompute objects.
2180///
2181static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman246b2562007-10-22 18:31:58 +00002182SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002183 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Reid Spencere8019bb2007-03-01 07:25:48 +00002184 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2185 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2186 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002187
Chris Lattner53e677a2004-04-02 20:23:17 +00002188 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00002189 if (!LC || !MC || !NC) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002190 SCEV *CNC = new SCEVCouldNotCompute();
2191 return std::make_pair(CNC, CNC);
2192 }
2193
Reid Spencere8019bb2007-03-01 07:25:48 +00002194 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00002195 const APInt &L = LC->getValue()->getValue();
2196 const APInt &M = MC->getValue()->getValue();
2197 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00002198 APInt Two(BitWidth, 2);
2199 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002200
Reid Spencere8019bb2007-03-01 07:25:48 +00002201 {
2202 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00002203 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00002204 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2205 // The B coefficient is M-N/2
2206 APInt B(M);
2207 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002208
Reid Spencere8019bb2007-03-01 07:25:48 +00002209 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00002210 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00002211
Reid Spencere8019bb2007-03-01 07:25:48 +00002212 // Compute the B^2-4ac term.
2213 APInt SqrtTerm(B);
2214 SqrtTerm *= B;
2215 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00002216
Reid Spencere8019bb2007-03-01 07:25:48 +00002217 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2218 // integer value or else APInt::sqrt() will assert.
2219 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002220
Reid Spencere8019bb2007-03-01 07:25:48 +00002221 // Compute the two solutions for the quadratic formula.
2222 // The divisions must be performed as signed divisions.
2223 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00002224 APInt TwoA( A << 1 );
Reid Spencere8019bb2007-03-01 07:25:48 +00002225 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2226 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002227
Dan Gohman246b2562007-10-22 18:31:58 +00002228 return std::make_pair(SE.getConstant(Solution1),
2229 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00002230 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00002231}
2232
2233/// HowFarToZero - Return the number of times a backedge comparing the specified
2234/// value to zero will execute. If not computable, return UnknownValue
2235SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2236 // If the value is a constant
2237 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2238 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00002239 if (C->getValue()->isZero()) return C;
Chris Lattner53e677a2004-04-02 20:23:17 +00002240 return UnknownValue; // Otherwise it will loop infinitely.
2241 }
2242
2243 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2244 if (!AddRec || AddRec->getLoop() != L)
2245 return UnknownValue;
2246
2247 if (AddRec->isAffine()) {
2248 // If this is an affine expression the execution count of this branch is
2249 // equal to:
2250 //
2251 // (0 - Start/Step) iff Start % Step == 0
2252 //
2253 // Get the initial value for the loop.
2254 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002255 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002256 SCEVHandle Step = AddRec->getOperand(1);
2257
2258 Step = getSCEVAtScope(Step, L->getParentLoop());
2259
2260 // Figure out if Start % Step == 0.
2261 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2262 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2263 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
Dan Gohman246b2562007-10-22 18:31:58 +00002264 return SE.getNegativeSCEV(Start); // 0 - Start/1 == -Start
Chris Lattner53e677a2004-04-02 20:23:17 +00002265 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2266 return Start; // 0 - Start/-1 == Start
2267
2268 // Check to see if Start is divisible by SC with no remainder.
2269 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2270 ConstantInt *StartCC = StartC->getValue();
2271 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
Reid Spencer0a783f72006-11-02 01:53:59 +00002272 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002273 if (Rem->isNullValue()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002274 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
Dan Gohman246b2562007-10-22 18:31:58 +00002275 return SE.getUnknown(Result);
Chris Lattner53e677a2004-04-02 20:23:17 +00002276 }
2277 }
2278 }
Chris Lattner42a75512007-01-15 02:27:26 +00002279 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002280 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2281 // the quadratic equation to solve it.
Dan Gohman246b2562007-10-22 18:31:58 +00002282 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002283 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2284 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2285 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002286#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002287 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2288 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002289#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002290 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002291 if (ConstantInt *CB =
2292 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002293 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002294 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002295 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002296
Chris Lattner53e677a2004-04-02 20:23:17 +00002297 // We can only use this value if the chrec ends up with an exact zero
2298 // value at this index. When solving for "X*X != 5", for example, we
2299 // should not accept a root of 2.
Dan Gohman246b2562007-10-22 18:31:58 +00002300 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002301 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
Reid Spencercae57542007-03-02 00:28:52 +00002302 if (EvalVal->getValue()->isZero())
Chris Lattner53e677a2004-04-02 20:23:17 +00002303 return R1; // We found a quadratic root!
2304 }
2305 }
2306 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002307
Chris Lattner53e677a2004-04-02 20:23:17 +00002308 return UnknownValue;
2309}
2310
2311/// HowFarToNonZero - Return the number of times a backedge checking the
2312/// specified value for nonzero will execute. If not computable, return
2313/// UnknownValue
2314SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2315 // Loops that look like: while (X == 0) are very strange indeed. We don't
2316 // handle them yet except for the trivial case. This could be expanded in the
2317 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002318
Chris Lattner53e677a2004-04-02 20:23:17 +00002319 // If the value is a constant, check to see if it is known to be non-zero
2320 // already. If so, the backedge will execute zero times.
2321 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2322 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002323 Constant *NonZero =
2324 ConstantExpr::getICmp(ICmpInst::ICMP_NE, C->getValue(), Zero);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002325 if (NonZero == ConstantInt::getTrue())
Chris Lattner53e677a2004-04-02 20:23:17 +00002326 return getSCEV(Zero);
2327 return UnknownValue; // Otherwise it will loop infinitely.
2328 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002329
Chris Lattner53e677a2004-04-02 20:23:17 +00002330 // We could implement others, but I really doubt anyone writes loops like
2331 // this, and if they did, they would already be constant folded.
2332 return UnknownValue;
2333}
2334
Chris Lattnerdb25de42005-08-15 23:33:51 +00002335/// HowManyLessThans - Return the number of times a backedge containing the
2336/// specified less-than comparison will execute. If not computable, return
2337/// UnknownValue.
2338SCEVHandle ScalarEvolutionsImpl::
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002339HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00002340 // Only handle: "ADDREC < LoopInvariant".
2341 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2342
2343 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2344 if (!AddRec || AddRec->getLoop() != L)
2345 return UnknownValue;
2346
2347 if (AddRec->isAffine()) {
2348 // FORNOW: We only support unit strides.
Dan Gohman246b2562007-10-22 18:31:58 +00002349 SCEVHandle Zero = SE.getIntegerSCEV(0, RHS->getType());
2350 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
Chris Lattnerdb25de42005-08-15 23:33:51 +00002351 if (AddRec->getOperand(1) != One)
2352 return UnknownValue;
2353
Dan Gohman246b2562007-10-22 18:31:58 +00002354 // The number of iterations for "{n,+,1} < m", is m-n. However, we don't
Chris Lattnerdb25de42005-08-15 23:33:51 +00002355 // know that m is >= n on input to the loop. If it is, the condition return
2356 // true zero times. What we really should return, for full generality, is
2357 // SMAX(0, m-n). Since we cannot check this, we will instead check for a
2358 // canonical loop form: most do-loops will have a check that dominates the
Dan Gohman246b2562007-10-22 18:31:58 +00002359 // loop, that only enters the loop if (n-1)<m. If we can find this check,
Chris Lattnerdb25de42005-08-15 23:33:51 +00002360 // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2361
2362 // Search for the check.
2363 BasicBlock *Preheader = L->getLoopPreheader();
2364 BasicBlock *PreheaderDest = L->getHeader();
2365 if (Preheader == 0) return UnknownValue;
2366
2367 BranchInst *LoopEntryPredicate =
2368 dyn_cast<BranchInst>(Preheader->getTerminator());
2369 if (!LoopEntryPredicate) return UnknownValue;
2370
2371 // This might be a critical edge broken out. If the loop preheader ends in
2372 // an unconditional branch to the loop, check to see if the preheader has a
2373 // single predecessor, and if so, look for its terminator.
2374 while (LoopEntryPredicate->isUnconditional()) {
2375 PreheaderDest = Preheader;
2376 Preheader = Preheader->getSinglePredecessor();
2377 if (!Preheader) return UnknownValue; // Multiple preds.
2378
2379 LoopEntryPredicate =
2380 dyn_cast<BranchInst>(Preheader->getTerminator());
2381 if (!LoopEntryPredicate) return UnknownValue;
2382 }
2383
2384 // Now that we found a conditional branch that dominates the loop, check to
2385 // see if it is the comparison we are looking for.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002386 if (ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition())){
2387 Value *PreCondLHS = ICI->getOperand(0);
2388 Value *PreCondRHS = ICI->getOperand(1);
2389 ICmpInst::Predicate Cond;
2390 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2391 Cond = ICI->getPredicate();
2392 else
2393 Cond = ICI->getInversePredicate();
Chris Lattnerdb25de42005-08-15 23:33:51 +00002394
Reid Spencere4d87aa2006-12-23 06:05:41 +00002395 switch (Cond) {
2396 case ICmpInst::ICMP_UGT:
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002397 if (isSigned) return UnknownValue;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002398 std::swap(PreCondLHS, PreCondRHS);
2399 Cond = ICmpInst::ICMP_ULT;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002400 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002401 case ICmpInst::ICMP_SGT:
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002402 if (!isSigned) return UnknownValue;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002403 std::swap(PreCondLHS, PreCondRHS);
2404 Cond = ICmpInst::ICMP_SLT;
2405 break;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002406 case ICmpInst::ICMP_ULT:
2407 if (isSigned) return UnknownValue;
2408 break;
2409 case ICmpInst::ICMP_SLT:
2410 if (!isSigned) return UnknownValue;
2411 break;
2412 default:
2413 return UnknownValue;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002414 }
Chris Lattnerdb25de42005-08-15 23:33:51 +00002415
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002416 if (PreCondLHS->getType()->isInteger()) {
2417 if (RHS != getSCEV(PreCondRHS))
2418 return UnknownValue; // Not a comparison against 'm'.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002419
Dan Gohman246b2562007-10-22 18:31:58 +00002420 if (SE.getMinusSCEV(AddRec->getOperand(0), One)
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002421 != getSCEV(PreCondLHS))
2422 return UnknownValue; // Not a comparison against 'n-1'.
2423 }
2424 else return UnknownValue;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002425
2426 // cerr << "Computed Loop Trip Count as: "
Dan Gohman246b2562007-10-22 18:31:58 +00002427 // << // *SE.getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
2428 return SE.getMinusSCEV(RHS, AddRec->getOperand(0));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002429 }
2430 else
2431 return UnknownValue;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002432 }
2433
2434 return UnknownValue;
2435}
2436
Chris Lattner53e677a2004-04-02 20:23:17 +00002437/// getNumIterationsInRange - Return the number of iterations of this loop that
2438/// produce values in the specified constant range. Another way of looking at
2439/// this is that it returns the first iteration number where the value is not in
2440/// the condition, thus computing the exit count. If the iteration count can't
2441/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman246b2562007-10-22 18:31:58 +00002442SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2443 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002444 if (Range.isFullSet()) // Infinite loop.
2445 return new SCEVCouldNotCompute();
2446
2447 // If the start is a non-zero constant, shift the range to simplify things.
2448 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00002449 if (!SC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002450 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00002451 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2452 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002453 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2454 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00002455 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002456 // This is strange and shouldn't happen.
2457 return new SCEVCouldNotCompute();
2458 }
2459
2460 // The only time we can solve this is when we have all constant indices.
2461 // Otherwise, we cannot determine the overflow conditions.
2462 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2463 if (!isa<SCEVConstant>(getOperand(i)))
2464 return new SCEVCouldNotCompute();
2465
2466
2467 // Okay at this point we know that all elements of the chrec are constants and
2468 // that the start element is zero.
2469
2470 // First check to see if the range contains zero. If not, the first
2471 // iteration exits.
Reid Spencera6e8a952007-03-01 07:54:15 +00002472 if (!Range.contains(APInt(getBitWidth(),0)))
Dan Gohman246b2562007-10-22 18:31:58 +00002473 return SE.getConstant(ConstantInt::get(getType(),0));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002474
Chris Lattner53e677a2004-04-02 20:23:17 +00002475 if (isAffine()) {
2476 // If this is an affine expression then we have this situation:
2477 // Solve {0,+,A} in Range === Ax in Range
2478
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002479 // We know that zero is in the range. If A is positive then we know that
2480 // the upper value of the range must be the first possible exit value.
2481 // If A is negative then the lower of the range is the last possible loop
2482 // value. Also note that we already checked for a full range.
Reid Spencer581b0d42007-02-28 19:57:34 +00002483 APInt One(getBitWidth(),1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002484 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2485 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00002486
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002487 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00002488 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00002489 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002490
2491 // Evaluate at the exit value. If we really did fall out of the valid
2492 // range, then we computed our trip count, otherwise wrap around or other
2493 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00002494 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002495 if (Range.contains(Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002496 return new SCEVCouldNotCompute(); // Something strange happened
2497
2498 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00002499 assert(Range.contains(
2500 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00002501 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002502 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00002503 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00002504 } else if (isQuadratic()) {
2505 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2506 // quadratic equation to solve it. To do this, we must frame our problem in
2507 // terms of figuring out when zero is crossed, instead of when
2508 // Range.getUpper() is crossed.
2509 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00002510 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
2511 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002512
2513 // Next, solve the constructed addrec
2514 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00002515 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002516 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2517 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2518 if (R1) {
2519 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002520 if (ConstantInt *CB =
2521 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002522 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002523 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002524 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002525
Chris Lattner53e677a2004-04-02 20:23:17 +00002526 // Make sure the root is not off by one. The returned iteration should
2527 // not be in the range, but the previous one should be. When solving
2528 // for "X*X < 5", for example, we should not return a root of 2.
2529 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00002530 R1->getValue(),
2531 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002532 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002533 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00002534 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002535
Dan Gohman246b2562007-10-22 18:31:58 +00002536 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002537 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00002538 return SE.getConstant(NextVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002539 return new SCEVCouldNotCompute(); // Something strange happened
2540 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002541
Chris Lattner53e677a2004-04-02 20:23:17 +00002542 // If R1 was not in the range, then it is a good return value. Make
2543 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00002544 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00002545 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002546 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002547 return R1;
2548 return new SCEVCouldNotCompute(); // Something strange happened
2549 }
2550 }
2551 }
2552
2553 // Fallback, if this is a general polynomial, figure out the progression
2554 // through brute force: evaluate until we find an iteration that fails the
2555 // test. This is likely to be slow, but getting an accurate trip count is
2556 // incredibly important, we will be able to simplify the exit test a lot, and
2557 // we are almost guaranteed to get a trip count in this case.
2558 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00002559 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2560 do {
2561 ++NumBruteForceEvaluations;
Dan Gohman246b2562007-10-22 18:31:58 +00002562 SCEVHandle Val = evaluateAtIteration(SE.getConstant(TestVal), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002563 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2564 return new SCEVCouldNotCompute();
2565
2566 // Check to see if we found the value!
Reid Spencera6e8a952007-03-01 07:54:15 +00002567 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00002568 return SE.getConstant(TestVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002569
2570 // Increment to test the next index.
Zhou Shengfdc1e162007-04-07 17:40:57 +00002571 TestVal = ConstantInt::get(TestVal->getValue()+1);
Chris Lattner53e677a2004-04-02 20:23:17 +00002572 } while (TestVal != EndVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002573
Chris Lattner53e677a2004-04-02 20:23:17 +00002574 return new SCEVCouldNotCompute();
2575}
2576
2577
2578
2579//===----------------------------------------------------------------------===//
2580// ScalarEvolution Class Implementation
2581//===----------------------------------------------------------------------===//
2582
2583bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohman246b2562007-10-22 18:31:58 +00002584 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
Chris Lattner53e677a2004-04-02 20:23:17 +00002585 return false;
2586}
2587
2588void ScalarEvolution::releaseMemory() {
2589 delete (ScalarEvolutionsImpl*)Impl;
2590 Impl = 0;
2591}
2592
2593void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2594 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00002595 AU.addRequiredTransitive<LoopInfo>();
2596}
2597
2598SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2599 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2600}
2601
Chris Lattnera0740fb2005-08-09 23:36:33 +00002602/// hasSCEV - Return true if the SCEV for this value has already been
2603/// computed.
2604bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00002605 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00002606}
2607
2608
2609/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2610/// the specified value.
2611void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2612 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2613}
2614
2615
Chris Lattner53e677a2004-04-02 20:23:17 +00002616SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2617 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2618}
2619
2620bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2621 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2622}
2623
2624SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2625 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2626}
2627
Dan Gohman5cec4db2007-06-19 14:28:31 +00002628void ScalarEvolution::deleteValueFromRecords(Value *V) const {
2629 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002630}
2631
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002632static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00002633 const Loop *L) {
2634 // Print all inner loops first
2635 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2636 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002637
Bill Wendlinge8156192006-12-07 01:30:32 +00002638 cerr << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002639
Devang Patelb7211a22007-08-21 00:31:24 +00002640 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002641 L->getExitBlocks(ExitBlocks);
2642 if (ExitBlocks.size() != 1)
Bill Wendlinge8156192006-12-07 01:30:32 +00002643 cerr << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002644
2645 if (SE->hasLoopInvariantIterationCount(L)) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002646 cerr << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002647 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +00002648 cerr << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002649 }
2650
Bill Wendlinge8156192006-12-07 01:30:32 +00002651 cerr << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00002652}
2653
Reid Spencerce9653c2004-12-07 04:03:45 +00002654void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002655 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2656 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2657
2658 OS << "Classifying expressions for: " << F.getName() << "\n";
2659 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner42a75512007-01-15 02:27:26 +00002660 if (I->getType()->isInteger()) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00002661 OS << *I;
Chris Lattner53e677a2004-04-02 20:23:17 +00002662 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002663 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00002664 SV->print(OS);
2665 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002666
Chris Lattner42a75512007-01-15 02:27:26 +00002667 if ((*I).getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002668 ConstantRange Bounds = SV->getValueRange();
2669 if (!Bounds.isFullSet())
2670 OS << "Bounds: " << Bounds << " ";
2671 }
2672
Chris Lattner6ffe5512004-04-27 15:13:33 +00002673 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002674 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002675 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002676 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2677 OS << "<<Unknown>>";
2678 } else {
2679 OS << *ExitValue;
2680 }
2681 }
2682
2683
2684 OS << "\n";
2685 }
2686
2687 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2688 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2689 PrintLoopInfo(OS, this, *I);
2690}