blob: e82f5a4c503801be8a8c508bc5dcbe393dd6e7eb [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);
Chris Lattner53e677a2004-04-02 20:23:17 +0000115}
116
Reid Spencer581b0d42007-02-28 19:57:34 +0000117uint32_t SCEV::getBitWidth() const {
118 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
119 return ITy->getBitWidth();
120 return 0;
121}
122
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000123bool SCEV::isZero() const {
124 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
125 return SC->getValue()->isZero();
126 return false;
127}
128
Chris Lattner53e677a2004-04-02 20:23:17 +0000129
130SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
131
132bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
133 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000134 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000135}
136
137const Type *SCEVCouldNotCompute::getType() const {
138 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000139 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000140}
141
142bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
143 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
144 return false;
145}
146
Chris Lattner4dc534c2005-02-13 04:37:18 +0000147SCEVHandle SCEVCouldNotCompute::
148replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000149 const SCEVHandle &Conc,
150 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000151 return this;
152}
153
Chris Lattner53e677a2004-04-02 20:23:17 +0000154void SCEVCouldNotCompute::print(std::ostream &OS) const {
155 OS << "***COULDNOTCOMPUTE***";
156}
157
158bool SCEVCouldNotCompute::classof(const SCEV *S) {
159 return S->getSCEVType() == scCouldNotCompute;
160}
161
162
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000163// SCEVConstants - Only allow the creation of one SCEVConstant for any
164// particular value. Don't use a SCEVHandle here, or else the object will
165// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000166static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000167
Chris Lattner53e677a2004-04-02 20:23:17 +0000168
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000169SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000170 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000171}
Chris Lattner53e677a2004-04-02 20:23:17 +0000172
Dan Gohman246b2562007-10-22 18:31:58 +0000173SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Chris Lattnerb3364092006-10-04 21:49:37 +0000174 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000175 if (R == 0) R = new SCEVConstant(V);
176 return R;
177}
Chris Lattner53e677a2004-04-02 20:23:17 +0000178
Dan Gohman246b2562007-10-22 18:31:58 +0000179SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
180 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000181}
182
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000183const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000184
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000185void SCEVConstant::print(std::ostream &OS) const {
186 WriteAsOperand(OS, V, false);
187}
Chris Lattner53e677a2004-04-02 20:23:17 +0000188
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000189// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
190// particular input. Don't use a SCEVHandle here, or else the object will
191// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000192static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
193 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000194
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000195SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
196 : SCEV(scTruncate), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000197 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000198 "Cannot truncate non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000199 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
200 && "This is not a truncating conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000201}
Chris Lattner53e677a2004-04-02 20:23:17 +0000202
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000203SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000204 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000205}
Chris Lattner53e677a2004-04-02 20:23:17 +0000206
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000207void SCEVTruncateExpr::print(std::ostream &OS) const {
208 OS << "(truncate " << *Op << " to " << *Ty << ")";
209}
210
211// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
212// particular input. Don't use a SCEVHandle here, or else the object will never
213// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000214static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
215 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000216
217SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000218 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000219 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000220 "Cannot zero extend non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000221 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
222 && "This is not an extending conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000223}
224
225SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000226 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000227}
228
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000229void SCEVZeroExtendExpr::print(std::ostream &OS) const {
230 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
231}
232
Dan Gohmand19534a2007-06-15 14:38:12 +0000233// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
234// particular input. Don't use a SCEVHandle here, or else the object will never
235// be deleted!
236static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
237 SCEVSignExtendExpr*> > SCEVSignExtends;
238
239SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
240 : SCEV(scSignExtend), Op(op), Ty(ty) {
241 assert(Op->getType()->isInteger() && Ty->isInteger() &&
242 "Cannot sign extend non-integer value!");
243 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
244 && "This is not an extending conversion!");
245}
246
247SCEVSignExtendExpr::~SCEVSignExtendExpr() {
248 SCEVSignExtends->erase(std::make_pair(Op, Ty));
249}
250
Dan Gohmand19534a2007-06-15 14:38:12 +0000251void SCEVSignExtendExpr::print(std::ostream &OS) const {
252 OS << "(signextend " << *Op << " to " << *Ty << ")";
253}
254
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000255// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
256// particular input. Don't use a SCEVHandle here, or else the object will never
257// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000258static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
259 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000260
261SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000262 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
263 std::vector<SCEV*>(Operands.begin(),
264 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000265}
266
267void SCEVCommutativeExpr::print(std::ostream &OS) const {
268 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
269 const char *OpStr = getOperationStr();
270 OS << "(" << *Operands[0];
271 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
272 OS << OpStr << *Operands[i];
273 OS << ")";
274}
275
Chris Lattner4dc534c2005-02-13 04:37:18 +0000276SCEVHandle SCEVCommutativeExpr::
277replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000278 const SCEVHandle &Conc,
279 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000280 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000281 SCEVHandle H =
282 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000283 if (H != getOperand(i)) {
284 std::vector<SCEVHandle> NewOps;
285 NewOps.reserve(getNumOperands());
286 for (unsigned j = 0; j != i; ++j)
287 NewOps.push_back(getOperand(j));
288 NewOps.push_back(H);
289 for (++i; i != e; ++i)
290 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000291 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000292
293 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000294 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000295 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000296 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000297 else if (isa<SCEVSMaxExpr>(this))
298 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000299 else if (isa<SCEVUMaxExpr>(this))
300 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000301 else
302 assert(0 && "Unknown commutative expr!");
303 }
304 }
305 return this;
306}
307
308
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000309// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000310// input. Don't use a SCEVHandle here, or else the object will never be
311// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000312static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000313 SCEVUDivExpr*> > SCEVUDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000314
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000315SCEVUDivExpr::~SCEVUDivExpr() {
316 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000317}
318
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000319void SCEVUDivExpr::print(std::ostream &OS) const {
320 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000321}
322
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000323const Type *SCEVUDivExpr::getType() const {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000324 return LHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000325}
326
Nick Lewycky48dd6442008-12-02 08:05:48 +0000327
328// SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
329// input. Don't use a SCEVHandle here, or else the object will never be
330// deleted!
331static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
332 SCEVSDivExpr*> > SCEVSDivs;
333
334SCEVSDivExpr::~SCEVSDivExpr() {
335 SCEVSDivs->erase(std::make_pair(LHS, RHS));
336}
337
338void SCEVSDivExpr::print(std::ostream &OS) const {
339 OS << "(" << *LHS << " /s " << *RHS << ")";
340}
341
342const Type *SCEVSDivExpr::getType() const {
343 return LHS->getType();
344}
345
346
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000347// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
348// particular input. Don't use a SCEVHandle here, or else the object will never
349// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000350static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
351 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000352
353SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000354 SCEVAddRecExprs->erase(std::make_pair(L,
355 std::vector<SCEV*>(Operands.begin(),
356 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000357}
358
Chris Lattner4dc534c2005-02-13 04:37:18 +0000359SCEVHandle SCEVAddRecExpr::
360replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000361 const SCEVHandle &Conc,
362 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000363 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000364 SCEVHandle H =
365 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000366 if (H != getOperand(i)) {
367 std::vector<SCEVHandle> NewOps;
368 NewOps.reserve(getNumOperands());
369 for (unsigned j = 0; j != i; ++j)
370 NewOps.push_back(getOperand(j));
371 NewOps.push_back(H);
372 for (++i; i != e; ++i)
373 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000374 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000375
Dan Gohman246b2562007-10-22 18:31:58 +0000376 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000377 }
378 }
379 return this;
380}
381
382
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000383bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
384 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000385 // contain L and if the start is invariant.
386 return !QueryLoop->contains(L->getHeader()) &&
387 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000388}
389
390
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000391void SCEVAddRecExpr::print(std::ostream &OS) const {
392 OS << "{" << *Operands[0];
393 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
394 OS << ",+," << *Operands[i];
395 OS << "}<" << L->getHeader()->getName() + ">";
396}
Chris Lattner53e677a2004-04-02 20:23:17 +0000397
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000398// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
399// value. Don't use a SCEVHandle here, or else the object will never be
400// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000401static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000402
Chris Lattnerb3364092006-10-04 21:49:37 +0000403SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000404
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000405bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
406 // All non-instruction values are loop invariant. All instructions are loop
407 // invariant if they are not contained in the specified loop.
408 if (Instruction *I = dyn_cast<Instruction>(V))
409 return !L->contains(I->getParent());
410 return true;
411}
Chris Lattner53e677a2004-04-02 20:23:17 +0000412
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000413const Type *SCEVUnknown::getType() const {
414 return V->getType();
415}
Chris Lattner53e677a2004-04-02 20:23:17 +0000416
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000417void SCEVUnknown::print(std::ostream &OS) const {
418 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000419}
420
Chris Lattner8d741b82004-06-20 06:23:15 +0000421//===----------------------------------------------------------------------===//
422// SCEV Utilities
423//===----------------------------------------------------------------------===//
424
425namespace {
426 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
427 /// than the complexity of the RHS. This comparator is used to canonicalize
428 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000429 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000430 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Chris Lattner8d741b82004-06-20 06:23:15 +0000431 return LHS->getSCEVType() < RHS->getSCEVType();
432 }
433 };
434}
435
436/// GroupByComplexity - Given a list of SCEV objects, order them by their
437/// complexity, and group objects of the same complexity together by value.
438/// When this routine is finished, we know that any duplicates in the vector are
439/// consecutive and that complexity is monotonically increasing.
440///
441/// Note that we go take special precautions to ensure that we get determinstic
442/// results from this routine. In other words, we don't want the results of
443/// this to depend on where the addresses of various SCEV objects happened to
444/// land in memory.
445///
446static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
447 if (Ops.size() < 2) return; // Noop
448 if (Ops.size() == 2) {
449 // This is the common case, which also happens to be trivially simple.
450 // Special case it.
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000451 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000452 std::swap(Ops[0], Ops[1]);
453 return;
454 }
455
456 // Do the rough sort by complexity.
457 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
458
459 // Now that we are sorted by complexity, group elements of the same
460 // complexity. Note that this is, at worst, N^2, but the vector is likely to
461 // be extremely short in practice. Note that we take this approach because we
462 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000463 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000464 SCEV *S = Ops[i];
465 unsigned Complexity = S->getSCEVType();
466
467 // If there are any objects of the same complexity and same value as this
468 // one, group them.
469 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
470 if (Ops[j] == S) { // Found a duplicate.
471 // Move it to immediately after i'th element.
472 std::swap(Ops[i+1], Ops[j]);
473 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000474 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000475 }
476 }
477 }
478}
479
Chris Lattner53e677a2004-04-02 20:23:17 +0000480
Chris Lattner53e677a2004-04-02 20:23:17 +0000481
482//===----------------------------------------------------------------------===//
483// Simple SCEV method implementations
484//===----------------------------------------------------------------------===//
485
486/// getIntegerSCEV - Given an integer or FP type, create a constant for the
487/// specified signed integer value and return a SCEV for the constant.
Dan Gohman246b2562007-10-22 18:31:58 +0000488SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000489 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000490 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000491 C = Constant::getNullValue(Ty);
492 else if (Ty->isFloatingPoint())
Chris Lattner02a260a2008-04-20 00:41:09 +0000493 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
494 APFloat::IEEEdouble, Val));
Reid Spencere4d87aa2006-12-23 06:05:41 +0000495 else
Reid Spencerb83eb642006-10-20 07:07:24 +0000496 C = ConstantInt::get(Ty, Val);
Dan Gohman246b2562007-10-22 18:31:58 +0000497 return getUnknown(C);
Chris Lattner53e677a2004-04-02 20:23:17 +0000498}
499
Chris Lattner53e677a2004-04-02 20:23:17 +0000500/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
501///
Dan Gohman246b2562007-10-22 18:31:58 +0000502SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000503 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman246b2562007-10-22 18:31:58 +0000504 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000505
Nick Lewycky178f20a2008-02-20 06:58:55 +0000506 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
Nick Lewycky3e630762008-02-20 06:48:22 +0000507}
508
509/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
510SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
511 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
512 return getUnknown(ConstantExpr::getNot(VC->getValue()));
513
Nick Lewycky178f20a2008-02-20 06:58:55 +0000514 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
Nick Lewycky3e630762008-02-20 06:48:22 +0000515 return getMinusSCEV(AllOnes, V);
Chris Lattner53e677a2004-04-02 20:23:17 +0000516}
517
518/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
519///
Dan Gohman246b2562007-10-22 18:31:58 +0000520SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
521 const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000522 // X - Y --> X + -Y
Dan Gohman246b2562007-10-22 18:31:58 +0000523 return getAddExpr(LHS, getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000524}
525
526
Eli Friedmanb42a6262008-08-04 23:49:06 +0000527/// BinomialCoefficient - Compute BC(It, K). The result has width W.
528// Assume, K > 0.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000529static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedmanb42a6262008-08-04 23:49:06 +0000530 ScalarEvolution &SE,
531 const IntegerType* ResultTy) {
532 // Handle the simplest case efficiently.
533 if (K == 1)
534 return SE.getTruncateOrZeroExtend(It, ResultTy);
535
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000536 // We are using the following formula for BC(It, K):
537 //
538 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
539 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000540 // Suppose, W is the bitwidth of the return value. We must be prepared for
541 // overflow. Hence, we must assure that the result of our computation is
542 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
543 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000544 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000545 // However, this code doesn't use exactly that formula; the formula it uses
546 // is something like the following, where T is the number of factors of 2 in
547 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
548 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000549 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000550 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000551 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000552 // This formula is trivially equivalent to the previous formula. However,
553 // this formula can be implemented much more efficiently. The trick is that
554 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
555 // arithmetic. To do exact division in modular arithmetic, all we have
556 // to do is multiply by the inverse. Therefore, this step can be done at
557 // width W.
558 //
559 // The next issue is how to safely do the division by 2^T. The way this
560 // is done is by doing the multiplication step at a width of at least W + T
561 // bits. This way, the bottom W+T bits of the product are accurate. Then,
562 // when we perform the division by 2^T (which is equivalent to a right shift
563 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
564 // truncated out after the division by 2^T.
565 //
566 // In comparison to just directly using the first formula, this technique
567 // is much more efficient; using the first formula requires W * K bits,
568 // but this formula less than W + K bits. Also, the first formula requires
569 // a division step, whereas this formula only requires multiplies and shifts.
570 //
571 // It doesn't matter whether the subtraction step is done in the calculation
572 // width or the input iteration count's width; if the subtraction overflows,
573 // the result must be zero anyway. We prefer here to do it in the width of
574 // the induction variable because it helps a lot for certain cases; CodeGen
575 // isn't smart enough to ignore the overflow, which leads to much less
576 // efficient code if the width of the subtraction is wider than the native
577 // register width.
578 //
579 // (It's possible to not widen at all by pulling out factors of 2 before
580 // the multiplication; for example, K=2 can be calculated as
581 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
582 // extra arithmetic, so it's not an obvious win, and it gets
583 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000584
Eli Friedmanb42a6262008-08-04 23:49:06 +0000585 // Protection from insane SCEVs; this bound is conservative,
586 // but it probably doesn't matter.
587 if (K > 1000)
588 return new SCEVCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000589
Eli Friedmanb42a6262008-08-04 23:49:06 +0000590 unsigned W = ResultTy->getBitWidth();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000591
Eli Friedmanb42a6262008-08-04 23:49:06 +0000592 // Calculate K! / 2^T and T; we divide out the factors of two before
593 // multiplying for calculating K! / 2^T to avoid overflow.
594 // Other overflow doesn't matter because we only care about the bottom
595 // W bits of the result.
596 APInt OddFactorial(W, 1);
597 unsigned T = 1;
598 for (unsigned i = 3; i <= K; ++i) {
599 APInt Mult(W, i);
600 unsigned TwoFactors = Mult.countTrailingZeros();
601 T += TwoFactors;
602 Mult = Mult.lshr(TwoFactors);
603 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000604 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000605
Eli Friedmanb42a6262008-08-04 23:49:06 +0000606 // We need at least W + T bits for the multiplication step
607 // FIXME: A temporary hack; we round up the bitwidths
608 // to the nearest power of 2 to be nice to the code generator.
609 unsigned CalculationBits = 1U << Log2_32_Ceil(W + T);
610 // FIXME: Temporary hack to avoid generating integers that are too wide.
611 // Although, it's not completely clear how to determine how much
612 // widening is safe; for example, on X86, we can't really widen
613 // beyond 64 because we need to be able to do multiplication
614 // that's CalculationBits wide, but on X86-64, we can safely widen up to
615 // 128 bits.
616 if (CalculationBits > 64)
617 return new SCEVCouldNotCompute();
618
619 // Calcuate 2^T, at width T+W.
620 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
621
622 // Calculate the multiplicative inverse of K! / 2^T;
623 // this multiplication factor will perform the exact division by
624 // K! / 2^T.
625 APInt Mod = APInt::getSignedMinValue(W+1);
626 APInt MultiplyFactor = OddFactorial.zext(W+1);
627 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
628 MultiplyFactor = MultiplyFactor.trunc(W);
629
630 // Calculate the product, at width T+W
631 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
632 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
633 for (unsigned i = 1; i != K; ++i) {
634 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
635 Dividend = SE.getMulExpr(Dividend,
636 SE.getTruncateOrZeroExtend(S, CalculationTy));
637 }
638
639 // Divide by 2^T
640 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
641
642 // Truncate the result, and divide by K! / 2^T.
643
644 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
645 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000646}
647
Chris Lattner53e677a2004-04-02 20:23:17 +0000648/// evaluateAtIteration - Return the value of this chain of recurrences at
649/// the specified iteration number. We can evaluate this recurrence by
650/// multiplying each element in the chain by the binomial coefficient
651/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
652///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000653/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000654///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000655/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000656///
Dan Gohman246b2562007-10-22 18:31:58 +0000657SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
658 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000659 SCEVHandle Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000660 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000661 // The computation is correct in the face of overflow provided that the
662 // multiplication is performed _after_ the evaluation of the binomial
663 // coefficient.
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000664 SCEVHandle Coeff = BinomialCoefficient(It, i, SE,
665 cast<IntegerType>(getType()));
666 if (isa<SCEVCouldNotCompute>(Coeff))
667 return Coeff;
668
669 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000670 }
671 return Result;
672}
673
Chris Lattner53e677a2004-04-02 20:23:17 +0000674//===----------------------------------------------------------------------===//
675// SCEV Expression folder implementations
676//===----------------------------------------------------------------------===//
677
Dan Gohman246b2562007-10-22 18:31:58 +0000678SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000679 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000680 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000681 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000682
683 // If the input value is a chrec scev made out of constants, truncate
684 // all of the constants.
685 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
686 std::vector<SCEVHandle> Operands;
687 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
688 // FIXME: This should allow truncation of other expression types!
689 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman246b2562007-10-22 18:31:58 +0000690 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000691 else
692 break;
693 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman246b2562007-10-22 18:31:58 +0000694 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000695 }
696
Chris Lattnerb3364092006-10-04 21:49:37 +0000697 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000698 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
699 return Result;
700}
701
Dan Gohman246b2562007-10-22 18:31:58 +0000702SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000703 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000704 return getUnknown(
Reid Spencerd977d862006-12-12 23:36:14 +0000705 ConstantExpr::getZExt(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000706
707 // FIXME: If the input value is a chrec scev, and we can prove that the value
708 // did not overflow the old, smaller, value, we can zero extend all of the
709 // operands (often constants). This would allow analysis of something like
710 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
711
Chris Lattnerb3364092006-10-04 21:49:37 +0000712 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000713 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
714 return Result;
715}
716
Dan Gohman246b2562007-10-22 18:31:58 +0000717SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmand19534a2007-06-15 14:38:12 +0000718 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000719 return getUnknown(
Dan Gohmand19534a2007-06-15 14:38:12 +0000720 ConstantExpr::getSExt(SC->getValue(), Ty));
721
722 // FIXME: If the input value is a chrec scev, and we can prove that the value
723 // did not overflow the old, smaller, value, we can sign extend all of the
724 // operands (often constants). This would allow analysis of something like
725 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
726
727 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
728 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
729 return Result;
730}
731
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000732/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
733/// of the input value to the specified type. If the type must be
734/// extended, it is zero extended.
735SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
736 const Type *Ty) {
737 const Type *SrcTy = V->getType();
738 assert(SrcTy->isInteger() && Ty->isInteger() &&
739 "Cannot truncate or zero extend with non-integer arguments!");
740 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
741 return V; // No conversion
742 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
743 return getTruncateExpr(V, Ty);
744 return getZeroExtendExpr(V, Ty);
745}
746
Chris Lattner53e677a2004-04-02 20:23:17 +0000747// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman246b2562007-10-22 18:31:58 +0000748SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000749 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000750 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000751
752 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000753 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000754
755 // If there are any constants, fold them together.
756 unsigned Idx = 0;
757 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
758 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000759 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000760 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
761 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000762 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
763 RHSC->getValue()->getValue());
764 Ops[0] = getConstant(Fold);
765 Ops.erase(Ops.begin()+1); // Erase the folded element
766 if (Ops.size() == 1) return Ops[0];
767 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000768 }
769
770 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +0000771 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000772 Ops.erase(Ops.begin());
773 --Idx;
774 }
775 }
776
Chris Lattner627018b2004-04-07 16:16:11 +0000777 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000778
Chris Lattner53e677a2004-04-02 20:23:17 +0000779 // Okay, check to see if the same value occurs in the operand list twice. If
780 // so, merge them together into an multiply expression. Since we sorted the
781 // list, these values are required to be adjacent.
782 const Type *Ty = Ops[0]->getType();
783 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
784 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
785 // Found a match, merge the two values into a multiply, and add any
786 // remaining values to the result.
Dan Gohman246b2562007-10-22 18:31:58 +0000787 SCEVHandle Two = getIntegerSCEV(2, Ty);
788 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +0000789 if (Ops.size() == 2)
790 return Mul;
791 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
792 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +0000793 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000794 }
795
Dan Gohmanf50cd742007-06-18 19:30:09 +0000796 // Now we know the first non-constant operand. Skip past any cast SCEVs.
797 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
798 ++Idx;
799
800 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +0000801 if (Idx < Ops.size()) {
802 bool DeletedAdd = false;
803 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
804 // If we have an add, expand the add operands onto the end of the operands
805 // list.
806 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
807 Ops.erase(Ops.begin()+Idx);
808 DeletedAdd = true;
809 }
810
811 // If we deleted at least one add, we added operands to the end of the list,
812 // and they are not necessarily sorted. Recurse to resort and resimplify
813 // any operands we just aquired.
814 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +0000815 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000816 }
817
818 // Skip over the add expression until we get to a multiply.
819 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
820 ++Idx;
821
822 // If we are adding something to a multiply expression, make sure the
823 // something is not already an operand of the multiply. If so, merge it into
824 // the multiply.
825 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
826 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
827 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
828 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
829 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000830 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000831 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
832 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
833 if (Mul->getNumOperands() != 2) {
834 // If the multiply has more than two operands, we must get the
835 // Y*Z term.
836 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
837 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000838 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000839 }
Dan Gohman246b2562007-10-22 18:31:58 +0000840 SCEVHandle One = getIntegerSCEV(1, Ty);
841 SCEVHandle AddOne = getAddExpr(InnerMul, One);
842 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000843 if (Ops.size() == 2) return OuterMul;
844 if (AddOp < Idx) {
845 Ops.erase(Ops.begin()+AddOp);
846 Ops.erase(Ops.begin()+Idx-1);
847 } else {
848 Ops.erase(Ops.begin()+Idx);
849 Ops.erase(Ops.begin()+AddOp-1);
850 }
851 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000852 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000853 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000854
Chris Lattner53e677a2004-04-02 20:23:17 +0000855 // Check this multiply against other multiplies being added together.
856 for (unsigned OtherMulIdx = Idx+1;
857 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
858 ++OtherMulIdx) {
859 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
860 // If MulOp occurs in OtherMul, we can fold the two multiplies
861 // together.
862 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
863 OMulOp != e; ++OMulOp)
864 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
865 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
866 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
867 if (Mul->getNumOperands() != 2) {
868 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
869 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000870 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000871 }
872 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
873 if (OtherMul->getNumOperands() != 2) {
874 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
875 OtherMul->op_end());
876 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000877 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000878 }
Dan Gohman246b2562007-10-22 18:31:58 +0000879 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
880 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +0000881 if (Ops.size() == 2) return OuterMul;
882 Ops.erase(Ops.begin()+Idx);
883 Ops.erase(Ops.begin()+OtherMulIdx-1);
884 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000885 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000886 }
887 }
888 }
889 }
890
891 // If there are any add recurrences in the operands list, see if any other
892 // added values are loop invariant. If so, we can fold them into the
893 // recurrence.
894 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
895 ++Idx;
896
897 // Scan over all recurrences, trying to fold loop invariants into them.
898 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
899 // Scan all of the other operands to this add and add them to the vector if
900 // they are loop invariant w.r.t. the recurrence.
901 std::vector<SCEVHandle> LIOps;
902 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
903 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
904 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
905 LIOps.push_back(Ops[i]);
906 Ops.erase(Ops.begin()+i);
907 --i; --e;
908 }
909
910 // If we found some loop invariants, fold them into the recurrence.
911 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +0000912 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +0000913 LIOps.push_back(AddRec->getStart());
914
915 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +0000916 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000917
Dan Gohman246b2562007-10-22 18:31:58 +0000918 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000919 // If all of the other operands were loop invariant, we are done.
920 if (Ops.size() == 1) return NewRec;
921
922 // Otherwise, add the folded AddRec by the non-liv parts.
923 for (unsigned i = 0;; ++i)
924 if (Ops[i] == AddRec) {
925 Ops[i] = NewRec;
926 break;
927 }
Dan Gohman246b2562007-10-22 18:31:58 +0000928 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000929 }
930
931 // Okay, if there weren't any loop invariants to be folded, check to see if
932 // there are multiple AddRec's with the same loop induction variable being
933 // added together. If so, we can fold them.
934 for (unsigned OtherIdx = Idx+1;
935 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
936 if (OtherIdx != Idx) {
937 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
938 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
939 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
940 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
941 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
942 if (i >= NewOps.size()) {
943 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
944 OtherAddRec->op_end());
945 break;
946 }
Dan Gohman246b2562007-10-22 18:31:58 +0000947 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +0000948 }
Dan Gohman246b2562007-10-22 18:31:58 +0000949 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000950
951 if (Ops.size() == 2) return NewAddRec;
952
953 Ops.erase(Ops.begin()+Idx);
954 Ops.erase(Ops.begin()+OtherIdx-1);
955 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +0000956 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000957 }
958 }
959
960 // Otherwise couldn't fold anything into this recurrence. Move onto the
961 // next one.
962 }
963
964 // Okay, it looks like we really DO need an add expr. Check to see if we
965 // already have one, otherwise create a new one.
966 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000967 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
968 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000969 if (Result == 0) Result = new SCEVAddExpr(Ops);
970 return Result;
971}
972
973
Dan Gohman246b2562007-10-22 18:31:58 +0000974SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000975 assert(!Ops.empty() && "Cannot get empty mul!");
976
977 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000978 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000979
980 // If there are any constants, fold them together.
981 unsigned Idx = 0;
982 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
983
984 // C1*(C2+V) -> C1*C2 + C1*V
985 if (Ops.size() == 2)
986 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
987 if (Add->getNumOperands() == 2 &&
988 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +0000989 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
990 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000991
992
993 ++Idx;
994 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
995 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000996 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
997 RHSC->getValue()->getValue());
998 Ops[0] = getConstant(Fold);
999 Ops.erase(Ops.begin()+1); // Erase the folded element
1000 if (Ops.size() == 1) return Ops[0];
1001 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001002 }
1003
1004 // If we are left with a constant one being multiplied, strip it off.
1005 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1006 Ops.erase(Ops.begin());
1007 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001008 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001009 // If we have a multiply of zero, it will always be zero.
1010 return Ops[0];
1011 }
1012 }
1013
1014 // Skip over the add expression until we get to a multiply.
1015 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1016 ++Idx;
1017
1018 if (Ops.size() == 1)
1019 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001020
Chris Lattner53e677a2004-04-02 20:23:17 +00001021 // If there are mul operands inline them all into this expression.
1022 if (Idx < Ops.size()) {
1023 bool DeletedMul = false;
1024 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1025 // If we have an mul, expand the mul operands onto the end of the operands
1026 // list.
1027 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1028 Ops.erase(Ops.begin()+Idx);
1029 DeletedMul = true;
1030 }
1031
1032 // If we deleted at least one mul, we added operands to the end of the list,
1033 // and they are not necessarily sorted. Recurse to resort and resimplify
1034 // any operands we just aquired.
1035 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001036 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001037 }
1038
1039 // If there are any add recurrences in the operands list, see if any other
1040 // added values are loop invariant. If so, we can fold them into the
1041 // recurrence.
1042 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1043 ++Idx;
1044
1045 // Scan over all recurrences, trying to fold loop invariants into them.
1046 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1047 // Scan all of the other operands to this mul and add them to the vector if
1048 // they are loop invariant w.r.t. the recurrence.
1049 std::vector<SCEVHandle> LIOps;
1050 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1051 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1052 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1053 LIOps.push_back(Ops[i]);
1054 Ops.erase(Ops.begin()+i);
1055 --i; --e;
1056 }
1057
1058 // If we found some loop invariants, fold them into the recurrence.
1059 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001060 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001061 std::vector<SCEVHandle> NewOps;
1062 NewOps.reserve(AddRec->getNumOperands());
1063 if (LIOps.size() == 1) {
1064 SCEV *Scale = LIOps[0];
1065 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001066 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001067 } else {
1068 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1069 std::vector<SCEVHandle> MulOps(LIOps);
1070 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001071 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001072 }
1073 }
1074
Dan Gohman246b2562007-10-22 18:31:58 +00001075 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001076
1077 // If all of the other operands were loop invariant, we are done.
1078 if (Ops.size() == 1) return NewRec;
1079
1080 // Otherwise, multiply the folded AddRec by the non-liv parts.
1081 for (unsigned i = 0;; ++i)
1082 if (Ops[i] == AddRec) {
1083 Ops[i] = NewRec;
1084 break;
1085 }
Dan Gohman246b2562007-10-22 18:31:58 +00001086 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001087 }
1088
1089 // Okay, if there weren't any loop invariants to be folded, check to see if
1090 // there are multiple AddRec's with the same loop induction variable being
1091 // multiplied together. If so, we can fold them.
1092 for (unsigned OtherIdx = Idx+1;
1093 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1094 if (OtherIdx != Idx) {
1095 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1096 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1097 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1098 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman246b2562007-10-22 18:31:58 +00001099 SCEVHandle NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001100 G->getStart());
Dan Gohman246b2562007-10-22 18:31:58 +00001101 SCEVHandle B = F->getStepRecurrence(*this);
1102 SCEVHandle D = G->getStepRecurrence(*this);
1103 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1104 getMulExpr(G, B),
1105 getMulExpr(B, D));
1106 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1107 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001108 if (Ops.size() == 2) return NewAddRec;
1109
1110 Ops.erase(Ops.begin()+Idx);
1111 Ops.erase(Ops.begin()+OtherIdx-1);
1112 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001113 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001114 }
1115 }
1116
1117 // Otherwise couldn't fold anything into this recurrence. Move onto the
1118 // next one.
1119 }
1120
1121 // Okay, it looks like we really DO need an mul expr. Check to see if we
1122 // already have one, otherwise create a new one.
1123 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001124 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1125 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001126 if (Result == 0)
1127 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001128 return Result;
1129}
1130
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001131SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Nick Lewycky48dd6442008-12-02 08:05:48 +00001132 if (LHS == RHS)
1133 return getIntegerSCEV(1, LHS->getType()); // X udiv X --> 1
1134
Chris Lattner53e677a2004-04-02 20:23:17 +00001135 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1136 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky48dd6442008-12-02 08:05:48 +00001137 return LHS; // X udiv 1 --> X
Chris Lattner53e677a2004-04-02 20:23:17 +00001138
1139 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1140 Constant *LHSCV = LHSC->getValue();
1141 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001142 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001143 }
1144 }
1145
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001146 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1147 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001148 return Result;
1149}
1150
Nick Lewycky48dd6442008-12-02 08:05:48 +00001151SCEVHandle ScalarEvolution::getSDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1152 if (LHS == RHS)
1153 return getIntegerSCEV(1, LHS->getType()); // X sdiv X --> 1
1154
1155 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1156 if (RHSC->getValue()->equalsInt(1))
1157 return LHS; // X sdiv 1 --> X
1158
1159 if (RHSC->getValue()->isAllOnesValue())
1160 return getNegativeSCEV(LHS); // X sdiv -1 --> -X
1161
1162 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1163 Constant *LHSCV = LHSC->getValue();
1164 Constant *RHSCV = RHSC->getValue();
1165 return getUnknown(ConstantExpr::getSDiv(LHSCV, RHSCV));
1166 }
1167 }
1168
1169 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
1170 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
1171 return Result;
1172}
1173
Chris Lattner53e677a2004-04-02 20:23:17 +00001174
1175/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1176/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001177SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Chris Lattner53e677a2004-04-02 20:23:17 +00001178 const SCEVHandle &Step, const Loop *L) {
1179 std::vector<SCEVHandle> Operands;
1180 Operands.push_back(Start);
1181 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1182 if (StepChrec->getLoop() == L) {
1183 Operands.insert(Operands.end(), StepChrec->op_begin(),
1184 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001185 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001186 }
1187
1188 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001189 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001190}
1191
1192/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1193/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001194SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Chris Lattner53e677a2004-04-02 20:23:17 +00001195 const Loop *L) {
1196 if (Operands.size() == 1) return Operands[0];
1197
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001198 if (Operands.back()->isZero()) {
1199 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001200 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001201 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001202
Dan Gohmand9cc7492008-08-08 18:33:12 +00001203 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1204 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1205 const Loop* NestedLoop = NestedAR->getLoop();
1206 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1207 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1208 NestedAR->op_end());
1209 SCEVHandle NestedARHandle(NestedAR);
1210 Operands[0] = NestedAR->getStart();
1211 NestedOperands[0] = getAddRecExpr(Operands, L);
1212 return getAddRecExpr(NestedOperands, NestedLoop);
1213 }
1214 }
1215
Chris Lattner53e677a2004-04-02 20:23:17 +00001216 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001217 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1218 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001219 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1220 return Result;
1221}
1222
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001223SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1224 const SCEVHandle &RHS) {
1225 std::vector<SCEVHandle> Ops;
1226 Ops.push_back(LHS);
1227 Ops.push_back(RHS);
1228 return getSMaxExpr(Ops);
1229}
1230
1231SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1232 assert(!Ops.empty() && "Cannot get empty smax!");
1233 if (Ops.size() == 1) return Ops[0];
1234
1235 // Sort by complexity, this groups all similar expression types together.
1236 GroupByComplexity(Ops);
1237
1238 // If there are any constants, fold them together.
1239 unsigned Idx = 0;
1240 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1241 ++Idx;
1242 assert(Idx < Ops.size());
1243 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1244 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001245 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001246 APIntOps::smax(LHSC->getValue()->getValue(),
1247 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001248 Ops[0] = getConstant(Fold);
1249 Ops.erase(Ops.begin()+1); // Erase the folded element
1250 if (Ops.size() == 1) return Ops[0];
1251 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001252 }
1253
1254 // If we are left with a constant -inf, strip it off.
1255 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1256 Ops.erase(Ops.begin());
1257 --Idx;
1258 }
1259 }
1260
1261 if (Ops.size() == 1) return Ops[0];
1262
1263 // Find the first SMax
1264 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1265 ++Idx;
1266
1267 // Check to see if one of the operands is an SMax. If so, expand its operands
1268 // onto our operand list, and recurse to simplify.
1269 if (Idx < Ops.size()) {
1270 bool DeletedSMax = false;
1271 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1272 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1273 Ops.erase(Ops.begin()+Idx);
1274 DeletedSMax = true;
1275 }
1276
1277 if (DeletedSMax)
1278 return getSMaxExpr(Ops);
1279 }
1280
1281 // Okay, check to see if the same value occurs in the operand list twice. If
1282 // so, delete one. Since we sorted the list, these values are required to
1283 // be adjacent.
1284 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1285 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1286 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1287 --i; --e;
1288 }
1289
1290 if (Ops.size() == 1) return Ops[0];
1291
1292 assert(!Ops.empty() && "Reduced smax down to nothing!");
1293
Nick Lewycky3e630762008-02-20 06:48:22 +00001294 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001295 // already have one, otherwise create a new one.
1296 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1297 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1298 SCEVOps)];
1299 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1300 return Result;
1301}
1302
Nick Lewycky3e630762008-02-20 06:48:22 +00001303SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1304 const SCEVHandle &RHS) {
1305 std::vector<SCEVHandle> Ops;
1306 Ops.push_back(LHS);
1307 Ops.push_back(RHS);
1308 return getUMaxExpr(Ops);
1309}
1310
1311SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1312 assert(!Ops.empty() && "Cannot get empty umax!");
1313 if (Ops.size() == 1) return Ops[0];
1314
1315 // Sort by complexity, this groups all similar expression types together.
1316 GroupByComplexity(Ops);
1317
1318 // If there are any constants, fold them together.
1319 unsigned Idx = 0;
1320 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1321 ++Idx;
1322 assert(Idx < Ops.size());
1323 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1324 // We found two constants, fold them together!
1325 ConstantInt *Fold = ConstantInt::get(
1326 APIntOps::umax(LHSC->getValue()->getValue(),
1327 RHSC->getValue()->getValue()));
1328 Ops[0] = getConstant(Fold);
1329 Ops.erase(Ops.begin()+1); // Erase the folded element
1330 if (Ops.size() == 1) return Ops[0];
1331 LHSC = cast<SCEVConstant>(Ops[0]);
1332 }
1333
1334 // If we are left with a constant zero, strip it off.
1335 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1336 Ops.erase(Ops.begin());
1337 --Idx;
1338 }
1339 }
1340
1341 if (Ops.size() == 1) return Ops[0];
1342
1343 // Find the first UMax
1344 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1345 ++Idx;
1346
1347 // Check to see if one of the operands is a UMax. If so, expand its operands
1348 // onto our operand list, and recurse to simplify.
1349 if (Idx < Ops.size()) {
1350 bool DeletedUMax = false;
1351 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1352 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1353 Ops.erase(Ops.begin()+Idx);
1354 DeletedUMax = true;
1355 }
1356
1357 if (DeletedUMax)
1358 return getUMaxExpr(Ops);
1359 }
1360
1361 // Okay, check to see if the same value occurs in the operand list twice. If
1362 // so, delete one. Since we sorted the list, these values are required to
1363 // be adjacent.
1364 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1365 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1366 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1367 --i; --e;
1368 }
1369
1370 if (Ops.size() == 1) return Ops[0];
1371
1372 assert(!Ops.empty() && "Reduced umax down to nothing!");
1373
1374 // Okay, it looks like we really DO need a umax expr. Check to see if we
1375 // already have one, otherwise create a new one.
1376 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1377 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1378 SCEVOps)];
1379 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1380 return Result;
1381}
1382
Dan Gohman246b2562007-10-22 18:31:58 +00001383SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001384 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001385 return getConstant(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001386 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001387 if (Result == 0) Result = new SCEVUnknown(V);
1388 return Result;
1389}
1390
Chris Lattner53e677a2004-04-02 20:23:17 +00001391
1392//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001393// ScalarEvolutionsImpl Definition and Implementation
1394//===----------------------------------------------------------------------===//
1395//
1396/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1397/// evolution code.
1398///
1399namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001400 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohman246b2562007-10-22 18:31:58 +00001401 /// SE - A reference to the public ScalarEvolution object.
1402 ScalarEvolution &SE;
1403
Chris Lattner53e677a2004-04-02 20:23:17 +00001404 /// F - The function we are analyzing.
1405 ///
1406 Function &F;
1407
1408 /// LI - The loop information for the function we are currently analyzing.
1409 ///
1410 LoopInfo &LI;
1411
1412 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1413 /// things.
1414 SCEVHandle UnknownValue;
1415
1416 /// Scalars - This is a cache of the scalars we have analyzed so far.
1417 ///
1418 std::map<Value*, SCEVHandle> Scalars;
1419
1420 /// IterationCounts - Cache the iteration count of the loops for this
1421 /// function as they are computed.
1422 std::map<const Loop*, SCEVHandle> IterationCounts;
1423
Chris Lattner3221ad02004-04-17 22:58:41 +00001424 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1425 /// the PHI instructions that we attempt to compute constant evolutions for.
1426 /// This allows us to avoid potentially expensive recomputation of these
1427 /// properties. An instruction maps to null if we are unable to compute its
1428 /// exit value.
1429 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001430
Chris Lattner53e677a2004-04-02 20:23:17 +00001431 public:
Dan Gohman246b2562007-10-22 18:31:58 +00001432 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1433 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
Chris Lattner53e677a2004-04-02 20:23:17 +00001434
1435 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1436 /// expression and create a new one.
1437 SCEVHandle getSCEV(Value *V);
1438
Chris Lattnera0740fb2005-08-09 23:36:33 +00001439 /// hasSCEV - Return true if the SCEV for this value has already been
1440 /// computed.
1441 bool hasSCEV(Value *V) const {
1442 return Scalars.count(V);
1443 }
1444
1445 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1446 /// the specified value.
1447 void setSCEV(Value *V, const SCEVHandle &H) {
1448 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1449 assert(isNew && "This entry already existed!");
Devang Patel89d0a4d2008-11-11 19:17:41 +00001450 isNew = false;
Chris Lattnera0740fb2005-08-09 23:36:33 +00001451 }
1452
1453
Chris Lattner53e677a2004-04-02 20:23:17 +00001454 /// getSCEVAtScope - Compute the value of the specified expression within
1455 /// the indicated loop (which may be null to indicate in no loop). If the
1456 /// expression cannot be evaluated, return UnknownValue itself.
1457 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1458
1459
1460 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1461 /// an analyzable loop-invariant iteration count.
1462 bool hasLoopInvariantIterationCount(const Loop *L);
1463
1464 /// getIterationCount - If the specified loop has a predictable iteration
1465 /// count, return it. Note that it is not valid to call this method on a
1466 /// loop without a loop-invariant iteration count.
1467 SCEVHandle getIterationCount(const Loop *L);
1468
Dan Gohman5cec4db2007-06-19 14:28:31 +00001469 /// deleteValueFromRecords - This method should be called by the
1470 /// client before it removes a value from the program, to make sure
Chris Lattner53e677a2004-04-02 20:23:17 +00001471 /// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001472 void deleteValueFromRecords(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001473
1474 private:
1475 /// createSCEV - We know that there is no SCEV for the specified value.
1476 /// Analyze the expression.
1477 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001478
1479 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1480 /// SCEVs.
1481 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001482
1483 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1484 /// for the specified instruction and replaces any references to the
1485 /// symbolic value SymName with the specified value. This is used during
1486 /// PHI resolution.
1487 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1488 const SCEVHandle &SymName,
1489 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001490
1491 /// ComputeIterationCount - Compute the number of times the specified loop
1492 /// will iterate.
1493 SCEVHandle ComputeIterationCount(const Loop *L);
1494
Chris Lattner673e02b2004-10-12 01:49:27 +00001495 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001496 /// 'icmp op load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00001497 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1498 Constant *RHS,
1499 const Loop *L,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001500 ICmpInst::Predicate p);
Chris Lattner673e02b2004-10-12 01:49:27 +00001501
Chris Lattner7980fb92004-04-17 18:36:24 +00001502 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1503 /// constant number of times (the condition evolves only from constants),
1504 /// try to evaluate a few iterations of the loop until we get the exit
1505 /// condition gets a value of ExitWhen (true or false). If we cannot
1506 /// evaluate the trip count of the loop, return UnknownValue.
1507 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1508 bool ExitWhen);
1509
Chris Lattner53e677a2004-04-02 20:23:17 +00001510 /// HowFarToZero - Return the number of times a backedge comparing the
1511 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001512 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001513 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1514
1515 /// HowFarToNonZero - Return the number of times a backedge checking the
1516 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001517 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001518 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001519
Chris Lattnerdb25de42005-08-15 23:33:51 +00001520 /// HowManyLessThans - Return the number of times a backedge containing the
1521 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001522 /// UnknownValue. isSigned specifies whether the less-than is signed.
1523 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
Nick Lewyckydd643f22008-11-18 15:10:54 +00001524 bool isSigned, bool trueWhenEqual);
Chris Lattnerdb25de42005-08-15 23:33:51 +00001525
Dan Gohmanfd6edef2008-09-15 22:18:04 +00001526 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
1527 /// (which may not be an immediate predecessor) which has exactly one
1528 /// successor from which BB is reachable, or null if no such block is
1529 /// found.
1530 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1531
Nick Lewycky59cff122008-07-12 07:41:32 +00001532 /// executesAtLeastOnce - Test whether entry to the loop is protected by
1533 /// a conditional between LHS and RHS.
Nick Lewyckydd643f22008-11-18 15:10:54 +00001534 bool executesAtLeastOnce(const Loop *L, bool isSigned, bool trueWhenEqual,
1535 SCEV *LHS, SCEV *RHS);
1536
1537 /// potentialInfiniteLoop - Test whether the loop might jump over the exit value
1538 /// due to wrapping.
1539 bool potentialInfiniteLoop(SCEV *Stride, SCEV *RHS, bool isSigned,
1540 bool trueWhenEqual);
Nick Lewycky59cff122008-07-12 07:41:32 +00001541
Chris Lattner3221ad02004-04-17 22:58:41 +00001542 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1543 /// in the header of its containing loop, we know the loop executes a
1544 /// constant number of times, and the PHI node is just a recurrence
1545 /// involving constants, fold it.
Reid Spencere8019bb2007-03-01 07:25:48 +00001546 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
Chris Lattner3221ad02004-04-17 22:58:41 +00001547 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001548 };
1549}
1550
1551//===----------------------------------------------------------------------===//
1552// Basic SCEV Analysis and PHI Idiom Recognition Code
1553//
1554
Dan Gohman5cec4db2007-06-19 14:28:31 +00001555/// deleteValueFromRecords - This method should be called by the
Chris Lattner53e677a2004-04-02 20:23:17 +00001556/// client before it removes an instruction from the program, to make sure
1557/// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001558void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1559 SmallVector<Value *, 16> Worklist;
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001560
Dan Gohman5cec4db2007-06-19 14:28:31 +00001561 if (Scalars.erase(V)) {
1562 if (PHINode *PN = dyn_cast<PHINode>(V))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001563 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman5cec4db2007-06-19 14:28:31 +00001564 Worklist.push_back(V);
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001565 }
1566
1567 while (!Worklist.empty()) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001568 Value *VV = Worklist.back();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001569 Worklist.pop_back();
1570
Dan Gohman5cec4db2007-06-19 14:28:31 +00001571 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001572 UI != UE; ++UI) {
Nick Lewycky51e844b2007-06-06 11:26:20 +00001573 Instruction *Inst = cast<Instruction>(*UI);
1574 if (Scalars.erase(Inst)) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001575 if (PHINode *PN = dyn_cast<PHINode>(VV))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001576 ConstantEvolutionLoopExitValue.erase(PN);
1577 Worklist.push_back(Inst);
1578 }
1579 }
1580 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001581}
1582
1583
1584/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1585/// expression and create a new one.
1586SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1587 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1588
1589 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1590 if (I != Scalars.end()) return I->second;
1591 SCEVHandle S = createSCEV(V);
1592 Scalars.insert(std::make_pair(V, S));
1593 return S;
1594}
1595
Chris Lattner4dc534c2005-02-13 04:37:18 +00001596/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1597/// the specified instruction and replaces any references to the symbolic value
1598/// SymName with the specified value. This is used during PHI resolution.
1599void ScalarEvolutionsImpl::
1600ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1601 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001602 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001603 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001604
Chris Lattner4dc534c2005-02-13 04:37:18 +00001605 SCEVHandle NV =
Dan Gohman246b2562007-10-22 18:31:58 +00001606 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001607 if (NV == SI->second) return; // No change.
1608
1609 SI->second = NV; // Update the scalars map!
1610
1611 // Any instruction values that use this instruction might also need to be
1612 // updated!
1613 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1614 UI != E; ++UI)
1615 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1616}
Chris Lattner53e677a2004-04-02 20:23:17 +00001617
1618/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1619/// a loop header, making it a potential recurrence, or it doesn't.
1620///
1621SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1622 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1623 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1624 if (L->getHeader() == PN->getParent()) {
1625 // If it lives in the loop header, it has two incoming values, one
1626 // from outside the loop, and one from inside.
1627 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1628 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001629
Chris Lattner53e677a2004-04-02 20:23:17 +00001630 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman246b2562007-10-22 18:31:58 +00001631 SCEVHandle SymbolicName = SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001632 assert(Scalars.find(PN) == Scalars.end() &&
1633 "PHI node already processed?");
1634 Scalars.insert(std::make_pair(PN, SymbolicName));
1635
1636 // Using this symbolic name for the PHI, analyze the value coming around
1637 // the back-edge.
1638 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1639
1640 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1641 // has a special value for the first iteration of the loop.
1642
1643 // If the value coming around the backedge is an add with the symbolic
1644 // value we just inserted, then we found a simple induction variable!
1645 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1646 // If there is a single occurrence of the symbolic value, replace it
1647 // with a recurrence.
1648 unsigned FoundIndex = Add->getNumOperands();
1649 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1650 if (Add->getOperand(i) == SymbolicName)
1651 if (FoundIndex == e) {
1652 FoundIndex = i;
1653 break;
1654 }
1655
1656 if (FoundIndex != Add->getNumOperands()) {
1657 // Create an add with everything but the specified operand.
1658 std::vector<SCEVHandle> Ops;
1659 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1660 if (i != FoundIndex)
1661 Ops.push_back(Add->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001662 SCEVHandle Accum = SE.getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001663
1664 // This is not a valid addrec if the step amount is varying each
1665 // loop iteration, but is not itself an addrec in this loop.
1666 if (Accum->isLoopInvariant(L) ||
1667 (isa<SCEVAddRecExpr>(Accum) &&
1668 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1669 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman246b2562007-10-22 18:31:58 +00001670 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001671
1672 // Okay, for the entire analysis of this edge we assumed the PHI
1673 // to be symbolic. We now need to go back and update all of the
1674 // entries for the scalars that use the PHI (except for the PHI
1675 // itself) to use the new analyzed value instead of the "symbolic"
1676 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001677 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001678 return PHISCEV;
1679 }
1680 }
Chris Lattner97156e72006-04-26 18:34:07 +00001681 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1682 // Otherwise, this could be a loop like this:
1683 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1684 // In this case, j = {1,+,1} and BEValue is j.
1685 // Because the other in-value of i (0) fits the evolution of BEValue
1686 // i really is an addrec evolution.
1687 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1688 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1689
1690 // If StartVal = j.start - j.stride, we can use StartVal as the
1691 // initial step of the addrec evolution.
Dan Gohman246b2562007-10-22 18:31:58 +00001692 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1693 AddRec->getOperand(1))) {
Chris Lattner97156e72006-04-26 18:34:07 +00001694 SCEVHandle PHISCEV =
Dan Gohman246b2562007-10-22 18:31:58 +00001695 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00001696
1697 // Okay, for the entire analysis of this edge we assumed the PHI
1698 // to be symbolic. We now need to go back and update all of the
1699 // entries for the scalars that use the PHI (except for the PHI
1700 // itself) to use the new analyzed value instead of the "symbolic"
1701 // value.
1702 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1703 return PHISCEV;
1704 }
1705 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001706 }
1707
1708 return SymbolicName;
1709 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001710
Chris Lattner53e677a2004-04-02 20:23:17 +00001711 // If it's not a loop phi, we can't handle it yet.
Dan Gohman246b2562007-10-22 18:31:58 +00001712 return SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001713}
1714
Nick Lewycky83bb0052007-11-22 07:59:40 +00001715/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1716/// guaranteed to end in (at every loop iteration). It is, at the same time,
1717/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1718/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1719static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1720 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00001721 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00001722
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001723 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Nick Lewycky83bb0052007-11-22 07:59:40 +00001724 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1725
1726 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1727 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1728 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1729 }
1730
1731 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1732 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1733 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1734 }
1735
Chris Lattnera17f0392006-12-12 02:26:09 +00001736 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001737 // The result is the min of all operands results.
1738 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1739 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1740 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1741 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001742 }
1743
1744 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001745 // The result is the sum of all operands results.
1746 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1747 uint32_t BitWidth = M->getBitWidth();
1748 for (unsigned i = 1, e = M->getNumOperands();
1749 SumOpRes != BitWidth && i != e; ++i)
1750 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1751 BitWidth);
1752 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001753 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001754
Chris Lattnera17f0392006-12-12 02:26:09 +00001755 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001756 // The result is the min of all operands results.
1757 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1758 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1759 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1760 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001761 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001762
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001763 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1764 // The result is the min of all operands results.
1765 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1766 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1767 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1768 return MinOpRes;
1769 }
1770
Nick Lewycky3e630762008-02-20 06:48:22 +00001771 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1772 // The result is the min of all operands results.
1773 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1774 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1775 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1776 return MinOpRes;
1777 }
1778
Nick Lewycky48dd6442008-12-02 08:05:48 +00001779 // SCEVUDivExpr, SCEVSDivExpr, SCEVUnknown
Nick Lewycky83bb0052007-11-22 07:59:40 +00001780 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00001781}
Chris Lattner53e677a2004-04-02 20:23:17 +00001782
1783/// createSCEV - We know that there is no SCEV for the specified value.
1784/// Analyze the expression.
1785///
1786SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
Chris Lattner42b5e082007-11-23 08:46:22 +00001787 if (!isa<IntegerType>(V->getType()))
1788 return SE.getUnknown(V);
1789
Dan Gohman6c459a22008-06-22 19:56:46 +00001790 unsigned Opcode = Instruction::UserOp1;
1791 if (Instruction *I = dyn_cast<Instruction>(V))
1792 Opcode = I->getOpcode();
1793 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1794 Opcode = CE->getOpcode();
1795 else
1796 return SE.getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00001797
Dan Gohman6c459a22008-06-22 19:56:46 +00001798 User *U = cast<User>(V);
1799 switch (Opcode) {
1800 case Instruction::Add:
1801 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1802 getSCEV(U->getOperand(1)));
1803 case Instruction::Mul:
1804 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1805 getSCEV(U->getOperand(1)));
1806 case Instruction::UDiv:
1807 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1808 getSCEV(U->getOperand(1)));
Nick Lewycky48dd6442008-12-02 08:05:48 +00001809 case Instruction::SDiv:
1810 return SE.getSDivExpr(getSCEV(U->getOperand(0)),
1811 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00001812 case Instruction::Sub:
1813 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1814 getSCEV(U->getOperand(1)));
1815 case Instruction::Or:
1816 // If the RHS of the Or is a constant, we may have something like:
1817 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1818 // optimizations will transparently handle this case.
1819 //
1820 // In order for this transformation to be safe, the LHS must be of the
1821 // form X*(2^n) and the Or constant must be less than 2^n.
1822 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1823 SCEVHandle LHS = getSCEV(U->getOperand(0));
1824 const APInt &CIVal = CI->getValue();
1825 if (GetMinTrailingZeros(LHS) >=
1826 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1827 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001828 }
Dan Gohman6c459a22008-06-22 19:56:46 +00001829 break;
1830 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00001831 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00001832 // If the RHS of the xor is a signbit, then this is just an add.
1833 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00001834 if (CI->getValue().isSignBit())
1835 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1836 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00001837
1838 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman6c459a22008-06-22 19:56:46 +00001839 else if (CI->isAllOnesValue())
1840 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1841 }
1842 break;
1843
1844 case Instruction::Shl:
1845 // Turn shift left of a constant amount into a multiply.
1846 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1847 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1848 Constant *X = ConstantInt::get(
1849 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1850 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1851 }
1852 break;
1853
Nick Lewycky01eaf802008-07-07 06:15:49 +00001854 case Instruction::LShr:
Nick Lewycky48dd6442008-12-02 08:05:48 +00001855 // Turn logical shift right of a constant into an unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00001856 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1857 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1858 Constant *X = ConstantInt::get(
1859 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1860 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1861 }
1862 break;
1863
Dan Gohman6c459a22008-06-22 19:56:46 +00001864 case Instruction::Trunc:
1865 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1866
1867 case Instruction::ZExt:
1868 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1869
1870 case Instruction::SExt:
1871 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1872
1873 case Instruction::BitCast:
1874 // BitCasts are no-op casts so we just eliminate the cast.
1875 if (U->getType()->isInteger() &&
1876 U->getOperand(0)->getType()->isInteger())
1877 return getSCEV(U->getOperand(0));
1878 break;
1879
1880 case Instruction::PHI:
1881 return createNodeForPHI(cast<PHINode>(U));
1882
1883 case Instruction::Select:
1884 // This could be a smax or umax that was lowered earlier.
1885 // Try to recover it.
1886 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1887 Value *LHS = ICI->getOperand(0);
1888 Value *RHS = ICI->getOperand(1);
1889 switch (ICI->getPredicate()) {
1890 case ICmpInst::ICMP_SLT:
1891 case ICmpInst::ICMP_SLE:
1892 std::swap(LHS, RHS);
1893 // fall through
1894 case ICmpInst::ICMP_SGT:
1895 case ICmpInst::ICMP_SGE:
1896 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1897 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1898 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman1fbffe02008-07-30 04:36:32 +00001899 // ~smax(~x, ~y) == smin(x, y).
1900 return SE.getNotSCEV(SE.getSMaxExpr(
1901 SE.getNotSCEV(getSCEV(LHS)),
1902 SE.getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00001903 break;
1904 case ICmpInst::ICMP_ULT:
1905 case ICmpInst::ICMP_ULE:
1906 std::swap(LHS, RHS);
1907 // fall through
1908 case ICmpInst::ICMP_UGT:
1909 case ICmpInst::ICMP_UGE:
1910 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1911 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1912 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1913 // ~umax(~x, ~y) == umin(x, y)
1914 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
1915 SE.getNotSCEV(getSCEV(RHS))));
1916 break;
1917 default:
1918 break;
1919 }
1920 }
1921
1922 default: // We cannot analyze this expression.
1923 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001924 }
1925
Dan Gohman246b2562007-10-22 18:31:58 +00001926 return SE.getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001927}
1928
1929
1930
1931//===----------------------------------------------------------------------===//
1932// Iteration Count Computation Code
1933//
1934
1935/// getIterationCount - If the specified loop has a predictable iteration
1936/// count, return it. Note that it is not valid to call this method on a
1937/// loop without a loop-invariant iteration count.
1938SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1939 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1940 if (I == IterationCounts.end()) {
1941 SCEVHandle ItCount = ComputeIterationCount(L);
1942 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1943 if (ItCount != UnknownValue) {
1944 assert(ItCount->isLoopInvariant(L) &&
1945 "Computed trip count isn't loop invariant for loop!");
1946 ++NumTripCountsComputed;
1947 } else if (isa<PHINode>(L->getHeader()->begin())) {
1948 // Only count loops that have phi nodes as not being computable.
1949 ++NumTripCountsNotComputed;
1950 }
1951 }
1952 return I->second;
1953}
1954
1955/// ComputeIterationCount - Compute the number of times the specified loop
1956/// will iterate.
1957SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1958 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patelb7211a22007-08-21 00:31:24 +00001959 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001960 L->getExitBlocks(ExitBlocks);
1961 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001962
1963 // Okay, there is one exit block. Try to find the condition that causes the
1964 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001965 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001966
1967 BasicBlock *ExitingBlock = 0;
1968 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1969 PI != E; ++PI)
1970 if (L->contains(*PI)) {
1971 if (ExitingBlock == 0)
1972 ExitingBlock = *PI;
1973 else
1974 return UnknownValue; // More than one block exiting!
1975 }
1976 assert(ExitingBlock && "No exits from loop, something is broken!");
1977
1978 // Okay, we've computed the exiting block. See what condition causes us to
1979 // exit.
1980 //
1981 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00001982 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1983 if (ExitBr == 0) return UnknownValue;
1984 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00001985
1986 // At this point, we know we have a conditional branch that determines whether
1987 // the loop is exited. However, we don't know if the branch is executed each
1988 // time through the loop. If not, then the execution count of the branch will
1989 // not be equal to the trip count of the loop.
1990 //
1991 // Currently we check for this by checking to see if the Exit branch goes to
1992 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00001993 // times as the loop. We also handle the case where the exit block *is* the
1994 // loop header. This is common for un-rotated loops. More extensive analysis
1995 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001996 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00001997 ExitBr->getSuccessor(1) != L->getHeader() &&
1998 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00001999 return UnknownValue;
2000
Reid Spencere4d87aa2006-12-23 06:05:41 +00002001 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2002
Nick Lewycky3b711652008-02-21 08:34:02 +00002003 // If it's not an integer comparison then compute it the hard way.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002004 // Note that ICmpInst deals with pointer comparisons too so we must check
2005 // the type of the operand.
Chris Lattner8b0e3602007-01-07 02:24:26 +00002006 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Chris Lattner7980fb92004-04-17 18:36:24 +00002007 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
2008 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00002009
Reid Spencere4d87aa2006-12-23 06:05:41 +00002010 // If the condition was exit on true, convert the condition to exit on false
2011 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00002012 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00002013 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002014 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00002015 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002016
2017 // Handle common loops like: for (X = "string"; *X; ++X)
2018 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2019 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2020 SCEVHandle ItCnt =
2021 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
2022 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2023 }
2024
Chris Lattner53e677a2004-04-02 20:23:17 +00002025 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2026 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2027
2028 // Try to evaluate any dependencies out of the loop.
2029 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2030 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2031 Tmp = getSCEVAtScope(RHS, L);
2032 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2033
Reid Spencere4d87aa2006-12-23 06:05:41 +00002034 // At this point, we would like to compute how many iterations of the
2035 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00002036 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2037 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00002038 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002039 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00002040 }
2041
2042 // FIXME: think about handling pointer comparisons! i.e.:
2043 // while (P != P+100) ++P;
2044
2045 // If we have a comparison of a chrec against a constant, try to use value
2046 // ranges to answer this query.
2047 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2048 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2049 if (AddRec->getLoop() == L) {
2050 // Form the comparison range using the constant of the correct type so
2051 // that the ConstantRange class knows to do a signed or unsigned
2052 // comparison.
2053 ConstantInt *CompVal = RHSC->getValue();
2054 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00002055 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00002056 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00002057 if (CompVal) {
2058 // Form the constant range.
Reid Spencerc6aedf72007-02-28 22:03:51 +00002059 ConstantRange CompRange(
2060 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002061
Dan Gohman246b2562007-10-22 18:31:58 +00002062 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002063 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2064 }
2065 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002066
Chris Lattner53e677a2004-04-02 20:23:17 +00002067 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002068 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00002069 // Convert to: while (X-Y != 0)
Dan Gohman246b2562007-10-22 18:31:58 +00002070 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002071 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002072 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002073 }
2074 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00002075 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman246b2562007-10-22 18:31:58 +00002076 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002077 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002078 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002079 }
2080 case ICmpInst::ICMP_SLT: {
Nick Lewyckydd643f22008-11-18 15:10:54 +00002081 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002082 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002083 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002084 }
2085 case ICmpInst::ICMP_SGT: {
Eli Friedman068acc32008-07-30 00:04:08 +00002086 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewyckydd643f22008-11-18 15:10:54 +00002087 SE.getNotSCEV(RHS), L, true, false);
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002088 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2089 break;
2090 }
2091 case ICmpInst::ICMP_ULT: {
Nick Lewyckydd643f22008-11-18 15:10:54 +00002092 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false, false);
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002093 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2094 break;
2095 }
2096 case ICmpInst::ICMP_UGT: {
Dale Johannesena0c8fc62008-04-20 16:58:57 +00002097 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewyckydd643f22008-11-18 15:10:54 +00002098 SE.getNotSCEV(RHS), L, false, false);
2099 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2100 break;
2101 }
2102 case ICmpInst::ICMP_SLE: {
2103 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true, true);
2104 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2105 break;
2106 }
2107 case ICmpInst::ICMP_SGE: {
2108 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2109 SE.getNotSCEV(RHS), L, true, true);
2110 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2111 break;
2112 }
2113 case ICmpInst::ICMP_ULE: {
2114 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false, true);
2115 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2116 break;
2117 }
2118 case ICmpInst::ICMP_UGE: {
2119 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2120 SE.getNotSCEV(RHS), L, false, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002121 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002122 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002123 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002124 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002125#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002126 cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002127 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendlinge8156192006-12-07 01:30:32 +00002128 cerr << "[unsigned] ";
2129 cerr << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00002130 << Instruction::getOpcodeName(Instruction::ICmp)
2131 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002132#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00002133 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002134 }
Chris Lattner7980fb92004-04-17 18:36:24 +00002135 return ComputeIterationCountExhaustively(L, ExitCond,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002136 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00002137}
2138
Chris Lattner673e02b2004-10-12 01:49:27 +00002139static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00002140EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2141 ScalarEvolution &SE) {
2142 SCEVHandle InVal = SE.getConstant(C);
2143 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002144 assert(isa<SCEVConstant>(Val) &&
2145 "Evaluation of SCEV at constant didn't fold correctly?");
2146 return cast<SCEVConstant>(Val)->getValue();
2147}
2148
2149/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2150/// and a GEP expression (missing the pointer index) indexing into it, return
2151/// the addressed element of the initializer or null if the index expression is
2152/// invalid.
2153static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002154GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00002155 const std::vector<ConstantInt*> &Indices) {
2156 Constant *Init = GV->getInitializer();
2157 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002158 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00002159 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2160 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2161 Init = cast<Constant>(CS->getOperand(Idx));
2162 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2163 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2164 Init = cast<Constant>(CA->getOperand(Idx));
2165 } else if (isa<ConstantAggregateZero>(Init)) {
2166 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2167 assert(Idx < STy->getNumElements() && "Bad struct index!");
2168 Init = Constant::getNullValue(STy->getElementType(Idx));
2169 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2170 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2171 Init = Constant::getNullValue(ATy->getElementType());
2172 } else {
2173 assert(0 && "Unknown constant aggregate type!");
2174 }
2175 return 0;
2176 } else {
2177 return 0; // Unknown initializer type
2178 }
2179 }
2180 return Init;
2181}
2182
2183/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky08de6132008-05-06 04:03:18 +00002184/// 'icmp op load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00002185SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002186ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002187 const Loop *L,
2188 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002189 if (LI->isVolatile()) return UnknownValue;
2190
2191 // Check to see if the loaded pointer is a getelementptr of a global.
2192 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2193 if (!GEP) return UnknownValue;
2194
2195 // Make sure that it is really a constant global we are gepping, with an
2196 // initializer, and make sure the first IDX is really 0.
2197 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2198 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2199 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2200 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2201 return UnknownValue;
2202
2203 // Okay, we allow one non-constant index into the GEP instruction.
2204 Value *VarIdx = 0;
2205 std::vector<ConstantInt*> Indexes;
2206 unsigned VarIdxNum = 0;
2207 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2208 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2209 Indexes.push_back(CI);
2210 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2211 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2212 VarIdx = GEP->getOperand(i);
2213 VarIdxNum = i-2;
2214 Indexes.push_back(0);
2215 }
2216
2217 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2218 // Check to see if X is a loop variant variable value now.
2219 SCEVHandle Idx = getSCEV(VarIdx);
2220 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2221 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2222
2223 // We can only recognize very limited forms of loop index expressions, in
2224 // particular, only affine AddRec's like {C1,+,C2}.
2225 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2226 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2227 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2228 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2229 return UnknownValue;
2230
2231 unsigned MaxSteps = MaxBruteForceIterations;
2232 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002233 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00002234 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohman246b2562007-10-22 18:31:58 +00002235 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002236
2237 // Form the GEP offset.
2238 Indexes[VarIdxNum] = Val;
2239
2240 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2241 if (Result == 0) break; // Cannot compute!
2242
2243 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002244 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002245 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00002246 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002247#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002248 cerr << "\n***\n*** Computed loop count " << *ItCst
2249 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2250 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00002251#endif
2252 ++NumArrayLenItCounts;
Dan Gohman246b2562007-10-22 18:31:58 +00002253 return SE.getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00002254 }
2255 }
2256 return UnknownValue;
2257}
2258
2259
Chris Lattner3221ad02004-04-17 22:58:41 +00002260/// CanConstantFold - Return true if we can constant fold an instruction of the
2261/// specified type, assuming that all operands were constants.
2262static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00002263 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00002264 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2265 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002266
Chris Lattner3221ad02004-04-17 22:58:41 +00002267 if (const CallInst *CI = dyn_cast<CallInst>(I))
2268 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00002269 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00002270 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00002271}
2272
Chris Lattner3221ad02004-04-17 22:58:41 +00002273/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2274/// in the loop that V is derived from. We allow arbitrary operations along the
2275/// way, but the operands of an operation must either be constants or a value
2276/// derived from a constant PHI. If this expression does not fit with these
2277/// constraints, return null.
2278static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2279 // If this is not an instruction, or if this is an instruction outside of the
2280 // loop, it can't be derived from a loop PHI.
2281 Instruction *I = dyn_cast<Instruction>(V);
2282 if (I == 0 || !L->contains(I->getParent())) return 0;
2283
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002284 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002285 if (L->getHeader() == I->getParent())
2286 return PN;
2287 else
2288 // We don't currently keep track of the control flow needed to evaluate
2289 // PHIs, so we cannot handle PHIs inside of loops.
2290 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002291 }
Chris Lattner3221ad02004-04-17 22:58:41 +00002292
2293 // If we won't be able to constant fold this expression even if the operands
2294 // are constants, return early.
2295 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002296
Chris Lattner3221ad02004-04-17 22:58:41 +00002297 // Otherwise, we can evaluate this instruction if all of its operands are
2298 // constant or derived from a PHI node themselves.
2299 PHINode *PHI = 0;
2300 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2301 if (!(isa<Constant>(I->getOperand(Op)) ||
2302 isa<GlobalValue>(I->getOperand(Op)))) {
2303 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2304 if (P == 0) return 0; // Not evolving from PHI
2305 if (PHI == 0)
2306 PHI = P;
2307 else if (PHI != P)
2308 return 0; // Evolving from multiple different PHIs.
2309 }
2310
2311 // This is a expression evolving from a constant PHI!
2312 return PHI;
2313}
2314
2315/// EvaluateExpression - Given an expression that passes the
2316/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2317/// in the loop has the value PHIVal. If we can't fold this expression for some
2318/// reason, return null.
2319static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2320 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00002321 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00002322 Instruction *I = cast<Instruction>(V);
2323
2324 std::vector<Constant*> Operands;
2325 Operands.resize(I->getNumOperands());
2326
2327 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2328 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2329 if (Operands[i] == 0) return 0;
2330 }
2331
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002332 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2333 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2334 &Operands[0], Operands.size());
2335 else
2336 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2337 &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00002338}
2339
2340/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2341/// in the header of its containing loop, we know the loop executes a
2342/// constant number of times, and the PHI node is just a recurrence
2343/// involving constants, fold it.
2344Constant *ScalarEvolutionsImpl::
Reid Spencere8019bb2007-03-01 07:25:48 +00002345getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00002346 std::map<PHINode*, Constant*>::iterator I =
2347 ConstantEvolutionLoopExitValue.find(PN);
2348 if (I != ConstantEvolutionLoopExitValue.end())
2349 return I->second;
2350
Reid Spencere8019bb2007-03-01 07:25:48 +00002351 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00002352 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2353
2354 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2355
2356 // Since the loop is canonicalized, the PHI node must have two entries. One
2357 // entry must be a constant (coming in from outside of the loop), and the
2358 // second must be derived from the same PHI.
2359 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2360 Constant *StartCST =
2361 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2362 if (StartCST == 0)
2363 return RetVal = 0; // Must be a constant.
2364
2365 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2366 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2367 if (PN2 != PN)
2368 return RetVal = 0; // Not derived from same PHI.
2369
2370 // Execute the loop symbolically to determine the exit value.
Reid Spencere8019bb2007-03-01 07:25:48 +00002371 if (Its.getActiveBits() >= 32)
2372 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00002373
Reid Spencere8019bb2007-03-01 07:25:48 +00002374 unsigned NumIterations = Its.getZExtValue(); // must be in range
2375 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00002376 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2377 if (IterationNum == NumIterations)
2378 return RetVal = PHIVal; // Got exit value!
2379
2380 // Compute the value of the PHI node for the next iteration.
2381 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2382 if (NextPHI == PHIVal)
2383 return RetVal = NextPHI; // Stopped evolving!
2384 if (NextPHI == 0)
2385 return 0; // Couldn't evaluate!
2386 PHIVal = NextPHI;
2387 }
2388}
2389
Chris Lattner7980fb92004-04-17 18:36:24 +00002390/// ComputeIterationCountExhaustively - If the trip is known to execute a
2391/// constant number of times (the condition evolves only from constants),
2392/// try to evaluate a few iterations of the loop until we get the exit
2393/// condition gets a value of ExitWhen (true or false). If we cannot
2394/// evaluate the trip count of the loop, return UnknownValue.
2395SCEVHandle ScalarEvolutionsImpl::
2396ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2397 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2398 if (PN == 0) return UnknownValue;
2399
2400 // Since the loop is canonicalized, the PHI node must have two entries. One
2401 // entry must be a constant (coming in from outside of the loop), and the
2402 // second must be derived from the same PHI.
2403 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2404 Constant *StartCST =
2405 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2406 if (StartCST == 0) return UnknownValue; // Must be a constant.
2407
2408 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2409 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2410 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2411
2412 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2413 // the loop symbolically to determine when the condition gets a value of
2414 // "ExitWhen".
2415 unsigned IterationNum = 0;
2416 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2417 for (Constant *PHIVal = StartCST;
2418 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002419 ConstantInt *CondVal =
2420 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00002421
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002422 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00002423 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002424
Reid Spencere8019bb2007-03-01 07:25:48 +00002425 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002426 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00002427 ++NumBruteForceTripCountsComputed;
Dan Gohman246b2562007-10-22 18:31:58 +00002428 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00002429 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002430
Chris Lattner3221ad02004-04-17 22:58:41 +00002431 // Compute the value of the PHI node for the next iteration.
2432 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2433 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00002434 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00002435 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00002436 }
2437
2438 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00002439 return UnknownValue;
2440}
2441
2442/// getSCEVAtScope - Compute the value of the specified expression within the
2443/// indicated loop (which may be null to indicate in no loop). If the
2444/// expression cannot be evaluated, return UnknownValue.
2445SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2446 // FIXME: this should be turned into a virtual method on SCEV!
2447
Chris Lattner3221ad02004-04-17 22:58:41 +00002448 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002449
Nick Lewycky3e630762008-02-20 06:48:22 +00002450 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00002451 // exit value from the loop without using SCEVs.
2452 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2453 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2454 const Loop *LI = this->LI[I->getParent()];
2455 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2456 if (PHINode *PN = dyn_cast<PHINode>(I))
2457 if (PN->getParent() == LI->getHeader()) {
2458 // Okay, there is no closed form solution for the PHI node. Check
2459 // to see if the loop that contains it has a known iteration count.
2460 // If so, we may be able to force computation of the exit value.
2461 SCEVHandle IterationCount = getIterationCount(LI);
2462 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2463 // Okay, we know how many times the containing loop executes. If
2464 // this is a constant evolving PHI node, get the final value at
2465 // the specified iteration number.
2466 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencere8019bb2007-03-01 07:25:48 +00002467 ICC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00002468 LI);
Dan Gohman246b2562007-10-22 18:31:58 +00002469 if (RV) return SE.getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00002470 }
2471 }
2472
Reid Spencer09906f32006-12-04 21:33:23 +00002473 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00002474 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00002475 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00002476 // result. This is particularly useful for computing loop exit values.
2477 if (CanConstantFold(I)) {
2478 std::vector<Constant*> Operands;
2479 Operands.reserve(I->getNumOperands());
2480 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2481 Value *Op = I->getOperand(i);
2482 if (Constant *C = dyn_cast<Constant>(Op)) {
2483 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002484 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00002485 // If any of the operands is non-constant and if they are
2486 // non-integer, don't even try to analyze them with scev techniques.
2487 if (!isa<IntegerType>(Op->getType()))
2488 return V;
2489
Chris Lattner3221ad02004-04-17 22:58:41 +00002490 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2491 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
Reid Spencerd977d862006-12-12 23:36:14 +00002492 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2493 Op->getType(),
2494 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002495 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2496 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
Reid Spencerd977d862006-12-12 23:36:14 +00002497 Operands.push_back(ConstantExpr::getIntegerCast(C,
2498 Op->getType(),
2499 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002500 else
2501 return V;
2502 } else {
2503 return V;
2504 }
2505 }
2506 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002507
2508 Constant *C;
2509 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2510 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2511 &Operands[0], Operands.size());
2512 else
2513 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2514 &Operands[0], Operands.size());
Dan Gohman246b2562007-10-22 18:31:58 +00002515 return SE.getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002516 }
2517 }
2518
2519 // This is some other type of SCEVUnknown, just return it.
2520 return V;
2521 }
2522
Chris Lattner53e677a2004-04-02 20:23:17 +00002523 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2524 // Avoid performing the look-up in the common case where the specified
2525 // expression has no loop-variant portions.
2526 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2527 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2528 if (OpAtScope != Comm->getOperand(i)) {
2529 if (OpAtScope == UnknownValue) return UnknownValue;
2530 // Okay, at least one of these operands is loop variant but might be
2531 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002532 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002533 NewOps.push_back(OpAtScope);
2534
2535 for (++i; i != e; ++i) {
2536 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2537 if (OpAtScope == UnknownValue) return UnknownValue;
2538 NewOps.push_back(OpAtScope);
2539 }
2540 if (isa<SCEVAddExpr>(Comm))
Dan Gohman246b2562007-10-22 18:31:58 +00002541 return SE.getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002542 if (isa<SCEVMulExpr>(Comm))
2543 return SE.getMulExpr(NewOps);
2544 if (isa<SCEVSMaxExpr>(Comm))
2545 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00002546 if (isa<SCEVUMaxExpr>(Comm))
2547 return SE.getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002548 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002549 }
2550 }
2551 // If we got here, all operands are loop invariant.
2552 return Comm;
2553 }
2554
Nick Lewycky48dd6442008-12-02 08:05:48 +00002555 if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(V)) {
2556 SCEVHandle LHS = getSCEVAtScope(UDiv->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002557 if (LHS == UnknownValue) return LHS;
Nick Lewycky48dd6442008-12-02 08:05:48 +00002558 SCEVHandle RHS = getSCEVAtScope(UDiv->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002559 if (RHS == UnknownValue) return RHS;
Nick Lewycky48dd6442008-12-02 08:05:48 +00002560 if (LHS == UDiv->getLHS() && RHS == UDiv->getRHS())
2561 return UDiv; // must be loop invariant
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00002562 return SE.getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002563 }
2564
Nick Lewycky48dd6442008-12-02 08:05:48 +00002565 if (SCEVSDivExpr *SDiv = dyn_cast<SCEVSDivExpr>(V)) {
2566 SCEVHandle LHS = getSCEVAtScope(SDiv->getLHS(), L);
2567 if (LHS == UnknownValue) return LHS;
2568 SCEVHandle RHS = getSCEVAtScope(SDiv->getRHS(), L);
2569 if (RHS == UnknownValue) return RHS;
2570 if (LHS == SDiv->getLHS() && RHS == SDiv->getRHS())
2571 return SDiv; // must be loop invariant
2572 return SE.getSDivExpr(LHS, RHS);
2573 }
2574
Chris Lattner53e677a2004-04-02 20:23:17 +00002575 // If this is a loop recurrence for a loop that does not contain L, then we
2576 // are dealing with the final value computed by the loop.
2577 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2578 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2579 // To evaluate this recurrence, we need to know how many times the AddRec
2580 // loop iterates. Compute this now.
2581 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2582 if (IterationCount == UnknownValue) return UnknownValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002583
Eli Friedmanb42a6262008-08-04 23:49:06 +00002584 // Then, evaluate the AddRec.
Dan Gohman246b2562007-10-22 18:31:58 +00002585 return AddRec->evaluateAtIteration(IterationCount, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002586 }
2587 return UnknownValue;
2588 }
2589
2590 //assert(0 && "Unknown SCEV type!");
2591 return UnknownValue;
2592}
2593
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002594/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2595/// following equation:
2596///
2597/// A * X = B (mod N)
2598///
2599/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2600/// A and B isn't important.
2601///
2602/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2603static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2604 ScalarEvolution &SE) {
2605 uint32_t BW = A.getBitWidth();
2606 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2607 assert(A != 0 && "A must be non-zero.");
2608
2609 // 1. D = gcd(A, N)
2610 //
2611 // The gcd of A and N may have only one prime factor: 2. The number of
2612 // trailing zeros in A is its multiplicity
2613 uint32_t Mult2 = A.countTrailingZeros();
2614 // D = 2^Mult2
2615
2616 // 2. Check if B is divisible by D.
2617 //
2618 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2619 // is not less than multiplicity of this prime factor for D.
2620 if (B.countTrailingZeros() < Mult2)
2621 return new SCEVCouldNotCompute();
2622
2623 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2624 // modulo (N / D).
2625 //
2626 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2627 // bit width during computations.
2628 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2629 APInt Mod(BW + 1, 0);
2630 Mod.set(BW - Mult2); // Mod = N / D
2631 APInt I = AD.multiplicativeInverse(Mod);
2632
2633 // 4. Compute the minimum unsigned root of the equation:
2634 // I * (B / D) mod (N / D)
2635 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2636
2637 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2638 // bits.
2639 return SE.getConstant(Result.trunc(BW));
2640}
Chris Lattner53e677a2004-04-02 20:23:17 +00002641
2642/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2643/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2644/// might be the same) or two SCEVCouldNotCompute objects.
2645///
2646static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman246b2562007-10-22 18:31:58 +00002647SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002648 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Reid Spencere8019bb2007-03-01 07:25:48 +00002649 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2650 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2651 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002652
Chris Lattner53e677a2004-04-02 20:23:17 +00002653 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00002654 if (!LC || !MC || !NC) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002655 SCEV *CNC = new SCEVCouldNotCompute();
2656 return std::make_pair(CNC, CNC);
2657 }
2658
Reid Spencere8019bb2007-03-01 07:25:48 +00002659 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00002660 const APInt &L = LC->getValue()->getValue();
2661 const APInt &M = MC->getValue()->getValue();
2662 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00002663 APInt Two(BitWidth, 2);
2664 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002665
Reid Spencere8019bb2007-03-01 07:25:48 +00002666 {
2667 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00002668 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00002669 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2670 // The B coefficient is M-N/2
2671 APInt B(M);
2672 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002673
Reid Spencere8019bb2007-03-01 07:25:48 +00002674 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00002675 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00002676
Reid Spencere8019bb2007-03-01 07:25:48 +00002677 // Compute the B^2-4ac term.
2678 APInt SqrtTerm(B);
2679 SqrtTerm *= B;
2680 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00002681
Reid Spencere8019bb2007-03-01 07:25:48 +00002682 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2683 // integer value or else APInt::sqrt() will assert.
2684 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002685
Reid Spencere8019bb2007-03-01 07:25:48 +00002686 // Compute the two solutions for the quadratic formula.
2687 // The divisions must be performed as signed divisions.
2688 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00002689 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00002690 if (TwoA.isMinValue()) {
2691 SCEV *CNC = new SCEVCouldNotCompute();
2692 return std::make_pair(CNC, CNC);
2693 }
2694
Reid Spencere8019bb2007-03-01 07:25:48 +00002695 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2696 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002697
Dan Gohman246b2562007-10-22 18:31:58 +00002698 return std::make_pair(SE.getConstant(Solution1),
2699 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00002700 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00002701}
2702
2703/// HowFarToZero - Return the number of times a backedge comparing the specified
2704/// value to zero will execute. If not computable, return UnknownValue
2705SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2706 // If the value is a constant
2707 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2708 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00002709 if (C->getValue()->isZero()) return C;
Chris Lattner53e677a2004-04-02 20:23:17 +00002710 return UnknownValue; // Otherwise it will loop infinitely.
2711 }
2712
2713 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2714 if (!AddRec || AddRec->getLoop() != L)
2715 return UnknownValue;
2716
2717 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002718 // If this is an affine expression, the execution count of this branch is
2719 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00002720 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002721 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00002722 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002723 // equivalent to:
2724 //
2725 // Step*N = -Start (mod 2^BW)
2726 //
2727 // where BW is the common bit width of Start and Step.
2728
Chris Lattner53e677a2004-04-02 20:23:17 +00002729 // Get the initial value for the loop.
2730 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002731 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002732
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002733 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002734
Chris Lattner53e677a2004-04-02 20:23:17 +00002735 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002736 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00002737
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002738 // First, handle unitary steps.
2739 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2740 return SE.getNegativeSCEV(Start); // N = -Start (as unsigned)
2741 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2742 return Start; // N = Start (as unsigned)
2743
2744 // Then, try to solve the above equation provided that Start is constant.
2745 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2746 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2747 -StartC->getValue()->getValue(),SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002748 }
Chris Lattner42a75512007-01-15 02:27:26 +00002749 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002750 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2751 // the quadratic equation to solve it.
Dan Gohman246b2562007-10-22 18:31:58 +00002752 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002753 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2754 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2755 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002756#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002757 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2758 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002759#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002760 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002761 if (ConstantInt *CB =
2762 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002763 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002764 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002765 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002766
Chris Lattner53e677a2004-04-02 20:23:17 +00002767 // We can only use this value if the chrec ends up with an exact zero
2768 // value at this index. When solving for "X*X != 5", for example, we
2769 // should not accept a root of 2.
Dan Gohman246b2562007-10-22 18:31:58 +00002770 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002771 if (Val->isZero())
2772 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00002773 }
2774 }
2775 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002776
Chris Lattner53e677a2004-04-02 20:23:17 +00002777 return UnknownValue;
2778}
2779
2780/// HowFarToNonZero - Return the number of times a backedge checking the
2781/// specified value for nonzero will execute. If not computable, return
2782/// UnknownValue
2783SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2784 // Loops that look like: while (X == 0) are very strange indeed. We don't
2785 // handle them yet except for the trivial case. This could be expanded in the
2786 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002787
Chris Lattner53e677a2004-04-02 20:23:17 +00002788 // If the value is a constant, check to see if it is known to be non-zero
2789 // already. If so, the backedge will execute zero times.
2790 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00002791 if (!C->getValue()->isNullValue())
2792 return SE.getIntegerSCEV(0, C->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002793 return UnknownValue; // Otherwise it will loop infinitely.
2794 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002795
Chris Lattner53e677a2004-04-02 20:23:17 +00002796 // We could implement others, but I really doubt anyone writes loops like
2797 // this, and if they did, they would already be constant folded.
2798 return UnknownValue;
2799}
2800
Dan Gohmanfd6edef2008-09-15 22:18:04 +00002801/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2802/// (which may not be an immediate predecessor) which has exactly one
2803/// successor from which BB is reachable, or null if no such block is
2804/// found.
2805///
2806BasicBlock *
2807ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2808 // If the block has a unique predecessor, the predecessor must have
2809 // no other successors from which BB is reachable.
2810 if (BasicBlock *Pred = BB->getSinglePredecessor())
2811 return Pred;
2812
2813 // A loop's header is defined to be a block that dominates the loop.
2814 // If the loop has a preheader, it must be a block that has exactly
2815 // one successor that can reach BB. This is slightly more strict
2816 // than necessary, but works if critical edges are split.
2817 if (Loop *L = LI.getLoopFor(BB))
2818 return L->getLoopPreheader();
2819
2820 return 0;
2821}
2822
Nick Lewycky59cff122008-07-12 07:41:32 +00002823/// executesAtLeastOnce - Test whether entry to the loop is protected by
2824/// a conditional between LHS and RHS.
2825bool ScalarEvolutionsImpl::executesAtLeastOnce(const Loop *L, bool isSigned,
Nick Lewyckydd643f22008-11-18 15:10:54 +00002826 bool trueWhenEqual,
Nick Lewycky59cff122008-07-12 07:41:32 +00002827 SCEV *LHS, SCEV *RHS) {
2828 BasicBlock *Preheader = L->getLoopPreheader();
2829 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00002830
Dan Gohman38372182008-08-12 20:17:31 +00002831 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohmanfd6edef2008-09-15 22:18:04 +00002832 // there are predecessors that can be found that have unique successors
2833 // leading to the original header.
2834 for (; Preheader;
2835 PreheaderDest = Preheader,
2836 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohman38372182008-08-12 20:17:31 +00002837
2838 BranchInst *LoopEntryPredicate =
Nick Lewycky59cff122008-07-12 07:41:32 +00002839 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00002840 if (!LoopEntryPredicate ||
2841 LoopEntryPredicate->isUnconditional())
2842 continue;
2843
2844 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2845 if (!ICI) continue;
2846
2847 // Now that we found a conditional branch that dominates the loop, check to
2848 // see if it is the comparison we are looking for.
2849 Value *PreCondLHS = ICI->getOperand(0);
2850 Value *PreCondRHS = ICI->getOperand(1);
2851 ICmpInst::Predicate Cond;
2852 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2853 Cond = ICI->getPredicate();
2854 else
2855 Cond = ICI->getInversePredicate();
2856
2857 switch (Cond) {
2858 case ICmpInst::ICMP_UGT:
Nick Lewyckydd643f22008-11-18 15:10:54 +00002859 if (isSigned || trueWhenEqual) continue;
Dan Gohman38372182008-08-12 20:17:31 +00002860 std::swap(PreCondLHS, PreCondRHS);
2861 Cond = ICmpInst::ICMP_ULT;
2862 break;
2863 case ICmpInst::ICMP_SGT:
Nick Lewyckydd643f22008-11-18 15:10:54 +00002864 if (!isSigned || trueWhenEqual) continue;
Dan Gohman38372182008-08-12 20:17:31 +00002865 std::swap(PreCondLHS, PreCondRHS);
2866 Cond = ICmpInst::ICMP_SLT;
2867 break;
2868 case ICmpInst::ICMP_ULT:
Nick Lewyckydd643f22008-11-18 15:10:54 +00002869 if (isSigned || trueWhenEqual) continue;
Dan Gohman38372182008-08-12 20:17:31 +00002870 break;
2871 case ICmpInst::ICMP_SLT:
Nick Lewyckydd643f22008-11-18 15:10:54 +00002872 if (!isSigned || trueWhenEqual) continue;
2873 break;
2874 case ICmpInst::ICMP_UGE:
2875 if (isSigned || !trueWhenEqual) continue;
2876 std::swap(PreCondLHS, PreCondRHS);
2877 Cond = ICmpInst::ICMP_ULE;
2878 break;
2879 case ICmpInst::ICMP_SGE:
2880 if (!isSigned || !trueWhenEqual) continue;
2881 std::swap(PreCondLHS, PreCondRHS);
2882 Cond = ICmpInst::ICMP_SLE;
2883 break;
2884 case ICmpInst::ICMP_ULE:
2885 if (isSigned || !trueWhenEqual) continue;
2886 break;
2887 case ICmpInst::ICMP_SLE:
2888 if (!isSigned || !trueWhenEqual) continue;
Dan Gohman38372182008-08-12 20:17:31 +00002889 break;
2890 default:
2891 continue;
2892 }
2893
2894 if (!PreCondLHS->getType()->isInteger()) continue;
2895
2896 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
2897 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
2898 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
2899 (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
2900 RHS == SE.getNotSCEV(PreCondLHSSCEV)))
2901 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00002902 }
2903
Dan Gohman38372182008-08-12 20:17:31 +00002904 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00002905}
2906
Nick Lewyckydd643f22008-11-18 15:10:54 +00002907/// potentialInfiniteLoop - Test whether the loop might jump over the exit value
2908/// due to wrapping around 2^n.
2909bool ScalarEvolutionsImpl::potentialInfiniteLoop(SCEV *Stride, SCEV *RHS,
2910 bool isSigned, bool trueWhenEqual) {
2911 // Return true when the distance from RHS to maxint > Stride.
2912
2913 if (!isa<SCEVConstant>(Stride))
2914 return true;
2915 SCEVConstant *SC = cast<SCEVConstant>(Stride);
2916
2917 if (SC->getValue()->isZero())
2918 return true;
2919 if (!trueWhenEqual && SC->getValue()->isOne())
2920 return false;
2921
2922 if (!isa<SCEVConstant>(RHS))
2923 return true;
2924 SCEVConstant *R = cast<SCEVConstant>(RHS);
2925
2926 if (isSigned)
2927 return true; // XXX: because we don't have an sdiv scev.
2928
2929 // If negative, it wraps around every iteration, but we don't care about that.
2930 APInt S = SC->getValue()->getValue().abs();
2931
2932 APInt Dist = APInt::getMaxValue(R->getValue()->getBitWidth()) -
2933 R->getValue()->getValue();
2934
2935 if (trueWhenEqual)
2936 return !S.ult(Dist);
2937 else
2938 return !S.ule(Dist);
2939}
2940
Chris Lattnerdb25de42005-08-15 23:33:51 +00002941/// HowManyLessThans - Return the number of times a backedge containing the
2942/// specified less-than comparison will execute. If not computable, return
2943/// UnknownValue.
2944SCEVHandle ScalarEvolutionsImpl::
Nick Lewyckydd643f22008-11-18 15:10:54 +00002945HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
2946 bool isSigned, bool trueWhenEqual) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00002947 // Only handle: "ADDREC < LoopInvariant".
2948 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2949
2950 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2951 if (!AddRec || AddRec->getLoop() != L)
2952 return UnknownValue;
2953
2954 if (AddRec->isAffine()) {
Nick Lewyckydd643f22008-11-18 15:10:54 +00002955 SCEVHandle Stride = AddRec->getOperand(1);
2956 if (potentialInfiniteLoop(Stride, RHS, isSigned, trueWhenEqual))
Chris Lattnerdb25de42005-08-15 23:33:51 +00002957 return UnknownValue;
2958
Nick Lewyckydd643f22008-11-18 15:10:54 +00002959 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
2960 // m. So, we count the number of iterations in which {n,+,s} < m is true.
2961 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00002962 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00002963
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002964 // First, we get the value of the LHS in the first iteration: n
2965 SCEVHandle Start = AddRec->getOperand(0);
2966
Nick Lewyckydd643f22008-11-18 15:10:54 +00002967 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002968
Nick Lewyckydd643f22008-11-18 15:10:54 +00002969 // Assuming that the loop will run at least once, we know that it will
2970 // run (m-n)/s times.
2971 SCEVHandle End = RHS;
2972
2973 if (!executesAtLeastOnce(L, isSigned, trueWhenEqual,
2974 SE.getMinusSCEV(Start, One), RHS)) {
2975 // If not, we get the value of the LHS in the first iteration in which
2976 // the above condition doesn't hold. This equals to max(m,n).
2977 End = isSigned ? SE.getSMaxExpr(RHS, Start)
2978 : SE.getUMaxExpr(RHS, Start);
Nick Lewycky59cff122008-07-12 07:41:32 +00002979 }
Nick Lewyckydd643f22008-11-18 15:10:54 +00002980
2981 // If the expression is less-than-or-equal to, we need to extend the
2982 // loop by one iteration.
2983 //
2984 // The loop won't actually run (m-n)/s times because the loop iterations
2985 // won't divide evenly. For example, if you have {2,+,5} u< 10 the
2986 // division would equal one, but the loop runs twice putting the
2987 // induction variable at 12.
2988
2989 if (!trueWhenEqual)
2990 // (Stride - 1) is correct only because we know it's unsigned.
2991 // What we really want is to decrease the magnitude of Stride by one.
2992 Start = SE.getMinusSCEV(Start, SE.getMinusSCEV(Stride, One));
2993 else
2994 Start = SE.getMinusSCEV(Start, Stride);
2995
2996 // Finally, we subtract these two values to get the number of times the
2997 // backedge is executed: max(m,n)-n.
2998 return SE.getUDivExpr(SE.getMinusSCEV(End, Start), Stride);
Chris Lattnerdb25de42005-08-15 23:33:51 +00002999 }
3000
3001 return UnknownValue;
3002}
3003
Chris Lattner53e677a2004-04-02 20:23:17 +00003004/// getNumIterationsInRange - Return the number of iterations of this loop that
3005/// produce values in the specified constant range. Another way of looking at
3006/// this is that it returns the first iteration number where the value is not in
3007/// the condition, thus computing the exit count. If the iteration count can't
3008/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman246b2562007-10-22 18:31:58 +00003009SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3010 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00003011 if (Range.isFullSet()) // Infinite loop.
3012 return new SCEVCouldNotCompute();
3013
3014 // If the start is a non-zero constant, shift the range to simplify things.
3015 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00003016 if (!SC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003017 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00003018 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3019 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003020 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
3021 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00003022 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00003023 // This is strange and shouldn't happen.
3024 return new SCEVCouldNotCompute();
3025 }
3026
3027 // The only time we can solve this is when we have all constant indices.
3028 // Otherwise, we cannot determine the overflow conditions.
3029 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3030 if (!isa<SCEVConstant>(getOperand(i)))
3031 return new SCEVCouldNotCompute();
3032
3033
3034 // Okay at this point we know that all elements of the chrec are constants and
3035 // that the start element is zero.
3036
3037 // First check to see if the range contains zero. If not, the first
3038 // iteration exits.
Reid Spencera6e8a952007-03-01 07:54:15 +00003039 if (!Range.contains(APInt(getBitWidth(),0)))
Dan Gohman246b2562007-10-22 18:31:58 +00003040 return SE.getConstant(ConstantInt::get(getType(),0));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003041
Chris Lattner53e677a2004-04-02 20:23:17 +00003042 if (isAffine()) {
3043 // If this is an affine expression then we have this situation:
3044 // Solve {0,+,A} in Range === Ax in Range
3045
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003046 // We know that zero is in the range. If A is positive then we know that
3047 // the upper value of the range must be the first possible exit value.
3048 // If A is negative then the lower of the range is the last possible loop
3049 // value. Also note that we already checked for a full range.
Reid Spencer581b0d42007-02-28 19:57:34 +00003050 APInt One(getBitWidth(),1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003051 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3052 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00003053
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003054 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00003055 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00003056 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00003057
3058 // Evaluate at the exit value. If we really did fall out of the valid
3059 // range, then we computed our trip count, otherwise wrap around or other
3060 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00003061 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003062 if (Range.contains(Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00003063 return new SCEVCouldNotCompute(); // Something strange happened
3064
3065 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00003066 assert(Range.contains(
3067 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003068 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00003069 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00003070 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00003071 } else if (isQuadratic()) {
3072 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3073 // quadratic equation to solve it. To do this, we must frame our problem in
3074 // terms of figuring out when zero is crossed, instead of when
3075 // Range.getUpper() is crossed.
3076 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00003077 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3078 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003079
3080 // Next, solve the constructed addrec
3081 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00003082 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00003083 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3084 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3085 if (R1) {
3086 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003087 if (ConstantInt *CB =
3088 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003089 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00003090 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00003091 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003092
Chris Lattner53e677a2004-04-02 20:23:17 +00003093 // Make sure the root is not off by one. The returned iteration should
3094 // not be in the range, but the previous one should be. When solving
3095 // for "X*X < 5", for example, we should not return a root of 2.
3096 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003097 R1->getValue(),
3098 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003099 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003100 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00003101 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003102
Dan Gohman246b2562007-10-22 18:31:58 +00003103 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003104 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00003105 return SE.getConstant(NextVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00003106 return new SCEVCouldNotCompute(); // Something strange happened
3107 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003108
Chris Lattner53e677a2004-04-02 20:23:17 +00003109 // If R1 was not in the range, then it is a good return value. Make
3110 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00003111 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00003112 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003113 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00003114 return R1;
3115 return new SCEVCouldNotCompute(); // Something strange happened
3116 }
3117 }
3118 }
3119
Chris Lattner53e677a2004-04-02 20:23:17 +00003120 return new SCEVCouldNotCompute();
3121}
3122
3123
3124
3125//===----------------------------------------------------------------------===//
3126// ScalarEvolution Class Implementation
3127//===----------------------------------------------------------------------===//
3128
3129bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohman246b2562007-10-22 18:31:58 +00003130 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
Chris Lattner53e677a2004-04-02 20:23:17 +00003131 return false;
3132}
3133
3134void ScalarEvolution::releaseMemory() {
3135 delete (ScalarEvolutionsImpl*)Impl;
3136 Impl = 0;
3137}
3138
3139void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3140 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00003141 AU.addRequiredTransitive<LoopInfo>();
3142}
3143
3144SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
3145 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
3146}
3147
Chris Lattnera0740fb2005-08-09 23:36:33 +00003148/// hasSCEV - Return true if the SCEV for this value has already been
3149/// computed.
3150bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00003151 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00003152}
3153
3154
3155/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
3156/// the specified value.
3157void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
3158 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
3159}
3160
3161
Chris Lattner53e677a2004-04-02 20:23:17 +00003162SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
3163 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
3164}
3165
3166bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
3167 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
3168}
3169
3170SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3171 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3172}
3173
Dan Gohman5cec4db2007-06-19 14:28:31 +00003174void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3175 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003176}
3177
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003178static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00003179 const Loop *L) {
3180 // Print all inner loops first
3181 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3182 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003183
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003184 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003185
Devang Patelb7211a22007-08-21 00:31:24 +00003186 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003187 L->getExitBlocks(ExitBlocks);
3188 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003189 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003190
3191 if (SE->hasLoopInvariantIterationCount(L)) {
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003192 OS << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003193 } else {
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003194 OS << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003195 }
3196
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003197 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00003198}
3199
Reid Spencerce9653c2004-12-07 04:03:45 +00003200void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00003201 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3202 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3203
3204 OS << "Classifying expressions for: " << F.getName() << "\n";
3205 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner42a75512007-01-15 02:27:26 +00003206 if (I->getType()->isInteger()) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00003207 OS << *I;
Dan Gohman8dae1382008-09-14 17:21:12 +00003208 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00003209 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00003210 SV->print(OS);
3211 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003212
Chris Lattner6ffe5512004-04-27 15:13:33 +00003213 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003214 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00003215 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003216 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3217 OS << "<<Unknown>>";
3218 } else {
3219 OS << *ExitValue;
3220 }
3221 }
3222
3223
3224 OS << "\n";
3225 }
3226
3227 OS << "Determining loop execution counts for: " << F.getName() << "\n";
3228 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3229 PrintLoopInfo(OS, this, *I);
3230}