blob: c05ba8d0ef2700866f5ce8ea7525f421464d1e31 [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
17// can handle. These classes are reference counted, managed by the SCEVHandle
18// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000031//
Chris Lattner53e677a2004-04-02 20:23:17 +000032// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
Chris Lattner53e677a2004-04-02 20:23:17 +000036// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
Chris Lattner3b27d682006-12-19 22:30:33 +000062#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000063#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000064#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000066#include "llvm/GlobalVariable.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
John Criswella1156432005-10-27 15:54:34 +000068#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000069#include "llvm/Analysis/LoopInfo.h"
70#include "llvm/Assembly/Writer.h"
71#include "llvm/Transforms/Scalar.h"
72#include "llvm/Support/CFG.h"
Chris Lattner95255282006-06-28 23:17:24 +000073#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000074#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000075#include "llvm/Support/ConstantRange.h"
76#include "llvm/Support/InstIterator.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000077#include "llvm/Support/ManagedStatic.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000078#include "llvm/Support/MathExtras.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000079#include "llvm/Support/Streams.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000080#include "llvm/ADT/Statistic.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000081#include <ostream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000082#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000083#include <cmath>
Chris Lattner53e677a2004-04-02 20:23:17 +000084using namespace llvm;
85
Chris Lattner3b27d682006-12-19 22:30:33 +000086STATISTIC(NumArrayLenItCounts,
87 "Number of trip counts computed with array length");
88STATISTIC(NumTripCountsComputed,
89 "Number of loops with predictable loop counts");
90STATISTIC(NumTripCountsNotComputed,
91 "Number of loops without predictable loop counts");
92STATISTIC(NumBruteForceTripCountsComputed,
93 "Number of loops with trip counts computed by force");
94
Dan Gohman844731a2008-05-13 00:00:25 +000095static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +000096MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
97 cl::desc("Maximum number of iterations SCEV will "
98 "symbolically execute a constant derived loop"),
99 cl::init(100));
100
Dan Gohman844731a2008-05-13 00:00:25 +0000101static RegisterPass<ScalarEvolution>
102R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000103char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000104
105//===----------------------------------------------------------------------===//
106// SCEV class definitions
107//===----------------------------------------------------------------------===//
108
109//===----------------------------------------------------------------------===//
110// Implementation of the SCEV class.
111//
Chris Lattner53e677a2004-04-02 20:23:17 +0000112SCEV::~SCEV() {}
113void SCEV::dump() const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000114 print(cerr);
Nick Lewyckyd1f5fab2009-01-16 17:07:22 +0000115 cerr << '\n';
Chris Lattner53e677a2004-04-02 20:23:17 +0000116}
117
Reid Spencer581b0d42007-02-28 19:57:34 +0000118uint32_t SCEV::getBitWidth() const {
119 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
120 return ITy->getBitWidth();
121 return 0;
122}
123
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000124bool SCEV::isZero() const {
125 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
126 return SC->getValue()->isZero();
127 return false;
128}
129
Chris Lattner53e677a2004-04-02 20:23:17 +0000130
131SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
132
133bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
134 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000135 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000136}
137
138const Type *SCEVCouldNotCompute::getType() const {
139 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000140 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000141}
142
143bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
144 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
145 return false;
146}
147
Chris Lattner4dc534c2005-02-13 04:37:18 +0000148SCEVHandle SCEVCouldNotCompute::
149replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000150 const SCEVHandle &Conc,
151 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000152 return this;
153}
154
Chris Lattner53e677a2004-04-02 20:23:17 +0000155void SCEVCouldNotCompute::print(std::ostream &OS) const {
156 OS << "***COULDNOTCOMPUTE***";
157}
158
159bool SCEVCouldNotCompute::classof(const SCEV *S) {
160 return S->getSCEVType() == scCouldNotCompute;
161}
162
163
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000164// SCEVConstants - Only allow the creation of one SCEVConstant for any
165// particular value. Don't use a SCEVHandle here, or else the object will
166// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000167static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000168
Chris Lattner53e677a2004-04-02 20:23:17 +0000169
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000170SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000171 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000172}
Chris Lattner53e677a2004-04-02 20:23:17 +0000173
Dan Gohman246b2562007-10-22 18:31:58 +0000174SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Chris Lattnerb3364092006-10-04 21:49:37 +0000175 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000176 if (R == 0) R = new SCEVConstant(V);
177 return R;
178}
Chris Lattner53e677a2004-04-02 20:23:17 +0000179
Dan Gohman246b2562007-10-22 18:31:58 +0000180SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
181 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000182}
183
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000184const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000185
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000186void SCEVConstant::print(std::ostream &OS) const {
187 WriteAsOperand(OS, V, false);
188}
Chris Lattner53e677a2004-04-02 20:23:17 +0000189
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000190// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
191// particular input. Don't use a SCEVHandle here, or else the object will
192// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000193static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
194 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000195
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000196SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
197 : SCEV(scTruncate), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000198 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000199 "Cannot truncate non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000200 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
201 && "This is not a truncating conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000202}
Chris Lattner53e677a2004-04-02 20:23:17 +0000203
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000204SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000205 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000206}
Chris Lattner53e677a2004-04-02 20:23:17 +0000207
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000208void SCEVTruncateExpr::print(std::ostream &OS) const {
209 OS << "(truncate " << *Op << " to " << *Ty << ")";
210}
211
212// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
213// particular input. Don't use a SCEVHandle here, or else the object will never
214// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000215static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
216 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000217
218SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000219 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000220 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000221 "Cannot zero extend non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000222 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
223 && "This is not an extending conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000224}
225
226SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000227 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000228}
229
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000230void SCEVZeroExtendExpr::print(std::ostream &OS) const {
231 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
232}
233
Dan Gohmand19534a2007-06-15 14:38:12 +0000234// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
235// particular input. Don't use a SCEVHandle here, or else the object will never
236// be deleted!
237static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
238 SCEVSignExtendExpr*> > SCEVSignExtends;
239
240SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
241 : SCEV(scSignExtend), Op(op), Ty(ty) {
242 assert(Op->getType()->isInteger() && Ty->isInteger() &&
243 "Cannot sign extend non-integer value!");
244 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
245 && "This is not an extending conversion!");
246}
247
248SCEVSignExtendExpr::~SCEVSignExtendExpr() {
249 SCEVSignExtends->erase(std::make_pair(Op, Ty));
250}
251
Dan Gohmand19534a2007-06-15 14:38:12 +0000252void SCEVSignExtendExpr::print(std::ostream &OS) const {
253 OS << "(signextend " << *Op << " to " << *Ty << ")";
254}
255
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000256// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
257// particular input. Don't use a SCEVHandle here, or else the object will never
258// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000259static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
260 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000261
262SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000263 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
264 std::vector<SCEV*>(Operands.begin(),
265 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000266}
267
268void SCEVCommutativeExpr::print(std::ostream &OS) const {
269 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
270 const char *OpStr = getOperationStr();
271 OS << "(" << *Operands[0];
272 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
273 OS << OpStr << *Operands[i];
274 OS << ")";
275}
276
Chris Lattner4dc534c2005-02-13 04:37:18 +0000277SCEVHandle SCEVCommutativeExpr::
278replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000279 const SCEVHandle &Conc,
280 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000281 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000282 SCEVHandle H =
283 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000284 if (H != getOperand(i)) {
285 std::vector<SCEVHandle> NewOps;
286 NewOps.reserve(getNumOperands());
287 for (unsigned j = 0; j != i; ++j)
288 NewOps.push_back(getOperand(j));
289 NewOps.push_back(H);
290 for (++i; i != e; ++i)
291 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000292 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000293
294 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000295 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000296 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000297 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000298 else if (isa<SCEVSMaxExpr>(this))
299 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000300 else if (isa<SCEVUMaxExpr>(this))
301 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000302 else
303 assert(0 && "Unknown commutative expr!");
304 }
305 }
306 return this;
307}
308
309
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000310// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000311// input. Don't use a SCEVHandle here, or else the object will never be
312// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000313static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000314 SCEVUDivExpr*> > SCEVUDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000315
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000316SCEVUDivExpr::~SCEVUDivExpr() {
317 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000318}
319
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000320void SCEVUDivExpr::print(std::ostream &OS) const {
321 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000322}
323
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000324const Type *SCEVUDivExpr::getType() const {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000325 return LHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000326}
327
328// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
329// particular input. Don't use a SCEVHandle here, or else the object will never
330// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000331static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
332 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000333
334SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000335 SCEVAddRecExprs->erase(std::make_pair(L,
336 std::vector<SCEV*>(Operands.begin(),
337 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000338}
339
Chris Lattner4dc534c2005-02-13 04:37:18 +0000340SCEVHandle SCEVAddRecExpr::
341replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000342 const SCEVHandle &Conc,
343 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000344 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000345 SCEVHandle H =
346 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000347 if (H != getOperand(i)) {
348 std::vector<SCEVHandle> NewOps;
349 NewOps.reserve(getNumOperands());
350 for (unsigned j = 0; j != i; ++j)
351 NewOps.push_back(getOperand(j));
352 NewOps.push_back(H);
353 for (++i; i != e; ++i)
354 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000355 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000356
Dan Gohman246b2562007-10-22 18:31:58 +0000357 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000358 }
359 }
360 return this;
361}
362
363
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000364bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
365 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000366 // contain L and if the start is invariant.
367 return !QueryLoop->contains(L->getHeader()) &&
368 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000369}
370
371
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000372void SCEVAddRecExpr::print(std::ostream &OS) const {
373 OS << "{" << *Operands[0];
374 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
375 OS << ",+," << *Operands[i];
376 OS << "}<" << L->getHeader()->getName() + ">";
377}
Chris Lattner53e677a2004-04-02 20:23:17 +0000378
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000379// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
380// value. Don't use a SCEVHandle here, or else the object will never be
381// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000382static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000383
Chris Lattnerb3364092006-10-04 21:49:37 +0000384SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000385
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000386bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
387 // All non-instruction values are loop invariant. All instructions are loop
388 // invariant if they are not contained in the specified loop.
389 if (Instruction *I = dyn_cast<Instruction>(V))
390 return !L->contains(I->getParent());
391 return true;
392}
Chris Lattner53e677a2004-04-02 20:23:17 +0000393
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000394const Type *SCEVUnknown::getType() const {
395 return V->getType();
396}
Chris Lattner53e677a2004-04-02 20:23:17 +0000397
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000398void SCEVUnknown::print(std::ostream &OS) const {
399 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000400}
401
Chris Lattner8d741b82004-06-20 06:23:15 +0000402//===----------------------------------------------------------------------===//
403// SCEV Utilities
404//===----------------------------------------------------------------------===//
405
406namespace {
407 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
408 /// than the complexity of the RHS. This comparator is used to canonicalize
409 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000410 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000411 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Chris Lattner8d741b82004-06-20 06:23:15 +0000412 return LHS->getSCEVType() < RHS->getSCEVType();
413 }
414 };
415}
416
417/// GroupByComplexity - Given a list of SCEV objects, order them by their
418/// complexity, and group objects of the same complexity together by value.
419/// When this routine is finished, we know that any duplicates in the vector are
420/// consecutive and that complexity is monotonically increasing.
421///
422/// Note that we go take special precautions to ensure that we get determinstic
423/// results from this routine. In other words, we don't want the results of
424/// this to depend on where the addresses of various SCEV objects happened to
425/// land in memory.
426///
427static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
428 if (Ops.size() < 2) return; // Noop
429 if (Ops.size() == 2) {
430 // This is the common case, which also happens to be trivially simple.
431 // Special case it.
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000432 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000433 std::swap(Ops[0], Ops[1]);
434 return;
435 }
436
437 // Do the rough sort by complexity.
438 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
439
440 // Now that we are sorted by complexity, group elements of the same
441 // complexity. Note that this is, at worst, N^2, but the vector is likely to
442 // be extremely short in practice. Note that we take this approach because we
443 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000444 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000445 SCEV *S = Ops[i];
446 unsigned Complexity = S->getSCEVType();
447
448 // If there are any objects of the same complexity and same value as this
449 // one, group them.
450 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
451 if (Ops[j] == S) { // Found a duplicate.
452 // Move it to immediately after i'th element.
453 std::swap(Ops[i+1], Ops[j]);
454 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000455 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000456 }
457 }
458 }
459}
460
Chris Lattner53e677a2004-04-02 20:23:17 +0000461
Chris Lattner53e677a2004-04-02 20:23:17 +0000462
463//===----------------------------------------------------------------------===//
464// Simple SCEV method implementations
465//===----------------------------------------------------------------------===//
466
467/// getIntegerSCEV - Given an integer or FP type, create a constant for the
468/// specified signed integer value and return a SCEV for the constant.
Dan Gohman246b2562007-10-22 18:31:58 +0000469SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000470 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000471 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000472 C = Constant::getNullValue(Ty);
473 else if (Ty->isFloatingPoint())
Chris Lattner02a260a2008-04-20 00:41:09 +0000474 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
475 APFloat::IEEEdouble, Val));
Reid Spencere4d87aa2006-12-23 06:05:41 +0000476 else
Reid Spencerb83eb642006-10-20 07:07:24 +0000477 C = ConstantInt::get(Ty, Val);
Dan Gohman246b2562007-10-22 18:31:58 +0000478 return getUnknown(C);
Chris Lattner53e677a2004-04-02 20:23:17 +0000479}
480
Chris Lattner53e677a2004-04-02 20:23:17 +0000481/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
482///
Dan Gohman246b2562007-10-22 18:31:58 +0000483SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000484 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman246b2562007-10-22 18:31:58 +0000485 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000486
Nick Lewycky178f20a2008-02-20 06:58:55 +0000487 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
Nick Lewycky3e630762008-02-20 06:48:22 +0000488}
489
490/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
491SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
492 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
493 return getUnknown(ConstantExpr::getNot(VC->getValue()));
494
Nick Lewycky178f20a2008-02-20 06:58:55 +0000495 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
Nick Lewycky3e630762008-02-20 06:48:22 +0000496 return getMinusSCEV(AllOnes, V);
Chris Lattner53e677a2004-04-02 20:23:17 +0000497}
498
499/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
500///
Dan Gohman246b2562007-10-22 18:31:58 +0000501SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
502 const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000503 // X - Y --> X + -Y
Dan Gohman246b2562007-10-22 18:31:58 +0000504 return getAddExpr(LHS, getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000505}
506
507
Eli Friedmanb42a6262008-08-04 23:49:06 +0000508/// BinomialCoefficient - Compute BC(It, K). The result has width W.
509// Assume, K > 0.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000510static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedmanb42a6262008-08-04 23:49:06 +0000511 ScalarEvolution &SE,
512 const IntegerType* ResultTy) {
513 // Handle the simplest case efficiently.
514 if (K == 1)
515 return SE.getTruncateOrZeroExtend(It, ResultTy);
516
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000517 // We are using the following formula for BC(It, K):
518 //
519 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
520 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000521 // Suppose, W is the bitwidth of the return value. We must be prepared for
522 // overflow. Hence, we must assure that the result of our computation is
523 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
524 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000525 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000526 // However, this code doesn't use exactly that formula; the formula it uses
527 // is something like the following, where T is the number of factors of 2 in
528 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
529 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000530 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000531 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000532 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000533 // This formula is trivially equivalent to the previous formula. However,
534 // this formula can be implemented much more efficiently. The trick is that
535 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
536 // arithmetic. To do exact division in modular arithmetic, all we have
537 // to do is multiply by the inverse. Therefore, this step can be done at
538 // width W.
539 //
540 // The next issue is how to safely do the division by 2^T. The way this
541 // is done is by doing the multiplication step at a width of at least W + T
542 // bits. This way, the bottom W+T bits of the product are accurate. Then,
543 // when we perform the division by 2^T (which is equivalent to a right shift
544 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
545 // truncated out after the division by 2^T.
546 //
547 // In comparison to just directly using the first formula, this technique
548 // is much more efficient; using the first formula requires W * K bits,
549 // but this formula less than W + K bits. Also, the first formula requires
550 // a division step, whereas this formula only requires multiplies and shifts.
551 //
552 // It doesn't matter whether the subtraction step is done in the calculation
553 // width or the input iteration count's width; if the subtraction overflows,
554 // the result must be zero anyway. We prefer here to do it in the width of
555 // the induction variable because it helps a lot for certain cases; CodeGen
556 // isn't smart enough to ignore the overflow, which leads to much less
557 // efficient code if the width of the subtraction is wider than the native
558 // register width.
559 //
560 // (It's possible to not widen at all by pulling out factors of 2 before
561 // the multiplication; for example, K=2 can be calculated as
562 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
563 // extra arithmetic, so it's not an obvious win, and it gets
564 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000565
Eli Friedmanb42a6262008-08-04 23:49:06 +0000566 // Protection from insane SCEVs; this bound is conservative,
567 // but it probably doesn't matter.
568 if (K > 1000)
569 return new SCEVCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000570
Eli Friedmanb42a6262008-08-04 23:49:06 +0000571 unsigned W = ResultTy->getBitWidth();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000572
Eli Friedmanb42a6262008-08-04 23:49:06 +0000573 // Calculate K! / 2^T and T; we divide out the factors of two before
574 // multiplying for calculating K! / 2^T to avoid overflow.
575 // Other overflow doesn't matter because we only care about the bottom
576 // W bits of the result.
577 APInt OddFactorial(W, 1);
578 unsigned T = 1;
579 for (unsigned i = 3; i <= K; ++i) {
580 APInt Mult(W, i);
581 unsigned TwoFactors = Mult.countTrailingZeros();
582 T += TwoFactors;
583 Mult = Mult.lshr(TwoFactors);
584 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000585 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000586
Eli Friedmanb42a6262008-08-04 23:49:06 +0000587 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000588 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000589
590 // Calcuate 2^T, at width T+W.
591 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
592
593 // Calculate the multiplicative inverse of K! / 2^T;
594 // this multiplication factor will perform the exact division by
595 // K! / 2^T.
596 APInt Mod = APInt::getSignedMinValue(W+1);
597 APInt MultiplyFactor = OddFactorial.zext(W+1);
598 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
599 MultiplyFactor = MultiplyFactor.trunc(W);
600
601 // Calculate the product, at width T+W
602 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
603 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
604 for (unsigned i = 1; i != K; ++i) {
605 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
606 Dividend = SE.getMulExpr(Dividend,
607 SE.getTruncateOrZeroExtend(S, CalculationTy));
608 }
609
610 // Divide by 2^T
611 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
612
613 // Truncate the result, and divide by K! / 2^T.
614
615 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
616 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000617}
618
Chris Lattner53e677a2004-04-02 20:23:17 +0000619/// evaluateAtIteration - Return the value of this chain of recurrences at
620/// the specified iteration number. We can evaluate this recurrence by
621/// multiplying each element in the chain by the binomial coefficient
622/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
623///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000624/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000625///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000626/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000627///
Dan Gohman246b2562007-10-22 18:31:58 +0000628SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
629 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000630 SCEVHandle Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000631 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000632 // The computation is correct in the face of overflow provided that the
633 // multiplication is performed _after_ the evaluation of the binomial
634 // coefficient.
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000635 SCEVHandle Coeff = BinomialCoefficient(It, i, SE,
636 cast<IntegerType>(getType()));
637 if (isa<SCEVCouldNotCompute>(Coeff))
638 return Coeff;
639
640 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000641 }
642 return Result;
643}
644
Chris Lattner53e677a2004-04-02 20:23:17 +0000645//===----------------------------------------------------------------------===//
646// SCEV Expression folder implementations
647//===----------------------------------------------------------------------===//
648
Dan Gohman246b2562007-10-22 18:31:58 +0000649SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000650 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000651 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000652 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000653
654 // If the input value is a chrec scev made out of constants, truncate
655 // all of the constants.
656 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
657 std::vector<SCEVHandle> Operands;
658 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
659 // FIXME: This should allow truncation of other expression types!
660 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman246b2562007-10-22 18:31:58 +0000661 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000662 else
663 break;
664 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman246b2562007-10-22 18:31:58 +0000665 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000666 }
667
Chris Lattnerb3364092006-10-04 21:49:37 +0000668 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000669 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
670 return Result;
671}
672
Dan Gohman246b2562007-10-22 18:31:58 +0000673SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000674 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000675 return getUnknown(
Reid Spencerd977d862006-12-12 23:36:14 +0000676 ConstantExpr::getZExt(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000677
678 // FIXME: If the input value is a chrec scev, and we can prove that the value
679 // did not overflow the old, smaller, value, we can zero extend all of the
680 // operands (often constants). This would allow analysis of something like
681 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
682
Chris Lattnerb3364092006-10-04 21:49:37 +0000683 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000684 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
685 return Result;
686}
687
Dan Gohman246b2562007-10-22 18:31:58 +0000688SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmand19534a2007-06-15 14:38:12 +0000689 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000690 return getUnknown(
Dan Gohmand19534a2007-06-15 14:38:12 +0000691 ConstantExpr::getSExt(SC->getValue(), Ty));
692
693 // FIXME: If the input value is a chrec scev, and we can prove that the value
694 // did not overflow the old, smaller, value, we can sign extend all of the
695 // operands (often constants). This would allow analysis of something like
696 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
697
698 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
699 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
700 return Result;
701}
702
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000703/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
704/// of the input value to the specified type. If the type must be
705/// extended, it is zero extended.
706SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
707 const Type *Ty) {
708 const Type *SrcTy = V->getType();
709 assert(SrcTy->isInteger() && Ty->isInteger() &&
710 "Cannot truncate or zero extend with non-integer arguments!");
711 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
712 return V; // No conversion
713 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
714 return getTruncateExpr(V, Ty);
715 return getZeroExtendExpr(V, Ty);
716}
717
Chris Lattner53e677a2004-04-02 20:23:17 +0000718// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman246b2562007-10-22 18:31:58 +0000719SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000720 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000721 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000722
723 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000724 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000725
726 // If there are any constants, fold them together.
727 unsigned Idx = 0;
728 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
729 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000730 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000731 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
732 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000733 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
734 RHSC->getValue()->getValue());
735 Ops[0] = getConstant(Fold);
736 Ops.erase(Ops.begin()+1); // Erase the folded element
737 if (Ops.size() == 1) return Ops[0];
738 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000739 }
740
741 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +0000742 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000743 Ops.erase(Ops.begin());
744 --Idx;
745 }
746 }
747
Chris Lattner627018b2004-04-07 16:16:11 +0000748 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000749
Chris Lattner53e677a2004-04-02 20:23:17 +0000750 // Okay, check to see if the same value occurs in the operand list twice. If
751 // so, merge them together into an multiply expression. Since we sorted the
752 // list, these values are required to be adjacent.
753 const Type *Ty = Ops[0]->getType();
754 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
755 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
756 // Found a match, merge the two values into a multiply, and add any
757 // remaining values to the result.
Dan Gohman246b2562007-10-22 18:31:58 +0000758 SCEVHandle Two = getIntegerSCEV(2, Ty);
759 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +0000760 if (Ops.size() == 2)
761 return Mul;
762 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
763 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +0000764 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000765 }
766
Dan Gohmanf50cd742007-06-18 19:30:09 +0000767 // Now we know the first non-constant operand. Skip past any cast SCEVs.
768 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
769 ++Idx;
770
771 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +0000772 if (Idx < Ops.size()) {
773 bool DeletedAdd = false;
774 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
775 // If we have an add, expand the add operands onto the end of the operands
776 // list.
777 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
778 Ops.erase(Ops.begin()+Idx);
779 DeletedAdd = true;
780 }
781
782 // If we deleted at least one add, we added operands to the end of the list,
783 // and they are not necessarily sorted. Recurse to resort and resimplify
784 // any operands we just aquired.
785 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +0000786 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000787 }
788
789 // Skip over the add expression until we get to a multiply.
790 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
791 ++Idx;
792
793 // If we are adding something to a multiply expression, make sure the
794 // something is not already an operand of the multiply. If so, merge it into
795 // the multiply.
796 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
797 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
798 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
799 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
800 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000801 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000802 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
803 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
804 if (Mul->getNumOperands() != 2) {
805 // If the multiply has more than two operands, we must get the
806 // Y*Z term.
807 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
808 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000809 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000810 }
Dan Gohman246b2562007-10-22 18:31:58 +0000811 SCEVHandle One = getIntegerSCEV(1, Ty);
812 SCEVHandle AddOne = getAddExpr(InnerMul, One);
813 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000814 if (Ops.size() == 2) return OuterMul;
815 if (AddOp < Idx) {
816 Ops.erase(Ops.begin()+AddOp);
817 Ops.erase(Ops.begin()+Idx-1);
818 } else {
819 Ops.erase(Ops.begin()+Idx);
820 Ops.erase(Ops.begin()+AddOp-1);
821 }
822 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000823 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000824 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000825
Chris Lattner53e677a2004-04-02 20:23:17 +0000826 // Check this multiply against other multiplies being added together.
827 for (unsigned OtherMulIdx = Idx+1;
828 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
829 ++OtherMulIdx) {
830 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
831 // If MulOp occurs in OtherMul, we can fold the two multiplies
832 // together.
833 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
834 OMulOp != e; ++OMulOp)
835 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
836 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
837 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
838 if (Mul->getNumOperands() != 2) {
839 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
840 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000841 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000842 }
843 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
844 if (OtherMul->getNumOperands() != 2) {
845 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
846 OtherMul->op_end());
847 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000848 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000849 }
Dan Gohman246b2562007-10-22 18:31:58 +0000850 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
851 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +0000852 if (Ops.size() == 2) return OuterMul;
853 Ops.erase(Ops.begin()+Idx);
854 Ops.erase(Ops.begin()+OtherMulIdx-1);
855 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000856 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000857 }
858 }
859 }
860 }
861
862 // If there are any add recurrences in the operands list, see if any other
863 // added values are loop invariant. If so, we can fold them into the
864 // recurrence.
865 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
866 ++Idx;
867
868 // Scan over all recurrences, trying to fold loop invariants into them.
869 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
870 // Scan all of the other operands to this add and add them to the vector if
871 // they are loop invariant w.r.t. the recurrence.
872 std::vector<SCEVHandle> LIOps;
873 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
874 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
875 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
876 LIOps.push_back(Ops[i]);
877 Ops.erase(Ops.begin()+i);
878 --i; --e;
879 }
880
881 // If we found some loop invariants, fold them into the recurrence.
882 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +0000883 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +0000884 LIOps.push_back(AddRec->getStart());
885
886 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +0000887 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000888
Dan Gohman246b2562007-10-22 18:31:58 +0000889 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000890 // If all of the other operands were loop invariant, we are done.
891 if (Ops.size() == 1) return NewRec;
892
893 // Otherwise, add the folded AddRec by the non-liv parts.
894 for (unsigned i = 0;; ++i)
895 if (Ops[i] == AddRec) {
896 Ops[i] = NewRec;
897 break;
898 }
Dan Gohman246b2562007-10-22 18:31:58 +0000899 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000900 }
901
902 // Okay, if there weren't any loop invariants to be folded, check to see if
903 // there are multiple AddRec's with the same loop induction variable being
904 // added together. If so, we can fold them.
905 for (unsigned OtherIdx = Idx+1;
906 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
907 if (OtherIdx != Idx) {
908 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
909 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
910 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
911 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
912 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
913 if (i >= NewOps.size()) {
914 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
915 OtherAddRec->op_end());
916 break;
917 }
Dan Gohman246b2562007-10-22 18:31:58 +0000918 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +0000919 }
Dan Gohman246b2562007-10-22 18:31:58 +0000920 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000921
922 if (Ops.size() == 2) return NewAddRec;
923
924 Ops.erase(Ops.begin()+Idx);
925 Ops.erase(Ops.begin()+OtherIdx-1);
926 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +0000927 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000928 }
929 }
930
931 // Otherwise couldn't fold anything into this recurrence. Move onto the
932 // next one.
933 }
934
935 // Okay, it looks like we really DO need an add expr. Check to see if we
936 // already have one, otherwise create a new one.
937 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000938 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
939 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000940 if (Result == 0) Result = new SCEVAddExpr(Ops);
941 return Result;
942}
943
944
Dan Gohman246b2562007-10-22 18:31:58 +0000945SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000946 assert(!Ops.empty() && "Cannot get empty mul!");
947
948 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000949 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000950
951 // If there are any constants, fold them together.
952 unsigned Idx = 0;
953 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
954
955 // C1*(C2+V) -> C1*C2 + C1*V
956 if (Ops.size() == 2)
957 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
958 if (Add->getNumOperands() == 2 &&
959 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +0000960 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
961 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000962
963
964 ++Idx;
965 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
966 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000967 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
968 RHSC->getValue()->getValue());
969 Ops[0] = getConstant(Fold);
970 Ops.erase(Ops.begin()+1); // Erase the folded element
971 if (Ops.size() == 1) return Ops[0];
972 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000973 }
974
975 // If we are left with a constant one being multiplied, strip it off.
976 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
977 Ops.erase(Ops.begin());
978 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +0000979 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000980 // If we have a multiply of zero, it will always be zero.
981 return Ops[0];
982 }
983 }
984
985 // Skip over the add expression until we get to a multiply.
986 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
987 ++Idx;
988
989 if (Ops.size() == 1)
990 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000991
Chris Lattner53e677a2004-04-02 20:23:17 +0000992 // If there are mul operands inline them all into this expression.
993 if (Idx < Ops.size()) {
994 bool DeletedMul = false;
995 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
996 // If we have an mul, expand the mul operands onto the end of the operands
997 // list.
998 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
999 Ops.erase(Ops.begin()+Idx);
1000 DeletedMul = true;
1001 }
1002
1003 // If we deleted at least one mul, we added operands to the end of the list,
1004 // and they are not necessarily sorted. Recurse to resort and resimplify
1005 // any operands we just aquired.
1006 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001007 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001008 }
1009
1010 // If there are any add recurrences in the operands list, see if any other
1011 // added values are loop invariant. If so, we can fold them into the
1012 // recurrence.
1013 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1014 ++Idx;
1015
1016 // Scan over all recurrences, trying to fold loop invariants into them.
1017 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1018 // Scan all of the other operands to this mul and add them to the vector if
1019 // they are loop invariant w.r.t. the recurrence.
1020 std::vector<SCEVHandle> LIOps;
1021 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1022 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1023 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1024 LIOps.push_back(Ops[i]);
1025 Ops.erase(Ops.begin()+i);
1026 --i; --e;
1027 }
1028
1029 // If we found some loop invariants, fold them into the recurrence.
1030 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001031 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001032 std::vector<SCEVHandle> NewOps;
1033 NewOps.reserve(AddRec->getNumOperands());
1034 if (LIOps.size() == 1) {
1035 SCEV *Scale = LIOps[0];
1036 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001037 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001038 } else {
1039 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1040 std::vector<SCEVHandle> MulOps(LIOps);
1041 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001042 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001043 }
1044 }
1045
Dan Gohman246b2562007-10-22 18:31:58 +00001046 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001047
1048 // If all of the other operands were loop invariant, we are done.
1049 if (Ops.size() == 1) return NewRec;
1050
1051 // Otherwise, multiply the folded AddRec by the non-liv parts.
1052 for (unsigned i = 0;; ++i)
1053 if (Ops[i] == AddRec) {
1054 Ops[i] = NewRec;
1055 break;
1056 }
Dan Gohman246b2562007-10-22 18:31:58 +00001057 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001058 }
1059
1060 // Okay, if there weren't any loop invariants to be folded, check to see if
1061 // there are multiple AddRec's with the same loop induction variable being
1062 // multiplied together. If so, we can fold them.
1063 for (unsigned OtherIdx = Idx+1;
1064 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1065 if (OtherIdx != Idx) {
1066 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1067 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1068 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1069 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman246b2562007-10-22 18:31:58 +00001070 SCEVHandle NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001071 G->getStart());
Dan Gohman246b2562007-10-22 18:31:58 +00001072 SCEVHandle B = F->getStepRecurrence(*this);
1073 SCEVHandle D = G->getStepRecurrence(*this);
1074 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1075 getMulExpr(G, B),
1076 getMulExpr(B, D));
1077 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1078 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001079 if (Ops.size() == 2) return NewAddRec;
1080
1081 Ops.erase(Ops.begin()+Idx);
1082 Ops.erase(Ops.begin()+OtherIdx-1);
1083 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001084 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001085 }
1086 }
1087
1088 // Otherwise couldn't fold anything into this recurrence. Move onto the
1089 // next one.
1090 }
1091
1092 // Okay, it looks like we really DO need an mul expr. Check to see if we
1093 // already have one, otherwise create a new one.
1094 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001095 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1096 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001097 if (Result == 0)
1098 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001099 return Result;
1100}
1101
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001102SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001103 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1104 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky789558d2009-01-13 09:18:58 +00001105 return LHS; // X udiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +00001106
1107 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1108 Constant *LHSCV = LHSC->getValue();
1109 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001110 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001111 }
1112 }
1113
Nick Lewycky789558d2009-01-13 09:18:58 +00001114 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1115
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001116 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1117 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001118 return Result;
1119}
1120
1121
1122/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1123/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001124SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Chris Lattner53e677a2004-04-02 20:23:17 +00001125 const SCEVHandle &Step, const Loop *L) {
1126 std::vector<SCEVHandle> Operands;
1127 Operands.push_back(Start);
1128 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1129 if (StepChrec->getLoop() == L) {
1130 Operands.insert(Operands.end(), StepChrec->op_begin(),
1131 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001132 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001133 }
1134
1135 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001136 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001137}
1138
1139/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1140/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001141SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Chris Lattner53e677a2004-04-02 20:23:17 +00001142 const Loop *L) {
1143 if (Operands.size() == 1) return Operands[0];
1144
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001145 if (Operands.back()->isZero()) {
1146 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001147 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001148 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001149
Dan Gohmand9cc7492008-08-08 18:33:12 +00001150 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1151 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1152 const Loop* NestedLoop = NestedAR->getLoop();
1153 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1154 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1155 NestedAR->op_end());
1156 SCEVHandle NestedARHandle(NestedAR);
1157 Operands[0] = NestedAR->getStart();
1158 NestedOperands[0] = getAddRecExpr(Operands, L);
1159 return getAddRecExpr(NestedOperands, NestedLoop);
1160 }
1161 }
1162
Chris Lattner53e677a2004-04-02 20:23:17 +00001163 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001164 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1165 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001166 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1167 return Result;
1168}
1169
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001170SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1171 const SCEVHandle &RHS) {
1172 std::vector<SCEVHandle> Ops;
1173 Ops.push_back(LHS);
1174 Ops.push_back(RHS);
1175 return getSMaxExpr(Ops);
1176}
1177
1178SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1179 assert(!Ops.empty() && "Cannot get empty smax!");
1180 if (Ops.size() == 1) return Ops[0];
1181
1182 // Sort by complexity, this groups all similar expression types together.
1183 GroupByComplexity(Ops);
1184
1185 // If there are any constants, fold them together.
1186 unsigned Idx = 0;
1187 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1188 ++Idx;
1189 assert(Idx < Ops.size());
1190 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1191 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001192 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001193 APIntOps::smax(LHSC->getValue()->getValue(),
1194 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001195 Ops[0] = getConstant(Fold);
1196 Ops.erase(Ops.begin()+1); // Erase the folded element
1197 if (Ops.size() == 1) return Ops[0];
1198 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001199 }
1200
1201 // If we are left with a constant -inf, strip it off.
1202 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1203 Ops.erase(Ops.begin());
1204 --Idx;
1205 }
1206 }
1207
1208 if (Ops.size() == 1) return Ops[0];
1209
1210 // Find the first SMax
1211 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1212 ++Idx;
1213
1214 // Check to see if one of the operands is an SMax. If so, expand its operands
1215 // onto our operand list, and recurse to simplify.
1216 if (Idx < Ops.size()) {
1217 bool DeletedSMax = false;
1218 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1219 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1220 Ops.erase(Ops.begin()+Idx);
1221 DeletedSMax = true;
1222 }
1223
1224 if (DeletedSMax)
1225 return getSMaxExpr(Ops);
1226 }
1227
1228 // Okay, check to see if the same value occurs in the operand list twice. If
1229 // so, delete one. Since we sorted the list, these values are required to
1230 // be adjacent.
1231 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1232 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1233 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1234 --i; --e;
1235 }
1236
1237 if (Ops.size() == 1) return Ops[0];
1238
1239 assert(!Ops.empty() && "Reduced smax down to nothing!");
1240
Nick Lewycky3e630762008-02-20 06:48:22 +00001241 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001242 // already have one, otherwise create a new one.
1243 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1244 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1245 SCEVOps)];
1246 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1247 return Result;
1248}
1249
Nick Lewycky3e630762008-02-20 06:48:22 +00001250SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1251 const SCEVHandle &RHS) {
1252 std::vector<SCEVHandle> Ops;
1253 Ops.push_back(LHS);
1254 Ops.push_back(RHS);
1255 return getUMaxExpr(Ops);
1256}
1257
1258SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1259 assert(!Ops.empty() && "Cannot get empty umax!");
1260 if (Ops.size() == 1) return Ops[0];
1261
1262 // Sort by complexity, this groups all similar expression types together.
1263 GroupByComplexity(Ops);
1264
1265 // If there are any constants, fold them together.
1266 unsigned Idx = 0;
1267 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1268 ++Idx;
1269 assert(Idx < Ops.size());
1270 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1271 // We found two constants, fold them together!
1272 ConstantInt *Fold = ConstantInt::get(
1273 APIntOps::umax(LHSC->getValue()->getValue(),
1274 RHSC->getValue()->getValue()));
1275 Ops[0] = getConstant(Fold);
1276 Ops.erase(Ops.begin()+1); // Erase the folded element
1277 if (Ops.size() == 1) return Ops[0];
1278 LHSC = cast<SCEVConstant>(Ops[0]);
1279 }
1280
1281 // If we are left with a constant zero, strip it off.
1282 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1283 Ops.erase(Ops.begin());
1284 --Idx;
1285 }
1286 }
1287
1288 if (Ops.size() == 1) return Ops[0];
1289
1290 // Find the first UMax
1291 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1292 ++Idx;
1293
1294 // Check to see if one of the operands is a UMax. If so, expand its operands
1295 // onto our operand list, and recurse to simplify.
1296 if (Idx < Ops.size()) {
1297 bool DeletedUMax = false;
1298 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1299 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1300 Ops.erase(Ops.begin()+Idx);
1301 DeletedUMax = true;
1302 }
1303
1304 if (DeletedUMax)
1305 return getUMaxExpr(Ops);
1306 }
1307
1308 // Okay, check to see if the same value occurs in the operand list twice. If
1309 // so, delete one. Since we sorted the list, these values are required to
1310 // be adjacent.
1311 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1312 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1313 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1314 --i; --e;
1315 }
1316
1317 if (Ops.size() == 1) return Ops[0];
1318
1319 assert(!Ops.empty() && "Reduced umax down to nothing!");
1320
1321 // Okay, it looks like we really DO need a umax expr. Check to see if we
1322 // already have one, otherwise create a new one.
1323 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1324 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1325 SCEVOps)];
1326 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1327 return Result;
1328}
1329
Dan Gohman246b2562007-10-22 18:31:58 +00001330SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001331 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001332 return getConstant(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001333 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001334 if (Result == 0) Result = new SCEVUnknown(V);
1335 return Result;
1336}
1337
Chris Lattner53e677a2004-04-02 20:23:17 +00001338
1339//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001340// ScalarEvolutionsImpl Definition and Implementation
1341//===----------------------------------------------------------------------===//
1342//
1343/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1344/// evolution code.
1345///
1346namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001347 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohman246b2562007-10-22 18:31:58 +00001348 /// SE - A reference to the public ScalarEvolution object.
1349 ScalarEvolution &SE;
1350
Chris Lattner53e677a2004-04-02 20:23:17 +00001351 /// F - The function we are analyzing.
1352 ///
1353 Function &F;
1354
1355 /// LI - The loop information for the function we are currently analyzing.
1356 ///
1357 LoopInfo &LI;
1358
1359 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1360 /// things.
1361 SCEVHandle UnknownValue;
1362
1363 /// Scalars - This is a cache of the scalars we have analyzed so far.
1364 ///
1365 std::map<Value*, SCEVHandle> Scalars;
1366
1367 /// IterationCounts - Cache the iteration count of the loops for this
1368 /// function as they are computed.
1369 std::map<const Loop*, SCEVHandle> IterationCounts;
1370
Chris Lattner3221ad02004-04-17 22:58:41 +00001371 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1372 /// the PHI instructions that we attempt to compute constant evolutions for.
1373 /// This allows us to avoid potentially expensive recomputation of these
1374 /// properties. An instruction maps to null if we are unable to compute its
1375 /// exit value.
1376 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001377
Chris Lattner53e677a2004-04-02 20:23:17 +00001378 public:
Dan Gohman246b2562007-10-22 18:31:58 +00001379 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1380 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
Chris Lattner53e677a2004-04-02 20:23:17 +00001381
1382 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1383 /// expression and create a new one.
1384 SCEVHandle getSCEV(Value *V);
1385
Chris Lattnera0740fb2005-08-09 23:36:33 +00001386 /// hasSCEV - Return true if the SCEV for this value has already been
1387 /// computed.
1388 bool hasSCEV(Value *V) const {
1389 return Scalars.count(V);
1390 }
1391
1392 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1393 /// the specified value.
1394 void setSCEV(Value *V, const SCEVHandle &H) {
1395 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1396 assert(isNew && "This entry already existed!");
Devang Patel89d0a4d2008-11-11 19:17:41 +00001397 isNew = false;
Chris Lattnera0740fb2005-08-09 23:36:33 +00001398 }
1399
1400
Chris Lattner53e677a2004-04-02 20:23:17 +00001401 /// getSCEVAtScope - Compute the value of the specified expression within
1402 /// the indicated loop (which may be null to indicate in no loop). If the
1403 /// expression cannot be evaluated, return UnknownValue itself.
1404 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1405
1406
1407 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1408 /// an analyzable loop-invariant iteration count.
1409 bool hasLoopInvariantIterationCount(const Loop *L);
1410
1411 /// getIterationCount - If the specified loop has a predictable iteration
1412 /// count, return it. Note that it is not valid to call this method on a
1413 /// loop without a loop-invariant iteration count.
1414 SCEVHandle getIterationCount(const Loop *L);
1415
Dan Gohman5cec4db2007-06-19 14:28:31 +00001416 /// deleteValueFromRecords - This method should be called by the
1417 /// client before it removes a value from the program, to make sure
Chris Lattner53e677a2004-04-02 20:23:17 +00001418 /// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001419 void deleteValueFromRecords(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001420
1421 private:
1422 /// createSCEV - We know that there is no SCEV for the specified value.
1423 /// Analyze the expression.
1424 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001425
1426 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1427 /// SCEVs.
1428 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001429
1430 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1431 /// for the specified instruction and replaces any references to the
1432 /// symbolic value SymName with the specified value. This is used during
1433 /// PHI resolution.
1434 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1435 const SCEVHandle &SymName,
1436 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001437
1438 /// ComputeIterationCount - Compute the number of times the specified loop
1439 /// will iterate.
1440 SCEVHandle ComputeIterationCount(const Loop *L);
1441
Chris Lattner673e02b2004-10-12 01:49:27 +00001442 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001443 /// 'icmp op load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00001444 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1445 Constant *RHS,
1446 const Loop *L,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001447 ICmpInst::Predicate p);
Chris Lattner673e02b2004-10-12 01:49:27 +00001448
Chris Lattner7980fb92004-04-17 18:36:24 +00001449 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1450 /// constant number of times (the condition evolves only from constants),
1451 /// try to evaluate a few iterations of the loop until we get the exit
1452 /// condition gets a value of ExitWhen (true or false). If we cannot
1453 /// evaluate the trip count of the loop, return UnknownValue.
1454 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1455 bool ExitWhen);
1456
Chris Lattner53e677a2004-04-02 20:23:17 +00001457 /// HowFarToZero - Return the number of times a backedge comparing the
1458 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001459 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001460 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1461
1462 /// HowFarToNonZero - Return the number of times a backedge checking the
1463 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001464 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001465 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001466
Chris Lattnerdb25de42005-08-15 23:33:51 +00001467 /// HowManyLessThans - Return the number of times a backedge containing the
1468 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001469 /// UnknownValue. isSigned specifies whether the less-than is signed.
1470 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
Nick Lewycky789558d2009-01-13 09:18:58 +00001471 bool isSigned);
Chris Lattnerdb25de42005-08-15 23:33:51 +00001472
Dan Gohmanfd6edef2008-09-15 22:18:04 +00001473 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
1474 /// (which may not be an immediate predecessor) which has exactly one
1475 /// successor from which BB is reachable, or null if no such block is
1476 /// found.
1477 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1478
Nick Lewycky59cff122008-07-12 07:41:32 +00001479 /// executesAtLeastOnce - Test whether entry to the loop is protected by
1480 /// a conditional between LHS and RHS.
Nick Lewycky789558d2009-01-13 09:18:58 +00001481 bool executesAtLeastOnce(const Loop *L, bool isSigned, SCEV *LHS, SCEV *RHS);
Nick Lewycky59cff122008-07-12 07:41:32 +00001482
Chris Lattner3221ad02004-04-17 22:58:41 +00001483 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1484 /// in the header of its containing loop, we know the loop executes a
1485 /// constant number of times, and the PHI node is just a recurrence
1486 /// involving constants, fold it.
Reid Spencere8019bb2007-03-01 07:25:48 +00001487 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
Chris Lattner3221ad02004-04-17 22:58:41 +00001488 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001489 };
1490}
1491
1492//===----------------------------------------------------------------------===//
1493// Basic SCEV Analysis and PHI Idiom Recognition Code
1494//
1495
Dan Gohman5cec4db2007-06-19 14:28:31 +00001496/// deleteValueFromRecords - This method should be called by the
Chris Lattner53e677a2004-04-02 20:23:17 +00001497/// client before it removes an instruction from the program, to make sure
1498/// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001499void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1500 SmallVector<Value *, 16> Worklist;
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001501
Dan Gohman5cec4db2007-06-19 14:28:31 +00001502 if (Scalars.erase(V)) {
1503 if (PHINode *PN = dyn_cast<PHINode>(V))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001504 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman5cec4db2007-06-19 14:28:31 +00001505 Worklist.push_back(V);
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001506 }
1507
1508 while (!Worklist.empty()) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001509 Value *VV = Worklist.back();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001510 Worklist.pop_back();
1511
Dan Gohman5cec4db2007-06-19 14:28:31 +00001512 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001513 UI != UE; ++UI) {
Nick Lewycky51e844b2007-06-06 11:26:20 +00001514 Instruction *Inst = cast<Instruction>(*UI);
1515 if (Scalars.erase(Inst)) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001516 if (PHINode *PN = dyn_cast<PHINode>(VV))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001517 ConstantEvolutionLoopExitValue.erase(PN);
1518 Worklist.push_back(Inst);
1519 }
1520 }
1521 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001522}
1523
1524
1525/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1526/// expression and create a new one.
1527SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1528 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1529
1530 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1531 if (I != Scalars.end()) return I->second;
1532 SCEVHandle S = createSCEV(V);
1533 Scalars.insert(std::make_pair(V, S));
1534 return S;
1535}
1536
Chris Lattner4dc534c2005-02-13 04:37:18 +00001537/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1538/// the specified instruction and replaces any references to the symbolic value
1539/// SymName with the specified value. This is used during PHI resolution.
1540void ScalarEvolutionsImpl::
1541ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1542 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001543 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001544 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001545
Chris Lattner4dc534c2005-02-13 04:37:18 +00001546 SCEVHandle NV =
Dan Gohman246b2562007-10-22 18:31:58 +00001547 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001548 if (NV == SI->second) return; // No change.
1549
1550 SI->second = NV; // Update the scalars map!
1551
1552 // Any instruction values that use this instruction might also need to be
1553 // updated!
1554 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1555 UI != E; ++UI)
1556 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1557}
Chris Lattner53e677a2004-04-02 20:23:17 +00001558
1559/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1560/// a loop header, making it a potential recurrence, or it doesn't.
1561///
1562SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1563 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1564 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1565 if (L->getHeader() == PN->getParent()) {
1566 // If it lives in the loop header, it has two incoming values, one
1567 // from outside the loop, and one from inside.
1568 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1569 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001570
Chris Lattner53e677a2004-04-02 20:23:17 +00001571 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman246b2562007-10-22 18:31:58 +00001572 SCEVHandle SymbolicName = SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001573 assert(Scalars.find(PN) == Scalars.end() &&
1574 "PHI node already processed?");
1575 Scalars.insert(std::make_pair(PN, SymbolicName));
1576
1577 // Using this symbolic name for the PHI, analyze the value coming around
1578 // the back-edge.
1579 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1580
1581 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1582 // has a special value for the first iteration of the loop.
1583
1584 // If the value coming around the backedge is an add with the symbolic
1585 // value we just inserted, then we found a simple induction variable!
1586 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1587 // If there is a single occurrence of the symbolic value, replace it
1588 // with a recurrence.
1589 unsigned FoundIndex = Add->getNumOperands();
1590 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1591 if (Add->getOperand(i) == SymbolicName)
1592 if (FoundIndex == e) {
1593 FoundIndex = i;
1594 break;
1595 }
1596
1597 if (FoundIndex != Add->getNumOperands()) {
1598 // Create an add with everything but the specified operand.
1599 std::vector<SCEVHandle> Ops;
1600 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1601 if (i != FoundIndex)
1602 Ops.push_back(Add->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001603 SCEVHandle Accum = SE.getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001604
1605 // This is not a valid addrec if the step amount is varying each
1606 // loop iteration, but is not itself an addrec in this loop.
1607 if (Accum->isLoopInvariant(L) ||
1608 (isa<SCEVAddRecExpr>(Accum) &&
1609 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1610 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman246b2562007-10-22 18:31:58 +00001611 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001612
1613 // Okay, for the entire analysis of this edge we assumed the PHI
1614 // to be symbolic. We now need to go back and update all of the
1615 // entries for the scalars that use the PHI (except for the PHI
1616 // itself) to use the new analyzed value instead of the "symbolic"
1617 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001618 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001619 return PHISCEV;
1620 }
1621 }
Chris Lattner97156e72006-04-26 18:34:07 +00001622 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1623 // Otherwise, this could be a loop like this:
1624 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1625 // In this case, j = {1,+,1} and BEValue is j.
1626 // Because the other in-value of i (0) fits the evolution of BEValue
1627 // i really is an addrec evolution.
1628 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1629 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1630
1631 // If StartVal = j.start - j.stride, we can use StartVal as the
1632 // initial step of the addrec evolution.
Dan Gohman246b2562007-10-22 18:31:58 +00001633 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1634 AddRec->getOperand(1))) {
Chris Lattner97156e72006-04-26 18:34:07 +00001635 SCEVHandle PHISCEV =
Dan Gohman246b2562007-10-22 18:31:58 +00001636 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00001637
1638 // Okay, for the entire analysis of this edge we assumed the PHI
1639 // to be symbolic. We now need to go back and update all of the
1640 // entries for the scalars that use the PHI (except for the PHI
1641 // itself) to use the new analyzed value instead of the "symbolic"
1642 // value.
1643 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1644 return PHISCEV;
1645 }
1646 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001647 }
1648
1649 return SymbolicName;
1650 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001651
Chris Lattner53e677a2004-04-02 20:23:17 +00001652 // If it's not a loop phi, we can't handle it yet.
Dan Gohman246b2562007-10-22 18:31:58 +00001653 return SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001654}
1655
Nick Lewycky83bb0052007-11-22 07:59:40 +00001656/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1657/// guaranteed to end in (at every loop iteration). It is, at the same time,
1658/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1659/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1660static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1661 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00001662 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00001663
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001664 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Nick Lewycky83bb0052007-11-22 07:59:40 +00001665 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1666
1667 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1668 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1669 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1670 }
1671
1672 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1673 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1674 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1675 }
1676
Chris Lattnera17f0392006-12-12 02:26:09 +00001677 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001678 // The result is the min of all operands results.
1679 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1680 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1681 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1682 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001683 }
1684
1685 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001686 // The result is the sum of all operands results.
1687 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1688 uint32_t BitWidth = M->getBitWidth();
1689 for (unsigned i = 1, e = M->getNumOperands();
1690 SumOpRes != BitWidth && i != e; ++i)
1691 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1692 BitWidth);
1693 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001694 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001695
Chris Lattnera17f0392006-12-12 02:26:09 +00001696 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001697 // The result is the min of all operands results.
1698 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1699 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1700 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1701 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001702 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001703
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001704 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1705 // The result is the min of all operands results.
1706 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1707 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1708 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1709 return MinOpRes;
1710 }
1711
Nick Lewycky3e630762008-02-20 06:48:22 +00001712 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1713 // The result is the min of all operands results.
1714 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1715 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1716 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1717 return MinOpRes;
1718 }
1719
Nick Lewycky789558d2009-01-13 09:18:58 +00001720 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky83bb0052007-11-22 07:59:40 +00001721 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00001722}
Chris Lattner53e677a2004-04-02 20:23:17 +00001723
1724/// createSCEV - We know that there is no SCEV for the specified value.
1725/// Analyze the expression.
1726///
1727SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
Chris Lattner42b5e082007-11-23 08:46:22 +00001728 if (!isa<IntegerType>(V->getType()))
1729 return SE.getUnknown(V);
1730
Dan Gohman6c459a22008-06-22 19:56:46 +00001731 unsigned Opcode = Instruction::UserOp1;
1732 if (Instruction *I = dyn_cast<Instruction>(V))
1733 Opcode = I->getOpcode();
1734 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1735 Opcode = CE->getOpcode();
1736 else
1737 return SE.getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00001738
Dan Gohman6c459a22008-06-22 19:56:46 +00001739 User *U = cast<User>(V);
1740 switch (Opcode) {
1741 case Instruction::Add:
1742 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1743 getSCEV(U->getOperand(1)));
1744 case Instruction::Mul:
1745 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1746 getSCEV(U->getOperand(1)));
1747 case Instruction::UDiv:
1748 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1749 getSCEV(U->getOperand(1)));
1750 case Instruction::Sub:
1751 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1752 getSCEV(U->getOperand(1)));
1753 case Instruction::Or:
1754 // If the RHS of the Or is a constant, we may have something like:
1755 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1756 // optimizations will transparently handle this case.
1757 //
1758 // In order for this transformation to be safe, the LHS must be of the
1759 // form X*(2^n) and the Or constant must be less than 2^n.
1760 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1761 SCEVHandle LHS = getSCEV(U->getOperand(0));
1762 const APInt &CIVal = CI->getValue();
1763 if (GetMinTrailingZeros(LHS) >=
1764 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1765 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001766 }
Dan Gohman6c459a22008-06-22 19:56:46 +00001767 break;
1768 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00001769 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00001770 // If the RHS of the xor is a signbit, then this is just an add.
1771 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00001772 if (CI->getValue().isSignBit())
1773 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1774 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00001775
1776 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman6c459a22008-06-22 19:56:46 +00001777 else if (CI->isAllOnesValue())
1778 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1779 }
1780 break;
1781
1782 case Instruction::Shl:
1783 // Turn shift left of a constant amount into a multiply.
1784 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1785 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1786 Constant *X = ConstantInt::get(
1787 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1788 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1789 }
1790 break;
1791
Nick Lewycky01eaf802008-07-07 06:15:49 +00001792 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00001793 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00001794 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1795 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1796 Constant *X = ConstantInt::get(
1797 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1798 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1799 }
1800 break;
1801
Dan Gohman6c459a22008-06-22 19:56:46 +00001802 case Instruction::Trunc:
1803 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1804
1805 case Instruction::ZExt:
1806 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1807
1808 case Instruction::SExt:
1809 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1810
1811 case Instruction::BitCast:
1812 // BitCasts are no-op casts so we just eliminate the cast.
1813 if (U->getType()->isInteger() &&
1814 U->getOperand(0)->getType()->isInteger())
1815 return getSCEV(U->getOperand(0));
1816 break;
1817
1818 case Instruction::PHI:
1819 return createNodeForPHI(cast<PHINode>(U));
1820
1821 case Instruction::Select:
1822 // This could be a smax or umax that was lowered earlier.
1823 // Try to recover it.
1824 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1825 Value *LHS = ICI->getOperand(0);
1826 Value *RHS = ICI->getOperand(1);
1827 switch (ICI->getPredicate()) {
1828 case ICmpInst::ICMP_SLT:
1829 case ICmpInst::ICMP_SLE:
1830 std::swap(LHS, RHS);
1831 // fall through
1832 case ICmpInst::ICMP_SGT:
1833 case ICmpInst::ICMP_SGE:
1834 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1835 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1836 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman1fbffe02008-07-30 04:36:32 +00001837 // ~smax(~x, ~y) == smin(x, y).
1838 return SE.getNotSCEV(SE.getSMaxExpr(
1839 SE.getNotSCEV(getSCEV(LHS)),
1840 SE.getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00001841 break;
1842 case ICmpInst::ICMP_ULT:
1843 case ICmpInst::ICMP_ULE:
1844 std::swap(LHS, RHS);
1845 // fall through
1846 case ICmpInst::ICMP_UGT:
1847 case ICmpInst::ICMP_UGE:
1848 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1849 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1850 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1851 // ~umax(~x, ~y) == umin(x, y)
1852 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
1853 SE.getNotSCEV(getSCEV(RHS))));
1854 break;
1855 default:
1856 break;
1857 }
1858 }
1859
1860 default: // We cannot analyze this expression.
1861 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001862 }
1863
Dan Gohman246b2562007-10-22 18:31:58 +00001864 return SE.getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001865}
1866
1867
1868
1869//===----------------------------------------------------------------------===//
1870// Iteration Count Computation Code
1871//
1872
1873/// getIterationCount - If the specified loop has a predictable iteration
1874/// count, return it. Note that it is not valid to call this method on a
1875/// loop without a loop-invariant iteration count.
1876SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1877 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1878 if (I == IterationCounts.end()) {
1879 SCEVHandle ItCount = ComputeIterationCount(L);
1880 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1881 if (ItCount != UnknownValue) {
1882 assert(ItCount->isLoopInvariant(L) &&
1883 "Computed trip count isn't loop invariant for loop!");
1884 ++NumTripCountsComputed;
1885 } else if (isa<PHINode>(L->getHeader()->begin())) {
1886 // Only count loops that have phi nodes as not being computable.
1887 ++NumTripCountsNotComputed;
1888 }
1889 }
1890 return I->second;
1891}
1892
1893/// ComputeIterationCount - Compute the number of times the specified loop
1894/// will iterate.
1895SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1896 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patelb7211a22007-08-21 00:31:24 +00001897 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001898 L->getExitBlocks(ExitBlocks);
1899 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001900
1901 // Okay, there is one exit block. Try to find the condition that causes the
1902 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001903 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001904
1905 BasicBlock *ExitingBlock = 0;
1906 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1907 PI != E; ++PI)
1908 if (L->contains(*PI)) {
1909 if (ExitingBlock == 0)
1910 ExitingBlock = *PI;
1911 else
1912 return UnknownValue; // More than one block exiting!
1913 }
1914 assert(ExitingBlock && "No exits from loop, something is broken!");
1915
1916 // Okay, we've computed the exiting block. See what condition causes us to
1917 // exit.
1918 //
1919 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00001920 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1921 if (ExitBr == 0) return UnknownValue;
1922 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00001923
1924 // At this point, we know we have a conditional branch that determines whether
1925 // the loop is exited. However, we don't know if the branch is executed each
1926 // time through the loop. If not, then the execution count of the branch will
1927 // not be equal to the trip count of the loop.
1928 //
1929 // Currently we check for this by checking to see if the Exit branch goes to
1930 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00001931 // times as the loop. We also handle the case where the exit block *is* the
1932 // loop header. This is common for un-rotated loops. More extensive analysis
1933 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001934 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00001935 ExitBr->getSuccessor(1) != L->getHeader() &&
1936 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00001937 return UnknownValue;
1938
Reid Spencere4d87aa2006-12-23 06:05:41 +00001939 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1940
Nick Lewycky3b711652008-02-21 08:34:02 +00001941 // If it's not an integer comparison then compute it the hard way.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001942 // Note that ICmpInst deals with pointer comparisons too so we must check
1943 // the type of the operand.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001944 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Chris Lattner7980fb92004-04-17 18:36:24 +00001945 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1946 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001947
Reid Spencere4d87aa2006-12-23 06:05:41 +00001948 // If the condition was exit on true, convert the condition to exit on false
1949 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00001950 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001951 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001952 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00001953 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001954
1955 // Handle common loops like: for (X = "string"; *X; ++X)
1956 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1957 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1958 SCEVHandle ItCnt =
1959 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1960 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1961 }
1962
Chris Lattner53e677a2004-04-02 20:23:17 +00001963 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1964 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1965
1966 // Try to evaluate any dependencies out of the loop.
1967 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1968 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1969 Tmp = getSCEVAtScope(RHS, L);
1970 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1971
Reid Spencere4d87aa2006-12-23 06:05:41 +00001972 // At this point, we would like to compute how many iterations of the
1973 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00001974 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
1975 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00001976 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001977 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00001978 }
1979
1980 // FIXME: think about handling pointer comparisons! i.e.:
1981 // while (P != P+100) ++P;
1982
1983 // If we have a comparison of a chrec against a constant, try to use value
1984 // ranges to answer this query.
1985 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1986 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1987 if (AddRec->getLoop() == L) {
1988 // Form the comparison range using the constant of the correct type so
1989 // that the ConstantRange class knows to do a signed or unsigned
1990 // comparison.
1991 ConstantInt *CompVal = RHSC->getValue();
1992 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00001993 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00001994 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00001995 if (CompVal) {
1996 // Form the constant range.
Reid Spencerc6aedf72007-02-28 22:03:51 +00001997 ConstantRange CompRange(
1998 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001999
Dan Gohman246b2562007-10-22 18:31:58 +00002000 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002001 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2002 }
2003 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002004
Chris Lattner53e677a2004-04-02 20:23:17 +00002005 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002006 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00002007 // Convert to: while (X-Y != 0)
Dan Gohman246b2562007-10-22 18:31:58 +00002008 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002009 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002010 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002011 }
2012 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00002013 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman246b2562007-10-22 18:31:58 +00002014 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002015 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002016 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002017 }
2018 case ICmpInst::ICMP_SLT: {
Nick Lewycky789558d2009-01-13 09:18:58 +00002019 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002020 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002021 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002022 }
2023 case ICmpInst::ICMP_SGT: {
Eli Friedman068acc32008-07-30 00:04:08 +00002024 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky789558d2009-01-13 09:18:58 +00002025 SE.getNotSCEV(RHS), L, true);
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002026 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2027 break;
2028 }
2029 case ICmpInst::ICMP_ULT: {
Nick Lewycky789558d2009-01-13 09:18:58 +00002030 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002031 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2032 break;
2033 }
2034 case ICmpInst::ICMP_UGT: {
Dale Johannesena0c8fc62008-04-20 16:58:57 +00002035 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky789558d2009-01-13 09:18:58 +00002036 SE.getNotSCEV(RHS), L, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002037 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002038 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002039 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002040 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002041#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002042 cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002043 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendlinge8156192006-12-07 01:30:32 +00002044 cerr << "[unsigned] ";
2045 cerr << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00002046 << Instruction::getOpcodeName(Instruction::ICmp)
2047 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002048#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00002049 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002050 }
Chris Lattner7980fb92004-04-17 18:36:24 +00002051 return ComputeIterationCountExhaustively(L, ExitCond,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002052 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00002053}
2054
Chris Lattner673e02b2004-10-12 01:49:27 +00002055static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00002056EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2057 ScalarEvolution &SE) {
2058 SCEVHandle InVal = SE.getConstant(C);
2059 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002060 assert(isa<SCEVConstant>(Val) &&
2061 "Evaluation of SCEV at constant didn't fold correctly?");
2062 return cast<SCEVConstant>(Val)->getValue();
2063}
2064
2065/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2066/// and a GEP expression (missing the pointer index) indexing into it, return
2067/// the addressed element of the initializer or null if the index expression is
2068/// invalid.
2069static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002070GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00002071 const std::vector<ConstantInt*> &Indices) {
2072 Constant *Init = GV->getInitializer();
2073 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002074 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00002075 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2076 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2077 Init = cast<Constant>(CS->getOperand(Idx));
2078 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2079 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2080 Init = cast<Constant>(CA->getOperand(Idx));
2081 } else if (isa<ConstantAggregateZero>(Init)) {
2082 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2083 assert(Idx < STy->getNumElements() && "Bad struct index!");
2084 Init = Constant::getNullValue(STy->getElementType(Idx));
2085 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2086 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2087 Init = Constant::getNullValue(ATy->getElementType());
2088 } else {
2089 assert(0 && "Unknown constant aggregate type!");
2090 }
2091 return 0;
2092 } else {
2093 return 0; // Unknown initializer type
2094 }
2095 }
2096 return Init;
2097}
2098
2099/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky08de6132008-05-06 04:03:18 +00002100/// 'icmp op load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00002101SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002102ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002103 const Loop *L,
2104 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002105 if (LI->isVolatile()) return UnknownValue;
2106
2107 // Check to see if the loaded pointer is a getelementptr of a global.
2108 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2109 if (!GEP) return UnknownValue;
2110
2111 // Make sure that it is really a constant global we are gepping, with an
2112 // initializer, and make sure the first IDX is really 0.
2113 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2114 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2115 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2116 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2117 return UnknownValue;
2118
2119 // Okay, we allow one non-constant index into the GEP instruction.
2120 Value *VarIdx = 0;
2121 std::vector<ConstantInt*> Indexes;
2122 unsigned VarIdxNum = 0;
2123 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2124 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2125 Indexes.push_back(CI);
2126 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2127 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2128 VarIdx = GEP->getOperand(i);
2129 VarIdxNum = i-2;
2130 Indexes.push_back(0);
2131 }
2132
2133 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2134 // Check to see if X is a loop variant variable value now.
2135 SCEVHandle Idx = getSCEV(VarIdx);
2136 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2137 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2138
2139 // We can only recognize very limited forms of loop index expressions, in
2140 // particular, only affine AddRec's like {C1,+,C2}.
2141 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2142 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2143 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2144 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2145 return UnknownValue;
2146
2147 unsigned MaxSteps = MaxBruteForceIterations;
2148 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002149 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00002150 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohman246b2562007-10-22 18:31:58 +00002151 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002152
2153 // Form the GEP offset.
2154 Indexes[VarIdxNum] = Val;
2155
2156 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2157 if (Result == 0) break; // Cannot compute!
2158
2159 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002160 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002161 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00002162 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002163#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002164 cerr << "\n***\n*** Computed loop count " << *ItCst
2165 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2166 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00002167#endif
2168 ++NumArrayLenItCounts;
Dan Gohman246b2562007-10-22 18:31:58 +00002169 return SE.getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00002170 }
2171 }
2172 return UnknownValue;
2173}
2174
2175
Chris Lattner3221ad02004-04-17 22:58:41 +00002176/// CanConstantFold - Return true if we can constant fold an instruction of the
2177/// specified type, assuming that all operands were constants.
2178static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00002179 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00002180 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2181 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002182
Chris Lattner3221ad02004-04-17 22:58:41 +00002183 if (const CallInst *CI = dyn_cast<CallInst>(I))
2184 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00002185 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00002186 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00002187}
2188
Chris Lattner3221ad02004-04-17 22:58:41 +00002189/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2190/// in the loop that V is derived from. We allow arbitrary operations along the
2191/// way, but the operands of an operation must either be constants or a value
2192/// derived from a constant PHI. If this expression does not fit with these
2193/// constraints, return null.
2194static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2195 // If this is not an instruction, or if this is an instruction outside of the
2196 // loop, it can't be derived from a loop PHI.
2197 Instruction *I = dyn_cast<Instruction>(V);
2198 if (I == 0 || !L->contains(I->getParent())) return 0;
2199
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002200 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002201 if (L->getHeader() == I->getParent())
2202 return PN;
2203 else
2204 // We don't currently keep track of the control flow needed to evaluate
2205 // PHIs, so we cannot handle PHIs inside of loops.
2206 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002207 }
Chris Lattner3221ad02004-04-17 22:58:41 +00002208
2209 // If we won't be able to constant fold this expression even if the operands
2210 // are constants, return early.
2211 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002212
Chris Lattner3221ad02004-04-17 22:58:41 +00002213 // Otherwise, we can evaluate this instruction if all of its operands are
2214 // constant or derived from a PHI node themselves.
2215 PHINode *PHI = 0;
2216 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2217 if (!(isa<Constant>(I->getOperand(Op)) ||
2218 isa<GlobalValue>(I->getOperand(Op)))) {
2219 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2220 if (P == 0) return 0; // Not evolving from PHI
2221 if (PHI == 0)
2222 PHI = P;
2223 else if (PHI != P)
2224 return 0; // Evolving from multiple different PHIs.
2225 }
2226
2227 // This is a expression evolving from a constant PHI!
2228 return PHI;
2229}
2230
2231/// EvaluateExpression - Given an expression that passes the
2232/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2233/// in the loop has the value PHIVal. If we can't fold this expression for some
2234/// reason, return null.
2235static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2236 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00002237 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00002238 Instruction *I = cast<Instruction>(V);
2239
2240 std::vector<Constant*> Operands;
2241 Operands.resize(I->getNumOperands());
2242
2243 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2244 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2245 if (Operands[i] == 0) return 0;
2246 }
2247
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002248 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2249 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2250 &Operands[0], Operands.size());
2251 else
2252 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2253 &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00002254}
2255
2256/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2257/// in the header of its containing loop, we know the loop executes a
2258/// constant number of times, and the PHI node is just a recurrence
2259/// involving constants, fold it.
2260Constant *ScalarEvolutionsImpl::
Reid Spencere8019bb2007-03-01 07:25:48 +00002261getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00002262 std::map<PHINode*, Constant*>::iterator I =
2263 ConstantEvolutionLoopExitValue.find(PN);
2264 if (I != ConstantEvolutionLoopExitValue.end())
2265 return I->second;
2266
Reid Spencere8019bb2007-03-01 07:25:48 +00002267 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00002268 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2269
2270 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2271
2272 // Since the loop is canonicalized, the PHI node must have two entries. One
2273 // entry must be a constant (coming in from outside of the loop), and the
2274 // second must be derived from the same PHI.
2275 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2276 Constant *StartCST =
2277 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2278 if (StartCST == 0)
2279 return RetVal = 0; // Must be a constant.
2280
2281 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2282 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2283 if (PN2 != PN)
2284 return RetVal = 0; // Not derived from same PHI.
2285
2286 // Execute the loop symbolically to determine the exit value.
Reid Spencere8019bb2007-03-01 07:25:48 +00002287 if (Its.getActiveBits() >= 32)
2288 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00002289
Reid Spencere8019bb2007-03-01 07:25:48 +00002290 unsigned NumIterations = Its.getZExtValue(); // must be in range
2291 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00002292 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2293 if (IterationNum == NumIterations)
2294 return RetVal = PHIVal; // Got exit value!
2295
2296 // Compute the value of the PHI node for the next iteration.
2297 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2298 if (NextPHI == PHIVal)
2299 return RetVal = NextPHI; // Stopped evolving!
2300 if (NextPHI == 0)
2301 return 0; // Couldn't evaluate!
2302 PHIVal = NextPHI;
2303 }
2304}
2305
Chris Lattner7980fb92004-04-17 18:36:24 +00002306/// ComputeIterationCountExhaustively - If the trip is known to execute a
2307/// constant number of times (the condition evolves only from constants),
2308/// try to evaluate a few iterations of the loop until we get the exit
2309/// condition gets a value of ExitWhen (true or false). If we cannot
2310/// evaluate the trip count of the loop, return UnknownValue.
2311SCEVHandle ScalarEvolutionsImpl::
2312ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2313 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2314 if (PN == 0) return UnknownValue;
2315
2316 // Since the loop is canonicalized, the PHI node must have two entries. One
2317 // entry must be a constant (coming in from outside of the loop), and the
2318 // second must be derived from the same PHI.
2319 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2320 Constant *StartCST =
2321 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2322 if (StartCST == 0) return UnknownValue; // Must be a constant.
2323
2324 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2325 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2326 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2327
2328 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2329 // the loop symbolically to determine when the condition gets a value of
2330 // "ExitWhen".
2331 unsigned IterationNum = 0;
2332 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2333 for (Constant *PHIVal = StartCST;
2334 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002335 ConstantInt *CondVal =
2336 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00002337
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002338 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00002339 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002340
Reid Spencere8019bb2007-03-01 07:25:48 +00002341 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002342 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00002343 ++NumBruteForceTripCountsComputed;
Dan Gohman246b2562007-10-22 18:31:58 +00002344 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00002345 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002346
Chris Lattner3221ad02004-04-17 22:58:41 +00002347 // Compute the value of the PHI node for the next iteration.
2348 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2349 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00002350 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00002351 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00002352 }
2353
2354 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00002355 return UnknownValue;
2356}
2357
2358/// getSCEVAtScope - Compute the value of the specified expression within the
2359/// indicated loop (which may be null to indicate in no loop). If the
2360/// expression cannot be evaluated, return UnknownValue.
2361SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2362 // FIXME: this should be turned into a virtual method on SCEV!
2363
Chris Lattner3221ad02004-04-17 22:58:41 +00002364 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002365
Nick Lewycky3e630762008-02-20 06:48:22 +00002366 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00002367 // exit value from the loop without using SCEVs.
2368 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2369 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2370 const Loop *LI = this->LI[I->getParent()];
2371 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2372 if (PHINode *PN = dyn_cast<PHINode>(I))
2373 if (PN->getParent() == LI->getHeader()) {
2374 // Okay, there is no closed form solution for the PHI node. Check
2375 // to see if the loop that contains it has a known iteration count.
2376 // If so, we may be able to force computation of the exit value.
2377 SCEVHandle IterationCount = getIterationCount(LI);
2378 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2379 // Okay, we know how many times the containing loop executes. If
2380 // this is a constant evolving PHI node, get the final value at
2381 // the specified iteration number.
2382 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencere8019bb2007-03-01 07:25:48 +00002383 ICC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00002384 LI);
Dan Gohman246b2562007-10-22 18:31:58 +00002385 if (RV) return SE.getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00002386 }
2387 }
2388
Reid Spencer09906f32006-12-04 21:33:23 +00002389 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00002390 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00002391 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00002392 // result. This is particularly useful for computing loop exit values.
2393 if (CanConstantFold(I)) {
2394 std::vector<Constant*> Operands;
2395 Operands.reserve(I->getNumOperands());
2396 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2397 Value *Op = I->getOperand(i);
2398 if (Constant *C = dyn_cast<Constant>(Op)) {
2399 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002400 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00002401 // If any of the operands is non-constant and if they are
2402 // non-integer, don't even try to analyze them with scev techniques.
2403 if (!isa<IntegerType>(Op->getType()))
2404 return V;
2405
Chris Lattner3221ad02004-04-17 22:58:41 +00002406 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2407 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
Reid Spencerd977d862006-12-12 23:36:14 +00002408 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2409 Op->getType(),
2410 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002411 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2412 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
Reid Spencerd977d862006-12-12 23:36:14 +00002413 Operands.push_back(ConstantExpr::getIntegerCast(C,
2414 Op->getType(),
2415 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002416 else
2417 return V;
2418 } else {
2419 return V;
2420 }
2421 }
2422 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002423
2424 Constant *C;
2425 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2426 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2427 &Operands[0], Operands.size());
2428 else
2429 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2430 &Operands[0], Operands.size());
Dan Gohman246b2562007-10-22 18:31:58 +00002431 return SE.getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002432 }
2433 }
2434
2435 // This is some other type of SCEVUnknown, just return it.
2436 return V;
2437 }
2438
Chris Lattner53e677a2004-04-02 20:23:17 +00002439 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2440 // Avoid performing the look-up in the common case where the specified
2441 // expression has no loop-variant portions.
2442 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2443 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2444 if (OpAtScope != Comm->getOperand(i)) {
2445 if (OpAtScope == UnknownValue) return UnknownValue;
2446 // Okay, at least one of these operands is loop variant but might be
2447 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002448 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002449 NewOps.push_back(OpAtScope);
2450
2451 for (++i; i != e; ++i) {
2452 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2453 if (OpAtScope == UnknownValue) return UnknownValue;
2454 NewOps.push_back(OpAtScope);
2455 }
2456 if (isa<SCEVAddExpr>(Comm))
Dan Gohman246b2562007-10-22 18:31:58 +00002457 return SE.getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002458 if (isa<SCEVMulExpr>(Comm))
2459 return SE.getMulExpr(NewOps);
2460 if (isa<SCEVSMaxExpr>(Comm))
2461 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00002462 if (isa<SCEVUMaxExpr>(Comm))
2463 return SE.getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002464 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002465 }
2466 }
2467 // If we got here, all operands are loop invariant.
2468 return Comm;
2469 }
2470
Nick Lewycky789558d2009-01-13 09:18:58 +00002471 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2472 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002473 if (LHS == UnknownValue) return LHS;
Nick Lewycky789558d2009-01-13 09:18:58 +00002474 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002475 if (RHS == UnknownValue) return RHS;
Nick Lewycky789558d2009-01-13 09:18:58 +00002476 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2477 return Div; // must be loop invariant
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00002478 return SE.getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002479 }
2480
2481 // If this is a loop recurrence for a loop that does not contain L, then we
2482 // are dealing with the final value computed by the loop.
2483 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2484 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2485 // To evaluate this recurrence, we need to know how many times the AddRec
2486 // loop iterates. Compute this now.
2487 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2488 if (IterationCount == UnknownValue) return UnknownValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002489
Eli Friedmanb42a6262008-08-04 23:49:06 +00002490 // Then, evaluate the AddRec.
Dan Gohman246b2562007-10-22 18:31:58 +00002491 return AddRec->evaluateAtIteration(IterationCount, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002492 }
2493 return UnknownValue;
2494 }
2495
2496 //assert(0 && "Unknown SCEV type!");
2497 return UnknownValue;
2498}
2499
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002500/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2501/// following equation:
2502///
2503/// A * X = B (mod N)
2504///
2505/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2506/// A and B isn't important.
2507///
2508/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2509static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2510 ScalarEvolution &SE) {
2511 uint32_t BW = A.getBitWidth();
2512 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2513 assert(A != 0 && "A must be non-zero.");
2514
2515 // 1. D = gcd(A, N)
2516 //
2517 // The gcd of A and N may have only one prime factor: 2. The number of
2518 // trailing zeros in A is its multiplicity
2519 uint32_t Mult2 = A.countTrailingZeros();
2520 // D = 2^Mult2
2521
2522 // 2. Check if B is divisible by D.
2523 //
2524 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2525 // is not less than multiplicity of this prime factor for D.
2526 if (B.countTrailingZeros() < Mult2)
2527 return new SCEVCouldNotCompute();
2528
2529 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2530 // modulo (N / D).
2531 //
2532 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2533 // bit width during computations.
2534 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2535 APInt Mod(BW + 1, 0);
2536 Mod.set(BW - Mult2); // Mod = N / D
2537 APInt I = AD.multiplicativeInverse(Mod);
2538
2539 // 4. Compute the minimum unsigned root of the equation:
2540 // I * (B / D) mod (N / D)
2541 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2542
2543 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2544 // bits.
2545 return SE.getConstant(Result.trunc(BW));
2546}
Chris Lattner53e677a2004-04-02 20:23:17 +00002547
2548/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2549/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2550/// might be the same) or two SCEVCouldNotCompute objects.
2551///
2552static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman246b2562007-10-22 18:31:58 +00002553SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002554 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Reid Spencere8019bb2007-03-01 07:25:48 +00002555 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2556 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2557 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002558
Chris Lattner53e677a2004-04-02 20:23:17 +00002559 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00002560 if (!LC || !MC || !NC) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002561 SCEV *CNC = new SCEVCouldNotCompute();
2562 return std::make_pair(CNC, CNC);
2563 }
2564
Reid Spencere8019bb2007-03-01 07:25:48 +00002565 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00002566 const APInt &L = LC->getValue()->getValue();
2567 const APInt &M = MC->getValue()->getValue();
2568 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00002569 APInt Two(BitWidth, 2);
2570 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002571
Reid Spencere8019bb2007-03-01 07:25:48 +00002572 {
2573 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00002574 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00002575 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2576 // The B coefficient is M-N/2
2577 APInt B(M);
2578 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002579
Reid Spencere8019bb2007-03-01 07:25:48 +00002580 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00002581 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00002582
Reid Spencere8019bb2007-03-01 07:25:48 +00002583 // Compute the B^2-4ac term.
2584 APInt SqrtTerm(B);
2585 SqrtTerm *= B;
2586 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00002587
Reid Spencere8019bb2007-03-01 07:25:48 +00002588 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2589 // integer value or else APInt::sqrt() will assert.
2590 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002591
Reid Spencere8019bb2007-03-01 07:25:48 +00002592 // Compute the two solutions for the quadratic formula.
2593 // The divisions must be performed as signed divisions.
2594 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00002595 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00002596 if (TwoA.isMinValue()) {
2597 SCEV *CNC = new SCEVCouldNotCompute();
2598 return std::make_pair(CNC, CNC);
2599 }
2600
Reid Spencere8019bb2007-03-01 07:25:48 +00002601 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2602 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002603
Dan Gohman246b2562007-10-22 18:31:58 +00002604 return std::make_pair(SE.getConstant(Solution1),
2605 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00002606 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00002607}
2608
2609/// HowFarToZero - Return the number of times a backedge comparing the specified
2610/// value to zero will execute. If not computable, return UnknownValue
2611SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2612 // If the value is a constant
2613 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2614 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00002615 if (C->getValue()->isZero()) return C;
Chris Lattner53e677a2004-04-02 20:23:17 +00002616 return UnknownValue; // Otherwise it will loop infinitely.
2617 }
2618
2619 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2620 if (!AddRec || AddRec->getLoop() != L)
2621 return UnknownValue;
2622
2623 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002624 // If this is an affine expression, the execution count of this branch is
2625 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00002626 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002627 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00002628 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002629 // equivalent to:
2630 //
2631 // Step*N = -Start (mod 2^BW)
2632 //
2633 // where BW is the common bit width of Start and Step.
2634
Chris Lattner53e677a2004-04-02 20:23:17 +00002635 // Get the initial value for the loop.
2636 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002637 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002638
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002639 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002640
Chris Lattner53e677a2004-04-02 20:23:17 +00002641 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002642 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00002643
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002644 // First, handle unitary steps.
2645 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2646 return SE.getNegativeSCEV(Start); // N = -Start (as unsigned)
2647 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2648 return Start; // N = Start (as unsigned)
2649
2650 // Then, try to solve the above equation provided that Start is constant.
2651 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2652 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2653 -StartC->getValue()->getValue(),SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002654 }
Chris Lattner42a75512007-01-15 02:27:26 +00002655 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002656 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2657 // the quadratic equation to solve it.
Dan Gohman246b2562007-10-22 18:31:58 +00002658 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002659 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2660 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2661 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002662#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002663 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2664 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002665#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002666 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002667 if (ConstantInt *CB =
2668 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002669 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002670 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002671 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002672
Chris Lattner53e677a2004-04-02 20:23:17 +00002673 // We can only use this value if the chrec ends up with an exact zero
2674 // value at this index. When solving for "X*X != 5", for example, we
2675 // should not accept a root of 2.
Dan Gohman246b2562007-10-22 18:31:58 +00002676 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002677 if (Val->isZero())
2678 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00002679 }
2680 }
2681 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002682
Chris Lattner53e677a2004-04-02 20:23:17 +00002683 return UnknownValue;
2684}
2685
2686/// HowFarToNonZero - Return the number of times a backedge checking the
2687/// specified value for nonzero will execute. If not computable, return
2688/// UnknownValue
2689SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2690 // Loops that look like: while (X == 0) are very strange indeed. We don't
2691 // handle them yet except for the trivial case. This could be expanded in the
2692 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002693
Chris Lattner53e677a2004-04-02 20:23:17 +00002694 // If the value is a constant, check to see if it is known to be non-zero
2695 // already. If so, the backedge will execute zero times.
2696 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00002697 if (!C->getValue()->isNullValue())
2698 return SE.getIntegerSCEV(0, C->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002699 return UnknownValue; // Otherwise it will loop infinitely.
2700 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002701
Chris Lattner53e677a2004-04-02 20:23:17 +00002702 // We could implement others, but I really doubt anyone writes loops like
2703 // this, and if they did, they would already be constant folded.
2704 return UnknownValue;
2705}
2706
Dan Gohmanfd6edef2008-09-15 22:18:04 +00002707/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2708/// (which may not be an immediate predecessor) which has exactly one
2709/// successor from which BB is reachable, or null if no such block is
2710/// found.
2711///
2712BasicBlock *
2713ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2714 // If the block has a unique predecessor, the predecessor must have
2715 // no other successors from which BB is reachable.
2716 if (BasicBlock *Pred = BB->getSinglePredecessor())
2717 return Pred;
2718
2719 // A loop's header is defined to be a block that dominates the loop.
2720 // If the loop has a preheader, it must be a block that has exactly
2721 // one successor that can reach BB. This is slightly more strict
2722 // than necessary, but works if critical edges are split.
2723 if (Loop *L = LI.getLoopFor(BB))
2724 return L->getLoopPreheader();
2725
2726 return 0;
2727}
2728
Nick Lewycky59cff122008-07-12 07:41:32 +00002729/// executesAtLeastOnce - Test whether entry to the loop is protected by
2730/// a conditional between LHS and RHS.
2731bool ScalarEvolutionsImpl::executesAtLeastOnce(const Loop *L, bool isSigned,
2732 SCEV *LHS, SCEV *RHS) {
2733 BasicBlock *Preheader = L->getLoopPreheader();
2734 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00002735
Dan Gohman38372182008-08-12 20:17:31 +00002736 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohmanfd6edef2008-09-15 22:18:04 +00002737 // there are predecessors that can be found that have unique successors
2738 // leading to the original header.
2739 for (; Preheader;
2740 PreheaderDest = Preheader,
2741 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohman38372182008-08-12 20:17:31 +00002742
2743 BranchInst *LoopEntryPredicate =
Nick Lewycky59cff122008-07-12 07:41:32 +00002744 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00002745 if (!LoopEntryPredicate ||
2746 LoopEntryPredicate->isUnconditional())
2747 continue;
2748
2749 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2750 if (!ICI) continue;
2751
2752 // Now that we found a conditional branch that dominates the loop, check to
2753 // see if it is the comparison we are looking for.
2754 Value *PreCondLHS = ICI->getOperand(0);
2755 Value *PreCondRHS = ICI->getOperand(1);
2756 ICmpInst::Predicate Cond;
2757 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2758 Cond = ICI->getPredicate();
2759 else
2760 Cond = ICI->getInversePredicate();
2761
2762 switch (Cond) {
2763 case ICmpInst::ICMP_UGT:
Nick Lewycky789558d2009-01-13 09:18:58 +00002764 if (isSigned) continue;
Dan Gohman38372182008-08-12 20:17:31 +00002765 std::swap(PreCondLHS, PreCondRHS);
2766 Cond = ICmpInst::ICMP_ULT;
2767 break;
2768 case ICmpInst::ICMP_SGT:
Nick Lewycky789558d2009-01-13 09:18:58 +00002769 if (!isSigned) continue;
Dan Gohman38372182008-08-12 20:17:31 +00002770 std::swap(PreCondLHS, PreCondRHS);
2771 Cond = ICmpInst::ICMP_SLT;
2772 break;
2773 case ICmpInst::ICMP_ULT:
Nick Lewycky789558d2009-01-13 09:18:58 +00002774 if (isSigned) continue;
Dan Gohman38372182008-08-12 20:17:31 +00002775 break;
2776 case ICmpInst::ICMP_SLT:
Nick Lewycky789558d2009-01-13 09:18:58 +00002777 if (!isSigned) continue;
Dan Gohman38372182008-08-12 20:17:31 +00002778 break;
2779 default:
2780 continue;
2781 }
2782
2783 if (!PreCondLHS->getType()->isInteger()) continue;
2784
2785 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
2786 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
2787 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
2788 (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
2789 RHS == SE.getNotSCEV(PreCondLHSSCEV)))
2790 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00002791 }
2792
Dan Gohman38372182008-08-12 20:17:31 +00002793 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00002794}
2795
Chris Lattnerdb25de42005-08-15 23:33:51 +00002796/// HowManyLessThans - Return the number of times a backedge containing the
2797/// specified less-than comparison will execute. If not computable, return
2798/// UnknownValue.
2799SCEVHandle ScalarEvolutionsImpl::
Nick Lewycky789558d2009-01-13 09:18:58 +00002800HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00002801 // Only handle: "ADDREC < LoopInvariant".
2802 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2803
2804 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2805 if (!AddRec || AddRec->getLoop() != L)
2806 return UnknownValue;
2807
2808 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00002809 // FORNOW: We only support unit strides.
2810 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
2811 if (AddRec->getOperand(1) != One)
Chris Lattnerdb25de42005-08-15 23:33:51 +00002812 return UnknownValue;
2813
Nick Lewycky789558d2009-01-13 09:18:58 +00002814 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
2815 // m. So, we count the number of iterations in which {n,+,1} < m is true.
2816 // Note that we cannot simply return max(m-n,0) because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00002817 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00002818
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002819 // First, we get the value of the LHS in the first iteration: n
2820 SCEVHandle Start = AddRec->getOperand(0);
2821
Nick Lewycky789558d2009-01-13 09:18:58 +00002822 if (executesAtLeastOnce(L, isSigned,
2823 SE.getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
2824 // Since we know that the condition is true in order to enter the loop,
2825 // we know that it will run exactly m-n times.
2826 return SE.getMinusSCEV(RHS, Start);
2827 } else {
2828 // Then, we get the value of the LHS in the first iteration in which the
2829 // above condition doesn't hold. This equals to max(m,n).
2830 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
2831 : SE.getUMaxExpr(RHS, Start);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002832
Nick Lewycky789558d2009-01-13 09:18:58 +00002833 // Finally, we subtract these two values to get the number of times the
2834 // backedge is executed: max(m,n)-n.
2835 return SE.getMinusSCEV(End, Start);
Nick Lewycky1447f5c2008-12-16 08:30:01 +00002836 }
Chris Lattnerdb25de42005-08-15 23:33:51 +00002837 }
2838
2839 return UnknownValue;
2840}
2841
Chris Lattner53e677a2004-04-02 20:23:17 +00002842/// getNumIterationsInRange - Return the number of iterations of this loop that
2843/// produce values in the specified constant range. Another way of looking at
2844/// this is that it returns the first iteration number where the value is not in
2845/// the condition, thus computing the exit count. If the iteration count can't
2846/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman246b2562007-10-22 18:31:58 +00002847SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2848 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002849 if (Range.isFullSet()) // Infinite loop.
2850 return new SCEVCouldNotCompute();
2851
2852 // If the start is a non-zero constant, shift the range to simplify things.
2853 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00002854 if (!SC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002855 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00002856 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2857 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002858 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2859 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00002860 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002861 // This is strange and shouldn't happen.
2862 return new SCEVCouldNotCompute();
2863 }
2864
2865 // The only time we can solve this is when we have all constant indices.
2866 // Otherwise, we cannot determine the overflow conditions.
2867 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2868 if (!isa<SCEVConstant>(getOperand(i)))
2869 return new SCEVCouldNotCompute();
2870
2871
2872 // Okay at this point we know that all elements of the chrec are constants and
2873 // that the start element is zero.
2874
2875 // First check to see if the range contains zero. If not, the first
2876 // iteration exits.
Reid Spencera6e8a952007-03-01 07:54:15 +00002877 if (!Range.contains(APInt(getBitWidth(),0)))
Dan Gohman246b2562007-10-22 18:31:58 +00002878 return SE.getConstant(ConstantInt::get(getType(),0));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002879
Chris Lattner53e677a2004-04-02 20:23:17 +00002880 if (isAffine()) {
2881 // If this is an affine expression then we have this situation:
2882 // Solve {0,+,A} in Range === Ax in Range
2883
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002884 // We know that zero is in the range. If A is positive then we know that
2885 // the upper value of the range must be the first possible exit value.
2886 // If A is negative then the lower of the range is the last possible loop
2887 // value. Also note that we already checked for a full range.
Reid Spencer581b0d42007-02-28 19:57:34 +00002888 APInt One(getBitWidth(),1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002889 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2890 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00002891
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002892 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00002893 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00002894 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002895
2896 // Evaluate at the exit value. If we really did fall out of the valid
2897 // range, then we computed our trip count, otherwise wrap around or other
2898 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00002899 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002900 if (Range.contains(Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002901 return new SCEVCouldNotCompute(); // Something strange happened
2902
2903 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00002904 assert(Range.contains(
2905 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00002906 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002907 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00002908 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00002909 } else if (isQuadratic()) {
2910 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2911 // quadratic equation to solve it. To do this, we must frame our problem in
2912 // terms of figuring out when zero is crossed, instead of when
2913 // Range.getUpper() is crossed.
2914 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00002915 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
2916 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002917
2918 // Next, solve the constructed addrec
2919 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00002920 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002921 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2922 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2923 if (R1) {
2924 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002925 if (ConstantInt *CB =
2926 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002927 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002928 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002929 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002930
Chris Lattner53e677a2004-04-02 20:23:17 +00002931 // Make sure the root is not off by one. The returned iteration should
2932 // not be in the range, but the previous one should be. When solving
2933 // for "X*X < 5", for example, we should not return a root of 2.
2934 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00002935 R1->getValue(),
2936 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002937 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002938 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00002939 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002940
Dan Gohman246b2562007-10-22 18:31:58 +00002941 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002942 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00002943 return SE.getConstant(NextVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002944 return new SCEVCouldNotCompute(); // Something strange happened
2945 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002946
Chris Lattner53e677a2004-04-02 20:23:17 +00002947 // If R1 was not in the range, then it is a good return value. Make
2948 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00002949 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00002950 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002951 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002952 return R1;
2953 return new SCEVCouldNotCompute(); // Something strange happened
2954 }
2955 }
2956 }
2957
Chris Lattner53e677a2004-04-02 20:23:17 +00002958 return new SCEVCouldNotCompute();
2959}
2960
2961
2962
2963//===----------------------------------------------------------------------===//
2964// ScalarEvolution Class Implementation
2965//===----------------------------------------------------------------------===//
2966
2967bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohman246b2562007-10-22 18:31:58 +00002968 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
Chris Lattner53e677a2004-04-02 20:23:17 +00002969 return false;
2970}
2971
2972void ScalarEvolution::releaseMemory() {
2973 delete (ScalarEvolutionsImpl*)Impl;
2974 Impl = 0;
2975}
2976
2977void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2978 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00002979 AU.addRequiredTransitive<LoopInfo>();
2980}
2981
2982SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2983 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2984}
2985
Chris Lattnera0740fb2005-08-09 23:36:33 +00002986/// hasSCEV - Return true if the SCEV for this value has already been
2987/// computed.
2988bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00002989 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00002990}
2991
2992
2993/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2994/// the specified value.
2995void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2996 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2997}
2998
2999
Chris Lattner53e677a2004-04-02 20:23:17 +00003000SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
3001 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
3002}
3003
3004bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
3005 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
3006}
3007
3008SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3009 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3010}
3011
Dan Gohman5cec4db2007-06-19 14:28:31 +00003012void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3013 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003014}
3015
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003016static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00003017 const Loop *L) {
3018 // Print all inner loops first
3019 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3020 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003021
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003022 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003023
Devang Patelb7211a22007-08-21 00:31:24 +00003024 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003025 L->getExitBlocks(ExitBlocks);
3026 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003027 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003028
3029 if (SE->hasLoopInvariantIterationCount(L)) {
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003030 OS << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003031 } else {
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003032 OS << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003033 }
3034
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003035 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00003036}
3037
Reid Spencerce9653c2004-12-07 04:03:45 +00003038void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00003039 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3040 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3041
3042 OS << "Classifying expressions for: " << F.getName() << "\n";
3043 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner42a75512007-01-15 02:27:26 +00003044 if (I->getType()->isInteger()) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00003045 OS << *I;
Dan Gohman8dae1382008-09-14 17:21:12 +00003046 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00003047 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00003048 SV->print(OS);
3049 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003050
Chris Lattner6ffe5512004-04-27 15:13:33 +00003051 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003052 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00003053 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003054 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3055 OS << "<<Unknown>>";
3056 } else {
3057 OS << *ExitValue;
3058 }
3059 }
3060
3061
3062 OS << "\n";
3063 }
3064
3065 OS << "Determining loop execution counts for: " << F.getName() << "\n";
3066 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3067 PrintLoopInfo(OS, this, *I);
3068}