blob: b1c3a1772737d35662a6da38b4d3c541db3542ed [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
17// can handle. These classes are reference counted, managed by the SCEVHandle
18// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000031//
Chris Lattner53e677a2004-04-02 20:23:17 +000032// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
Chris Lattner53e677a2004-04-02 20:23:17 +000036// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
Chris Lattner3b27d682006-12-19 22:30:33 +000062#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000063#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000064#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000066#include "llvm/GlobalVariable.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
John Criswella1156432005-10-27 15:54:34 +000068#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000069#include "llvm/Analysis/LoopInfo.h"
70#include "llvm/Assembly/Writer.h"
71#include "llvm/Transforms/Scalar.h"
72#include "llvm/Support/CFG.h"
Chris Lattner95255282006-06-28 23:17:24 +000073#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000074#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000075#include "llvm/Support/ConstantRange.h"
76#include "llvm/Support/InstIterator.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000077#include "llvm/Support/ManagedStatic.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000078#include "llvm/Support/MathExtras.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000079#include "llvm/Support/Streams.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000080#include "llvm/ADT/Statistic.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000081#include <ostream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000082#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000083#include <cmath>
Chris Lattner53e677a2004-04-02 20:23:17 +000084using namespace llvm;
85
Chris Lattner3b27d682006-12-19 22:30:33 +000086STATISTIC(NumBruteForceEvaluations,
87 "Number of brute force evaluations needed to "
88 "calculate high-order polynomial exit values");
89STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
97
98cl::opt<unsigned>
99MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
101 "symbolically execute a constant derived loop"),
102 cl::init(100));
103
Chris Lattner53e677a2004-04-02 20:23:17 +0000104namespace {
Chris Lattner5d8925c2006-08-27 22:30:17 +0000105 RegisterPass<ScalarEvolution>
Chris Lattner45a1cf82004-04-19 03:42:32 +0000106 R("scalar-evolution", "Scalar Evolution Analysis");
Chris Lattner53e677a2004-04-02 20:23:17 +0000107}
Devang Patel19974732007-05-03 01:11:54 +0000108char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000109
110//===----------------------------------------------------------------------===//
111// SCEV class definitions
112//===----------------------------------------------------------------------===//
113
114//===----------------------------------------------------------------------===//
115// Implementation of the SCEV class.
116//
Chris Lattner53e677a2004-04-02 20:23:17 +0000117SCEV::~SCEV() {}
118void SCEV::dump() const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000119 print(cerr);
Chris Lattner53e677a2004-04-02 20:23:17 +0000120}
121
122/// getValueRange - Return the tightest constant bounds that this value is
123/// known to have. This method is only valid on integer SCEV objects.
124ConstantRange SCEV::getValueRange() const {
125 const Type *Ty = getType();
Chris Lattner42a75512007-01-15 02:27:26 +0000126 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000127 // Default to a full range if no better information is available.
Reid Spencerc6aedf72007-02-28 22:03:51 +0000128 return ConstantRange(getBitWidth());
Chris Lattner53e677a2004-04-02 20:23:17 +0000129}
130
Reid Spencer581b0d42007-02-28 19:57:34 +0000131uint32_t SCEV::getBitWidth() const {
132 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
133 return ITy->getBitWidth();
134 return 0;
135}
136
Chris Lattner53e677a2004-04-02 20:23:17 +0000137
138SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
139
140bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000142 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000143}
144
145const Type *SCEVCouldNotCompute::getType() const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000147 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000148}
149
150bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
151 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
152 return false;
153}
154
Chris Lattner4dc534c2005-02-13 04:37:18 +0000155SCEVHandle SCEVCouldNotCompute::
156replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
157 const SCEVHandle &Conc) const {
158 return this;
159}
160
Chris Lattner53e677a2004-04-02 20:23:17 +0000161void SCEVCouldNotCompute::print(std::ostream &OS) const {
162 OS << "***COULDNOTCOMPUTE***";
163}
164
165bool SCEVCouldNotCompute::classof(const SCEV *S) {
166 return S->getSCEVType() == scCouldNotCompute;
167}
168
169
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000170// SCEVConstants - Only allow the creation of one SCEVConstant for any
171// particular value. Don't use a SCEVHandle here, or else the object will
172// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000173static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000174
Chris Lattner53e677a2004-04-02 20:23:17 +0000175
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000176SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000177 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000178}
Chris Lattner53e677a2004-04-02 20:23:17 +0000179
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000180SCEVHandle SCEVConstant::get(ConstantInt *V) {
Chris Lattnerb3364092006-10-04 21:49:37 +0000181 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000182 if (R == 0) R = new SCEVConstant(V);
183 return R;
184}
Chris Lattner53e677a2004-04-02 20:23:17 +0000185
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000186ConstantRange SCEVConstant::getValueRange() const {
Reid Spencerdc5c1592007-02-28 18:57:32 +0000187 return ConstantRange(V->getValue());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000188}
Chris Lattner53e677a2004-04-02 20:23:17 +0000189
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000190const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000191
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000192void SCEVConstant::print(std::ostream &OS) const {
193 WriteAsOperand(OS, V, false);
194}
Chris Lattner53e677a2004-04-02 20:23:17 +0000195
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000196// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
197// particular input. Don't use a SCEVHandle here, or else the object will
198// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000199static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
200 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000201
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000202SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
203 : SCEV(scTruncate), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000204 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000205 "Cannot truncate non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000206 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
207 && "This is not a truncating conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000208}
Chris Lattner53e677a2004-04-02 20:23:17 +0000209
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000210SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000211 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000212}
Chris Lattner53e677a2004-04-02 20:23:17 +0000213
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000214ConstantRange SCEVTruncateExpr::getValueRange() const {
Reid Spencerc6aedf72007-02-28 22:03:51 +0000215 return getOperand()->getValueRange().truncate(getBitWidth());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000216}
Chris Lattner53e677a2004-04-02 20:23:17 +0000217
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000218void SCEVTruncateExpr::print(std::ostream &OS) const {
219 OS << "(truncate " << *Op << " to " << *Ty << ")";
220}
221
222// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
223// particular input. Don't use a SCEVHandle here, or else the object will never
224// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000225static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
226 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000227
228SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000229 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000230 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000231 "Cannot zero extend non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000232 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
233 && "This is not an extending conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000234}
235
236SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000237 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000238}
239
240ConstantRange SCEVZeroExtendExpr::getValueRange() const {
Reid Spencerc6aedf72007-02-28 22:03:51 +0000241 return getOperand()->getValueRange().zeroExtend(getBitWidth());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000242}
243
244void SCEVZeroExtendExpr::print(std::ostream &OS) const {
245 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
246}
247
248// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
249// particular input. Don't use a SCEVHandle here, or else the object will never
250// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000251static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
252 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000253
254SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000255 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
256 std::vector<SCEV*>(Operands.begin(),
257 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000258}
259
260void SCEVCommutativeExpr::print(std::ostream &OS) const {
261 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
262 const char *OpStr = getOperationStr();
263 OS << "(" << *Operands[0];
264 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
265 OS << OpStr << *Operands[i];
266 OS << ")";
267}
268
Chris Lattner4dc534c2005-02-13 04:37:18 +0000269SCEVHandle SCEVCommutativeExpr::
270replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
271 const SCEVHandle &Conc) const {
272 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
273 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
274 if (H != getOperand(i)) {
275 std::vector<SCEVHandle> NewOps;
276 NewOps.reserve(getNumOperands());
277 for (unsigned j = 0; j != i; ++j)
278 NewOps.push_back(getOperand(j));
279 NewOps.push_back(H);
280 for (++i; i != e; ++i)
281 NewOps.push_back(getOperand(i)->
282 replaceSymbolicValuesWithConcrete(Sym, Conc));
283
284 if (isa<SCEVAddExpr>(this))
285 return SCEVAddExpr::get(NewOps);
286 else if (isa<SCEVMulExpr>(this))
287 return SCEVMulExpr::get(NewOps);
288 else
289 assert(0 && "Unknown commutative expr!");
290 }
291 }
292 return this;
293}
294
295
Chris Lattner60a05cc2006-04-01 04:48:52 +0000296// SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000297// input. Don't use a SCEVHandle here, or else the object will never be
298// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000299static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
300 SCEVSDivExpr*> > SCEVSDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000301
Chris Lattner60a05cc2006-04-01 04:48:52 +0000302SCEVSDivExpr::~SCEVSDivExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000303 SCEVSDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000304}
305
Chris Lattner60a05cc2006-04-01 04:48:52 +0000306void SCEVSDivExpr::print(std::ostream &OS) const {
307 OS << "(" << *LHS << " /s " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000308}
309
Chris Lattner60a05cc2006-04-01 04:48:52 +0000310const Type *SCEVSDivExpr::getType() const {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000311 return LHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000312}
313
314// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
315// particular input. Don't use a SCEVHandle here, or else the object will never
316// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000317static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
318 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000319
320SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000321 SCEVAddRecExprs->erase(std::make_pair(L,
322 std::vector<SCEV*>(Operands.begin(),
323 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000324}
325
Chris Lattner4dc534c2005-02-13 04:37:18 +0000326SCEVHandle SCEVAddRecExpr::
327replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
328 const SCEVHandle &Conc) const {
329 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
330 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
331 if (H != getOperand(i)) {
332 std::vector<SCEVHandle> NewOps;
333 NewOps.reserve(getNumOperands());
334 for (unsigned j = 0; j != i; ++j)
335 NewOps.push_back(getOperand(j));
336 NewOps.push_back(H);
337 for (++i; i != e; ++i)
338 NewOps.push_back(getOperand(i)->
339 replaceSymbolicValuesWithConcrete(Sym, Conc));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000340
Chris Lattner4dc534c2005-02-13 04:37:18 +0000341 return get(NewOps, L);
342 }
343 }
344 return this;
345}
346
347
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000348bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
349 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000350 // contain L and if the start is invariant.
351 return !QueryLoop->contains(L->getHeader()) &&
352 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000353}
354
355
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000356void SCEVAddRecExpr::print(std::ostream &OS) const {
357 OS << "{" << *Operands[0];
358 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
359 OS << ",+," << *Operands[i];
360 OS << "}<" << L->getHeader()->getName() + ">";
361}
Chris Lattner53e677a2004-04-02 20:23:17 +0000362
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000363// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
364// value. Don't use a SCEVHandle here, or else the object will never be
365// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000366static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000367
Chris Lattnerb3364092006-10-04 21:49:37 +0000368SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000369
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000370bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
371 // All non-instruction values are loop invariant. All instructions are loop
372 // invariant if they are not contained in the specified loop.
373 if (Instruction *I = dyn_cast<Instruction>(V))
374 return !L->contains(I->getParent());
375 return true;
376}
Chris Lattner53e677a2004-04-02 20:23:17 +0000377
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000378const Type *SCEVUnknown::getType() const {
379 return V->getType();
380}
Chris Lattner53e677a2004-04-02 20:23:17 +0000381
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000382void SCEVUnknown::print(std::ostream &OS) const {
383 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000384}
385
Chris Lattner8d741b82004-06-20 06:23:15 +0000386//===----------------------------------------------------------------------===//
387// SCEV Utilities
388//===----------------------------------------------------------------------===//
389
390namespace {
391 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
392 /// than the complexity of the RHS. This comparator is used to canonicalize
393 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000394 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Chris Lattner8d741b82004-06-20 06:23:15 +0000395 bool operator()(SCEV *LHS, SCEV *RHS) {
396 return LHS->getSCEVType() < RHS->getSCEVType();
397 }
398 };
399}
400
401/// GroupByComplexity - Given a list of SCEV objects, order them by their
402/// complexity, and group objects of the same complexity together by value.
403/// When this routine is finished, we know that any duplicates in the vector are
404/// consecutive and that complexity is monotonically increasing.
405///
406/// Note that we go take special precautions to ensure that we get determinstic
407/// results from this routine. In other words, we don't want the results of
408/// this to depend on where the addresses of various SCEV objects happened to
409/// land in memory.
410///
411static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
412 if (Ops.size() < 2) return; // Noop
413 if (Ops.size() == 2) {
414 // This is the common case, which also happens to be trivially simple.
415 // Special case it.
416 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
417 std::swap(Ops[0], Ops[1]);
418 return;
419 }
420
421 // Do the rough sort by complexity.
422 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
423
424 // Now that we are sorted by complexity, group elements of the same
425 // complexity. Note that this is, at worst, N^2, but the vector is likely to
426 // be extremely short in practice. Note that we take this approach because we
427 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000428 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000429 SCEV *S = Ops[i];
430 unsigned Complexity = S->getSCEVType();
431
432 // If there are any objects of the same complexity and same value as this
433 // one, group them.
434 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
435 if (Ops[j] == S) { // Found a duplicate.
436 // Move it to immediately after i'th element.
437 std::swap(Ops[i+1], Ops[j]);
438 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000439 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000440 }
441 }
442 }
443}
444
Chris Lattner53e677a2004-04-02 20:23:17 +0000445
Chris Lattner53e677a2004-04-02 20:23:17 +0000446
447//===----------------------------------------------------------------------===//
448// Simple SCEV method implementations
449//===----------------------------------------------------------------------===//
450
451/// getIntegerSCEV - Given an integer or FP type, create a constant for the
452/// specified signed integer value and return a SCEV for the constant.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000453SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000454 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000455 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000456 C = Constant::getNullValue(Ty);
457 else if (Ty->isFloatingPoint())
458 C = ConstantFP::get(Ty, Val);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000459 else
Reid Spencerb83eb642006-10-20 07:07:24 +0000460 C = ConstantInt::get(Ty, Val);
Chris Lattner53e677a2004-04-02 20:23:17 +0000461 return SCEVUnknown::get(C);
462}
463
Reid Spencer35fa4392007-03-01 22:28:51 +0000464SCEVHandle SCEVUnknown::getIntegerSCEV(const APInt& Val) {
465 return SCEVUnknown::get(ConstantInt::get(Val));
466}
467
Chris Lattner53e677a2004-04-02 20:23:17 +0000468/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
469/// input value to the specified type. If the type must be extended, it is zero
470/// extended.
471static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
472 const Type *SrcTy = V->getType();
Chris Lattner42a75512007-01-15 02:27:26 +0000473 assert(SrcTy->isInteger() && Ty->isInteger() &&
Chris Lattner53e677a2004-04-02 20:23:17 +0000474 "Cannot truncate or zero extend with non-integer arguments!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000475 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
Chris Lattner53e677a2004-04-02 20:23:17 +0000476 return V; // No conversion
Reid Spencere7ca0422007-01-08 01:26:33 +0000477 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
Chris Lattner53e677a2004-04-02 20:23:17 +0000478 return SCEVTruncateExpr::get(V, Ty);
479 return SCEVZeroExtendExpr::get(V, Ty);
480}
481
482/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
483///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000484SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000485 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
486 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000487
Chris Lattnerb06432c2004-04-23 21:29:03 +0000488 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000489}
490
491/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
492///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000493SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000494 // X - Y --> X + -Y
Chris Lattnerbac5b462005-03-09 05:34:41 +0000495 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000496}
497
498
Chris Lattner53e677a2004-04-02 20:23:17 +0000499/// PartialFact - Compute V!/(V-NumSteps)!
500static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
501 // Handle this case efficiently, it is common to have constant iteration
502 // counts while computing loop exit values.
503 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Zhou Sheng414de4d2007-04-07 17:48:27 +0000504 const APInt& Val = SC->getValue()->getValue();
Reid Spencerdc5c1592007-02-28 18:57:32 +0000505 APInt Result(Val.getBitWidth(), 1);
Chris Lattner53e677a2004-04-02 20:23:17 +0000506 for (; NumSteps; --NumSteps)
507 Result *= Val-(NumSteps-1);
Reid Spencerc7cd7a02007-03-01 19:32:33 +0000508 return SCEVUnknown::get(ConstantInt::get(Result));
Chris Lattner53e677a2004-04-02 20:23:17 +0000509 }
510
511 const Type *Ty = V->getType();
512 if (NumSteps == 0)
Chris Lattnerb06432c2004-04-23 21:29:03 +0000513 return SCEVUnknown::getIntegerSCEV(1, Ty);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000514
Chris Lattner53e677a2004-04-02 20:23:17 +0000515 SCEVHandle Result = V;
516 for (unsigned i = 1; i != NumSteps; ++i)
Chris Lattnerbac5b462005-03-09 05:34:41 +0000517 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V,
Chris Lattnerb06432c2004-04-23 21:29:03 +0000518 SCEVUnknown::getIntegerSCEV(i, Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000519 return Result;
520}
521
522
523/// evaluateAtIteration - Return the value of this chain of recurrences at
524/// the specified iteration number. We can evaluate this recurrence by
525/// multiplying each element in the chain by the binomial coefficient
526/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
527///
528/// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
529///
530/// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
531/// Is the binomial equation safe using modular arithmetic??
532///
533SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
534 SCEVHandle Result = getStart();
535 int Divisor = 1;
536 const Type *Ty = It->getType();
537 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
538 SCEVHandle BC = PartialFact(It, i);
539 Divisor *= i;
Chris Lattner60a05cc2006-04-01 04:48:52 +0000540 SCEVHandle Val = SCEVSDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
Chris Lattnerb06432c2004-04-23 21:29:03 +0000541 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000542 Result = SCEVAddExpr::get(Result, Val);
543 }
544 return Result;
545}
546
547
548//===----------------------------------------------------------------------===//
549// SCEV Expression folder implementations
550//===----------------------------------------------------------------------===//
551
552SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
553 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Reid Spencer7858b332006-12-05 19:14:13 +0000554 return SCEVUnknown::get(
Reid Spencer315d0552006-12-05 22:39:58 +0000555 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000556
557 // If the input value is a chrec scev made out of constants, truncate
558 // all of the constants.
559 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
560 std::vector<SCEVHandle> Operands;
561 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
562 // FIXME: This should allow truncation of other expression types!
563 if (isa<SCEVConstant>(AddRec->getOperand(i)))
564 Operands.push_back(get(AddRec->getOperand(i), Ty));
565 else
566 break;
567 if (Operands.size() == AddRec->getNumOperands())
568 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
569 }
570
Chris Lattnerb3364092006-10-04 21:49:37 +0000571 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000572 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
573 return Result;
574}
575
576SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
577 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Reid Spencer7858b332006-12-05 19:14:13 +0000578 return SCEVUnknown::get(
Reid Spencerd977d862006-12-12 23:36:14 +0000579 ConstantExpr::getZExt(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000580
581 // FIXME: If the input value is a chrec scev, and we can prove that the value
582 // did not overflow the old, smaller, value, we can zero extend all of the
583 // operands (often constants). This would allow analysis of something like
584 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
585
Chris Lattnerb3364092006-10-04 21:49:37 +0000586 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000587 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
588 return Result;
589}
590
591// get - Get a canonical add expression, or something simpler if possible.
592SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
593 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000594 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000595
596 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000597 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000598
599 // If there are any constants, fold them together.
600 unsigned Idx = 0;
601 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
602 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000603 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000604 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
605 // We found two constants, fold them together!
Zhou Shengfdc1e162007-04-07 17:40:57 +0000606 Constant *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
607 RHSC->getValue()->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +0000608 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
609 Ops[0] = SCEVConstant::get(CI);
610 Ops.erase(Ops.begin()+1); // Erase the folded element
611 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000612 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000613 } else {
614 // If we couldn't fold the expression, move to the next constant. Note
615 // that this is impossible to happen in practice because we always
616 // constant fold constant ints to constant ints.
617 ++Idx;
618 }
619 }
620
621 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +0000622 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000623 Ops.erase(Ops.begin());
624 --Idx;
625 }
626 }
627
Chris Lattner627018b2004-04-07 16:16:11 +0000628 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000629
Chris Lattner53e677a2004-04-02 20:23:17 +0000630 // Okay, check to see if the same value occurs in the operand list twice. If
631 // so, merge them together into an multiply expression. Since we sorted the
632 // list, these values are required to be adjacent.
633 const Type *Ty = Ops[0]->getType();
634 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
635 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
636 // Found a match, merge the two values into a multiply, and add any
637 // remaining values to the result.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000638 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000639 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
640 if (Ops.size() == 2)
641 return Mul;
642 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
643 Ops.push_back(Mul);
644 return SCEVAddExpr::get(Ops);
645 }
646
647 // Okay, now we know the first non-constant operand. If there are add
648 // operands they would be next.
649 if (Idx < Ops.size()) {
650 bool DeletedAdd = false;
651 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
652 // If we have an add, expand the add operands onto the end of the operands
653 // list.
654 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
655 Ops.erase(Ops.begin()+Idx);
656 DeletedAdd = true;
657 }
658
659 // If we deleted at least one add, we added operands to the end of the list,
660 // and they are not necessarily sorted. Recurse to resort and resimplify
661 // any operands we just aquired.
662 if (DeletedAdd)
663 return get(Ops);
664 }
665
666 // Skip over the add expression until we get to a multiply.
667 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
668 ++Idx;
669
670 // If we are adding something to a multiply expression, make sure the
671 // something is not already an operand of the multiply. If so, merge it into
672 // the multiply.
673 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
674 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
675 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
676 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
677 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000678 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000679 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
680 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
681 if (Mul->getNumOperands() != 2) {
682 // If the multiply has more than two operands, we must get the
683 // Y*Z term.
684 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
685 MulOps.erase(MulOps.begin()+MulOp);
686 InnerMul = SCEVMulExpr::get(MulOps);
687 }
Chris Lattnerb06432c2004-04-23 21:29:03 +0000688 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000689 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
690 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
691 if (Ops.size() == 2) return OuterMul;
692 if (AddOp < Idx) {
693 Ops.erase(Ops.begin()+AddOp);
694 Ops.erase(Ops.begin()+Idx-1);
695 } else {
696 Ops.erase(Ops.begin()+Idx);
697 Ops.erase(Ops.begin()+AddOp-1);
698 }
699 Ops.push_back(OuterMul);
700 return SCEVAddExpr::get(Ops);
701 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000702
Chris Lattner53e677a2004-04-02 20:23:17 +0000703 // Check this multiply against other multiplies being added together.
704 for (unsigned OtherMulIdx = Idx+1;
705 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
706 ++OtherMulIdx) {
707 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
708 // If MulOp occurs in OtherMul, we can fold the two multiplies
709 // together.
710 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
711 OMulOp != e; ++OMulOp)
712 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
713 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
714 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
715 if (Mul->getNumOperands() != 2) {
716 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
717 MulOps.erase(MulOps.begin()+MulOp);
718 InnerMul1 = SCEVMulExpr::get(MulOps);
719 }
720 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
721 if (OtherMul->getNumOperands() != 2) {
722 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
723 OtherMul->op_end());
724 MulOps.erase(MulOps.begin()+OMulOp);
725 InnerMul2 = SCEVMulExpr::get(MulOps);
726 }
727 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
728 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
729 if (Ops.size() == 2) return OuterMul;
730 Ops.erase(Ops.begin()+Idx);
731 Ops.erase(Ops.begin()+OtherMulIdx-1);
732 Ops.push_back(OuterMul);
733 return SCEVAddExpr::get(Ops);
734 }
735 }
736 }
737 }
738
739 // If there are any add recurrences in the operands list, see if any other
740 // added values are loop invariant. If so, we can fold them into the
741 // recurrence.
742 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
743 ++Idx;
744
745 // Scan over all recurrences, trying to fold loop invariants into them.
746 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
747 // Scan all of the other operands to this add and add them to the vector if
748 // they are loop invariant w.r.t. the recurrence.
749 std::vector<SCEVHandle> LIOps;
750 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
751 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
752 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
753 LIOps.push_back(Ops[i]);
754 Ops.erase(Ops.begin()+i);
755 --i; --e;
756 }
757
758 // If we found some loop invariants, fold them into the recurrence.
759 if (!LIOps.empty()) {
760 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
761 LIOps.push_back(AddRec->getStart());
762
763 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
764 AddRecOps[0] = SCEVAddExpr::get(LIOps);
765
766 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
767 // If all of the other operands were loop invariant, we are done.
768 if (Ops.size() == 1) return NewRec;
769
770 // Otherwise, add the folded AddRec by the non-liv parts.
771 for (unsigned i = 0;; ++i)
772 if (Ops[i] == AddRec) {
773 Ops[i] = NewRec;
774 break;
775 }
776 return SCEVAddExpr::get(Ops);
777 }
778
779 // Okay, if there weren't any loop invariants to be folded, check to see if
780 // there are multiple AddRec's with the same loop induction variable being
781 // added together. If so, we can fold them.
782 for (unsigned OtherIdx = Idx+1;
783 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
784 if (OtherIdx != Idx) {
785 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
786 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
787 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
788 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
789 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
790 if (i >= NewOps.size()) {
791 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
792 OtherAddRec->op_end());
793 break;
794 }
795 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
796 }
797 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
798
799 if (Ops.size() == 2) return NewAddRec;
800
801 Ops.erase(Ops.begin()+Idx);
802 Ops.erase(Ops.begin()+OtherIdx-1);
803 Ops.push_back(NewAddRec);
804 return SCEVAddExpr::get(Ops);
805 }
806 }
807
808 // Otherwise couldn't fold anything into this recurrence. Move onto the
809 // next one.
810 }
811
812 // Okay, it looks like we really DO need an add expr. Check to see if we
813 // already have one, otherwise create a new one.
814 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000815 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
816 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000817 if (Result == 0) Result = new SCEVAddExpr(Ops);
818 return Result;
819}
820
821
822SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
823 assert(!Ops.empty() && "Cannot get empty mul!");
824
825 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000826 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000827
828 // If there are any constants, fold them together.
829 unsigned Idx = 0;
830 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
831
832 // C1*(C2+V) -> C1*C2 + C1*V
833 if (Ops.size() == 2)
834 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
835 if (Add->getNumOperands() == 2 &&
836 isa<SCEVConstant>(Add->getOperand(0)))
837 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
838 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
839
840
841 ++Idx;
842 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
843 // We found two constants, fold them together!
Zhou Shengfdc1e162007-04-07 17:40:57 +0000844 Constant *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
845 RHSC->getValue()->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +0000846 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
847 Ops[0] = SCEVConstant::get(CI);
848 Ops.erase(Ops.begin()+1); // Erase the folded element
849 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000850 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000851 } else {
852 // If we couldn't fold the expression, move to the next constant. Note
853 // that this is impossible to happen in practice because we always
854 // constant fold constant ints to constant ints.
855 ++Idx;
856 }
857 }
858
859 // If we are left with a constant one being multiplied, strip it off.
860 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
861 Ops.erase(Ops.begin());
862 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +0000863 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000864 // If we have a multiply of zero, it will always be zero.
865 return Ops[0];
866 }
867 }
868
869 // Skip over the add expression until we get to a multiply.
870 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
871 ++Idx;
872
873 if (Ops.size() == 1)
874 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000875
Chris Lattner53e677a2004-04-02 20:23:17 +0000876 // If there are mul operands inline them all into this expression.
877 if (Idx < Ops.size()) {
878 bool DeletedMul = false;
879 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
880 // If we have an mul, expand the mul operands onto the end of the operands
881 // list.
882 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
883 Ops.erase(Ops.begin()+Idx);
884 DeletedMul = true;
885 }
886
887 // If we deleted at least one mul, we added operands to the end of the list,
888 // and they are not necessarily sorted. Recurse to resort and resimplify
889 // any operands we just aquired.
890 if (DeletedMul)
891 return get(Ops);
892 }
893
894 // If there are any add recurrences in the operands list, see if any other
895 // added values are loop invariant. If so, we can fold them into the
896 // recurrence.
897 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
898 ++Idx;
899
900 // Scan over all recurrences, trying to fold loop invariants into them.
901 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
902 // Scan all of the other operands to this mul and add them to the vector if
903 // they are loop invariant w.r.t. the recurrence.
904 std::vector<SCEVHandle> LIOps;
905 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
906 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
907 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
908 LIOps.push_back(Ops[i]);
909 Ops.erase(Ops.begin()+i);
910 --i; --e;
911 }
912
913 // If we found some loop invariants, fold them into the recurrence.
914 if (!LIOps.empty()) {
915 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
916 std::vector<SCEVHandle> NewOps;
917 NewOps.reserve(AddRec->getNumOperands());
918 if (LIOps.size() == 1) {
919 SCEV *Scale = LIOps[0];
920 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
921 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
922 } else {
923 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
924 std::vector<SCEVHandle> MulOps(LIOps);
925 MulOps.push_back(AddRec->getOperand(i));
926 NewOps.push_back(SCEVMulExpr::get(MulOps));
927 }
928 }
929
930 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
931
932 // If all of the other operands were loop invariant, we are done.
933 if (Ops.size() == 1) return NewRec;
934
935 // Otherwise, multiply the folded AddRec by the non-liv parts.
936 for (unsigned i = 0;; ++i)
937 if (Ops[i] == AddRec) {
938 Ops[i] = NewRec;
939 break;
940 }
941 return SCEVMulExpr::get(Ops);
942 }
943
944 // Okay, if there weren't any loop invariants to be folded, check to see if
945 // there are multiple AddRec's with the same loop induction variable being
946 // multiplied together. If so, we can fold them.
947 for (unsigned OtherIdx = Idx+1;
948 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
949 if (OtherIdx != Idx) {
950 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
951 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
952 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
953 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
954 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
955 G->getStart());
956 SCEVHandle B = F->getStepRecurrence();
957 SCEVHandle D = G->getStepRecurrence();
958 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
959 SCEVMulExpr::get(G, B),
960 SCEVMulExpr::get(B, D));
961 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
962 F->getLoop());
963 if (Ops.size() == 2) return NewAddRec;
964
965 Ops.erase(Ops.begin()+Idx);
966 Ops.erase(Ops.begin()+OtherIdx-1);
967 Ops.push_back(NewAddRec);
968 return SCEVMulExpr::get(Ops);
969 }
970 }
971
972 // Otherwise couldn't fold anything into this recurrence. Move onto the
973 // next one.
974 }
975
976 // Okay, it looks like we really DO need an mul expr. Check to see if we
977 // already have one, otherwise create a new one.
978 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000979 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
980 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000981 if (Result == 0)
982 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000983 return Result;
984}
985
Chris Lattner60a05cc2006-04-01 04:48:52 +0000986SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000987 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
988 if (RHSC->getValue()->equalsInt(1))
Reid Spencer1628cec2006-10-26 06:15:43 +0000989 return LHS; // X sdiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +0000990 if (RHSC->getValue()->isAllOnesValue())
Reid Spencer1628cec2006-10-26 06:15:43 +0000991 return SCEV::getNegativeSCEV(LHS); // X sdiv -1 --> -x
Chris Lattner53e677a2004-04-02 20:23:17 +0000992
993 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
994 Constant *LHSCV = LHSC->getValue();
995 Constant *RHSCV = RHSC->getValue();
Reid Spencer1628cec2006-10-26 06:15:43 +0000996 return SCEVUnknown::get(ConstantExpr::getSDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +0000997 }
998 }
999
1000 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1001
Chris Lattnerb3364092006-10-04 21:49:37 +00001002 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
Chris Lattner60a05cc2006-04-01 04:48:52 +00001003 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001004 return Result;
1005}
1006
1007
1008/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1009/// specified loop. Simplify the expression as much as possible.
1010SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
1011 const SCEVHandle &Step, const Loop *L) {
1012 std::vector<SCEVHandle> Operands;
1013 Operands.push_back(Start);
1014 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1015 if (StepChrec->getLoop() == L) {
1016 Operands.insert(Operands.end(), StepChrec->op_begin(),
1017 StepChrec->op_end());
1018 return get(Operands, L);
1019 }
1020
1021 Operands.push_back(Step);
1022 return get(Operands, L);
1023}
1024
1025/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1026/// specified loop. Simplify the expression as much as possible.
1027SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1028 const Loop *L) {
1029 if (Operands.size() == 1) return Operands[0];
1030
1031 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
Reid Spencercae57542007-03-02 00:28:52 +00001032 if (StepC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001033 Operands.pop_back();
1034 return get(Operands, L); // { X,+,0 } --> X
1035 }
1036
1037 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001038 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1039 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001040 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1041 return Result;
1042}
1043
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001044SCEVHandle SCEVUnknown::get(Value *V) {
1045 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1046 return SCEVConstant::get(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001047 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001048 if (Result == 0) Result = new SCEVUnknown(V);
1049 return Result;
1050}
1051
Chris Lattner53e677a2004-04-02 20:23:17 +00001052
1053//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001054// ScalarEvolutionsImpl Definition and Implementation
1055//===----------------------------------------------------------------------===//
1056//
1057/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1058/// evolution code.
1059///
1060namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001061 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Chris Lattner53e677a2004-04-02 20:23:17 +00001062 /// F - The function we are analyzing.
1063 ///
1064 Function &F;
1065
1066 /// LI - The loop information for the function we are currently analyzing.
1067 ///
1068 LoopInfo &LI;
1069
1070 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1071 /// things.
1072 SCEVHandle UnknownValue;
1073
1074 /// Scalars - This is a cache of the scalars we have analyzed so far.
1075 ///
1076 std::map<Value*, SCEVHandle> Scalars;
1077
1078 /// IterationCounts - Cache the iteration count of the loops for this
1079 /// function as they are computed.
1080 std::map<const Loop*, SCEVHandle> IterationCounts;
1081
Chris Lattner3221ad02004-04-17 22:58:41 +00001082 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1083 /// the PHI instructions that we attempt to compute constant evolutions for.
1084 /// This allows us to avoid potentially expensive recomputation of these
1085 /// properties. An instruction maps to null if we are unable to compute its
1086 /// exit value.
1087 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001088
Chris Lattner53e677a2004-04-02 20:23:17 +00001089 public:
1090 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1091 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1092
1093 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1094 /// expression and create a new one.
1095 SCEVHandle getSCEV(Value *V);
1096
Chris Lattnera0740fb2005-08-09 23:36:33 +00001097 /// hasSCEV - Return true if the SCEV for this value has already been
1098 /// computed.
1099 bool hasSCEV(Value *V) const {
1100 return Scalars.count(V);
1101 }
1102
1103 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1104 /// the specified value.
1105 void setSCEV(Value *V, const SCEVHandle &H) {
1106 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1107 assert(isNew && "This entry already existed!");
1108 }
1109
1110
Chris Lattner53e677a2004-04-02 20:23:17 +00001111 /// getSCEVAtScope - Compute the value of the specified expression within
1112 /// the indicated loop (which may be null to indicate in no loop). If the
1113 /// expression cannot be evaluated, return UnknownValue itself.
1114 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1115
1116
1117 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1118 /// an analyzable loop-invariant iteration count.
1119 bool hasLoopInvariantIterationCount(const Loop *L);
1120
1121 /// getIterationCount - If the specified loop has a predictable iteration
1122 /// count, return it. Note that it is not valid to call this method on a
1123 /// loop without a loop-invariant iteration count.
1124 SCEVHandle getIterationCount(const Loop *L);
1125
1126 /// deleteInstructionFromRecords - This method should be called by the
1127 /// client before it removes an instruction from the program, to make sure
1128 /// that no dangling references are left around.
1129 void deleteInstructionFromRecords(Instruction *I);
1130
1131 private:
1132 /// createSCEV - We know that there is no SCEV for the specified value.
1133 /// Analyze the expression.
1134 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001135
1136 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1137 /// SCEVs.
1138 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001139
1140 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1141 /// for the specified instruction and replaces any references to the
1142 /// symbolic value SymName with the specified value. This is used during
1143 /// PHI resolution.
1144 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1145 const SCEVHandle &SymName,
1146 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001147
1148 /// ComputeIterationCount - Compute the number of times the specified loop
1149 /// will iterate.
1150 SCEVHandle ComputeIterationCount(const Loop *L);
1151
Chris Lattner673e02b2004-10-12 01:49:27 +00001152 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Zhou Sheng83428362007-04-07 17:12:38 +00001153 /// 'setcc load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00001154 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1155 Constant *RHS,
1156 const Loop *L,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001157 ICmpInst::Predicate p);
Chris Lattner673e02b2004-10-12 01:49:27 +00001158
Chris Lattner7980fb92004-04-17 18:36:24 +00001159 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1160 /// constant number of times (the condition evolves only from constants),
1161 /// try to evaluate a few iterations of the loop until we get the exit
1162 /// condition gets a value of ExitWhen (true or false). If we cannot
1163 /// evaluate the trip count of the loop, return UnknownValue.
1164 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1165 bool ExitWhen);
1166
Chris Lattner53e677a2004-04-02 20:23:17 +00001167 /// HowFarToZero - Return the number of times a backedge comparing the
1168 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001169 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001170 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1171
1172 /// HowFarToNonZero - Return the number of times a backedge checking the
1173 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001174 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001175 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001176
Chris Lattnerdb25de42005-08-15 23:33:51 +00001177 /// HowManyLessThans - Return the number of times a backedge containing the
1178 /// specified less-than comparison will execute. If not computable, return
1179 /// UnknownValue.
1180 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L);
1181
Chris Lattner3221ad02004-04-17 22:58:41 +00001182 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1183 /// in the header of its containing loop, we know the loop executes a
1184 /// constant number of times, and the PHI node is just a recurrence
1185 /// involving constants, fold it.
Reid Spencere8019bb2007-03-01 07:25:48 +00001186 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
Chris Lattner3221ad02004-04-17 22:58:41 +00001187 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001188 };
1189}
1190
1191//===----------------------------------------------------------------------===//
1192// Basic SCEV Analysis and PHI Idiom Recognition Code
1193//
1194
1195/// deleteInstructionFromRecords - This method should be called by the
1196/// client before it removes an instruction from the program, to make sure
1197/// that no dangling references are left around.
1198void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001199 SmallVector<Instruction *, 16> Worklist;
1200
1201 if (Scalars.erase(I)) {
1202 if (PHINode *PN = dyn_cast<PHINode>(I))
1203 ConstantEvolutionLoopExitValue.erase(PN);
1204 Worklist.push_back(I);
1205 }
1206
1207 while (!Worklist.empty()) {
1208 Instruction *II = Worklist.back();
1209 Worklist.pop_back();
1210
1211 for (Instruction::use_iterator UI = II->use_begin(), UE = II->use_end();
1212 UI != UE; ++UI) {
1213 Instruction *Inst = dyn_cast<Instruction>(*UI);
1214 if (Inst && hasSCEV(Inst) && Scalars.erase(Inst)) {
1215 if (PHINode *PN = dyn_cast<PHINode>(II))
1216 ConstantEvolutionLoopExitValue.erase(PN);
1217 Worklist.push_back(Inst);
1218 }
1219 }
1220 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001221}
1222
1223
1224/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1225/// expression and create a new one.
1226SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1227 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1228
1229 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1230 if (I != Scalars.end()) return I->second;
1231 SCEVHandle S = createSCEV(V);
1232 Scalars.insert(std::make_pair(V, S));
1233 return S;
1234}
1235
Chris Lattner4dc534c2005-02-13 04:37:18 +00001236/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1237/// the specified instruction and replaces any references to the symbolic value
1238/// SymName with the specified value. This is used during PHI resolution.
1239void ScalarEvolutionsImpl::
1240ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1241 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001242 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001243 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001244
Chris Lattner4dc534c2005-02-13 04:37:18 +00001245 SCEVHandle NV =
1246 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal);
1247 if (NV == SI->second) return; // No change.
1248
1249 SI->second = NV; // Update the scalars map!
1250
1251 // Any instruction values that use this instruction might also need to be
1252 // updated!
1253 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1254 UI != E; ++UI)
1255 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1256}
Chris Lattner53e677a2004-04-02 20:23:17 +00001257
1258/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1259/// a loop header, making it a potential recurrence, or it doesn't.
1260///
1261SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1262 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1263 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1264 if (L->getHeader() == PN->getParent()) {
1265 // If it lives in the loop header, it has two incoming values, one
1266 // from outside the loop, and one from inside.
1267 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1268 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001269
Chris Lattner53e677a2004-04-02 20:23:17 +00001270 // While we are analyzing this PHI node, handle its value symbolically.
1271 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1272 assert(Scalars.find(PN) == Scalars.end() &&
1273 "PHI node already processed?");
1274 Scalars.insert(std::make_pair(PN, SymbolicName));
1275
1276 // Using this symbolic name for the PHI, analyze the value coming around
1277 // the back-edge.
1278 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1279
1280 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1281 // has a special value for the first iteration of the loop.
1282
1283 // If the value coming around the backedge is an add with the symbolic
1284 // value we just inserted, then we found a simple induction variable!
1285 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1286 // If there is a single occurrence of the symbolic value, replace it
1287 // with a recurrence.
1288 unsigned FoundIndex = Add->getNumOperands();
1289 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1290 if (Add->getOperand(i) == SymbolicName)
1291 if (FoundIndex == e) {
1292 FoundIndex = i;
1293 break;
1294 }
1295
1296 if (FoundIndex != Add->getNumOperands()) {
1297 // Create an add with everything but the specified operand.
1298 std::vector<SCEVHandle> Ops;
1299 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1300 if (i != FoundIndex)
1301 Ops.push_back(Add->getOperand(i));
1302 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1303
1304 // This is not a valid addrec if the step amount is varying each
1305 // loop iteration, but is not itself an addrec in this loop.
1306 if (Accum->isLoopInvariant(L) ||
1307 (isa<SCEVAddRecExpr>(Accum) &&
1308 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1309 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1310 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1311
1312 // Okay, for the entire analysis of this edge we assumed the PHI
1313 // to be symbolic. We now need to go back and update all of the
1314 // entries for the scalars that use the PHI (except for the PHI
1315 // itself) to use the new analyzed value instead of the "symbolic"
1316 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001317 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001318 return PHISCEV;
1319 }
1320 }
Chris Lattner97156e72006-04-26 18:34:07 +00001321 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1322 // Otherwise, this could be a loop like this:
1323 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1324 // In this case, j = {1,+,1} and BEValue is j.
1325 // Because the other in-value of i (0) fits the evolution of BEValue
1326 // i really is an addrec evolution.
1327 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1328 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1329
1330 // If StartVal = j.start - j.stride, we can use StartVal as the
1331 // initial step of the addrec evolution.
1332 if (StartVal == SCEV::getMinusSCEV(AddRec->getOperand(0),
1333 AddRec->getOperand(1))) {
1334 SCEVHandle PHISCEV =
1335 SCEVAddRecExpr::get(StartVal, AddRec->getOperand(1), L);
1336
1337 // Okay, for the entire analysis of this edge we assumed the PHI
1338 // to be symbolic. We now need to go back and update all of the
1339 // entries for the scalars that use the PHI (except for the PHI
1340 // itself) to use the new analyzed value instead of the "symbolic"
1341 // value.
1342 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1343 return PHISCEV;
1344 }
1345 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001346 }
1347
1348 return SymbolicName;
1349 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001350
Chris Lattner53e677a2004-04-02 20:23:17 +00001351 // If it's not a loop phi, we can't handle it yet.
1352 return SCEVUnknown::get(PN);
1353}
1354
Chris Lattnera17f0392006-12-12 02:26:09 +00001355/// GetConstantFactor - Determine the largest constant factor that S has. For
1356/// example, turn {4,+,8} -> 4. (S umod result) should always equal zero.
Reid Spencer6263cba2007-02-28 23:31:17 +00001357static APInt GetConstantFactor(SCEVHandle S) {
Chris Lattnera17f0392006-12-12 02:26:09 +00001358 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Zhou Sheng414de4d2007-04-07 17:48:27 +00001359 const APInt& V = C->getValue()->getValue();
Reid Spencer6263cba2007-02-28 23:31:17 +00001360 if (!V.isMinValue())
Chris Lattnera17f0392006-12-12 02:26:09 +00001361 return V;
1362 else // Zero is a multiple of everything.
Reid Spencer6263cba2007-02-28 23:31:17 +00001363 return APInt(C->getBitWidth(), 1).shl(C->getBitWidth()-1);
Chris Lattnera17f0392006-12-12 02:26:09 +00001364 }
1365
Reid Spencer9b4aeb32007-03-02 02:59:25 +00001366 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) {
Zhou Sheng83428362007-04-07 17:12:38 +00001367 return GetConstantFactor(T->getOperand()).trunc(
1368 cast<IntegerType>(T->getType())->getBitWidth());
Reid Spencer9b4aeb32007-03-02 02:59:25 +00001369 }
Chris Lattnera17f0392006-12-12 02:26:09 +00001370 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S))
Zhou Sheng83428362007-04-07 17:12:38 +00001371 return GetConstantFactor(E->getOperand()).zext(
1372 cast<IntegerType>(E->getType())->getBitWidth());
Chris Lattnera17f0392006-12-12 02:26:09 +00001373
1374 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1375 // The result is the min of all operands.
Zhou Sheng83428362007-04-07 17:12:38 +00001376 APInt Res(GetConstantFactor(A->getOperand(0)));
Reid Spencer6263cba2007-02-28 23:31:17 +00001377 for (unsigned i = 1, e = A->getNumOperands();
Reid Spencer07976052007-03-04 01:25:35 +00001378 i != e && Res.ugt(APInt(Res.getBitWidth(),1)); ++i) {
1379 APInt Tmp(GetConstantFactor(A->getOperand(i)));
Reid Spencer07976052007-03-04 01:25:35 +00001380 Res = APIntOps::umin(Res, Tmp);
1381 }
Chris Lattnera17f0392006-12-12 02:26:09 +00001382 return Res;
1383 }
1384
1385 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1386 // The result is the product of all the operands.
Zhou Sheng83428362007-04-07 17:12:38 +00001387 APInt Res(GetConstantFactor(M->getOperand(0)));
Reid Spencer07976052007-03-04 01:25:35 +00001388 for (unsigned i = 1, e = M->getNumOperands(); i != e; ++i) {
1389 APInt Tmp(GetConstantFactor(M->getOperand(i)));
Reid Spencer07976052007-03-04 01:25:35 +00001390 Res *= Tmp;
1391 }
Chris Lattnera17f0392006-12-12 02:26:09 +00001392 return Res;
1393 }
1394
1395 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Chris Lattner75de5ab2006-12-19 01:16:02 +00001396 // For now, we just handle linear expressions.
1397 if (A->getNumOperands() == 2) {
1398 // We want the GCD between the start and the stride value.
Zhou Sheng83428362007-04-07 17:12:38 +00001399 APInt Start(GetConstantFactor(A->getOperand(0)));
Reid Spencer6263cba2007-02-28 23:31:17 +00001400 if (Start == 1)
Zhou Sheng83428362007-04-07 17:12:38 +00001401 return Start;
1402 APInt Stride(GetConstantFactor(A->getOperand(1)));
Reid Spencer6263cba2007-02-28 23:31:17 +00001403 return APIntOps::GreatestCommonDivisor(Start, Stride);
Chris Lattner75de5ab2006-12-19 01:16:02 +00001404 }
Chris Lattnera17f0392006-12-12 02:26:09 +00001405 }
1406
1407 // SCEVSDivExpr, SCEVUnknown.
Reid Spencer6263cba2007-02-28 23:31:17 +00001408 return APInt(S->getBitWidth(), 1);
Chris Lattnera17f0392006-12-12 02:26:09 +00001409}
Chris Lattner53e677a2004-04-02 20:23:17 +00001410
1411/// createSCEV - We know that there is no SCEV for the specified value.
1412/// Analyze the expression.
1413///
1414SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1415 if (Instruction *I = dyn_cast<Instruction>(V)) {
1416 switch (I->getOpcode()) {
1417 case Instruction::Add:
1418 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1419 getSCEV(I->getOperand(1)));
1420 case Instruction::Mul:
1421 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1422 getSCEV(I->getOperand(1)));
Reid Spencer1628cec2006-10-26 06:15:43 +00001423 case Instruction::SDiv:
1424 return SCEVSDivExpr::get(getSCEV(I->getOperand(0)),
1425 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001426 break;
1427
1428 case Instruction::Sub:
Chris Lattnerbac5b462005-03-09 05:34:41 +00001429 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)),
1430 getSCEV(I->getOperand(1)));
Chris Lattnera17f0392006-12-12 02:26:09 +00001431 case Instruction::Or:
1432 // If the RHS of the Or is a constant, we may have something like:
1433 // X*4+1 which got turned into X*4|1. Handle this as an add so loop
1434 // optimizations will transparently handle this case.
1435 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1436 SCEVHandle LHS = getSCEV(I->getOperand(0));
Zhou Shengfdc1e162007-04-07 17:40:57 +00001437 APInt CommonFact(GetConstantFactor(LHS));
Reid Spencer6263cba2007-02-28 23:31:17 +00001438 assert(!CommonFact.isMinValue() &&
1439 "Common factor should at least be 1!");
1440 if (CommonFact.ugt(CI->getValue())) {
Chris Lattnera17f0392006-12-12 02:26:09 +00001441 // If the LHS is a multiple that is larger than the RHS, use +.
1442 return SCEVAddExpr::get(LHS,
1443 getSCEV(I->getOperand(1)));
1444 }
1445 }
1446 break;
Chris Lattner2811f2a2007-04-02 05:41:38 +00001447 case Instruction::Xor:
1448 // If the RHS of the xor is a signbit, then this is just an add.
1449 // Instcombine turns add of signbit into xor as a strength reduction step.
1450 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1451 if (CI->getValue().isSignBit())
1452 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1453 getSCEV(I->getOperand(1)));
1454 }
1455 break;
1456
Chris Lattner53e677a2004-04-02 20:23:17 +00001457 case Instruction::Shl:
1458 // Turn shift left of a constant amount into a multiply.
1459 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfdc1e162007-04-07 17:40:57 +00001460 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1461 Constant *X = ConstantInt::get(
1462 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001463 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1464 }
1465 break;
1466
Reid Spencer3da59db2006-11-27 01:05:10 +00001467 case Instruction::Trunc:
Chris Lattnerb2f3e702007-01-15 01:58:56 +00001468 return SCEVTruncateExpr::get(getSCEV(I->getOperand(0)), I->getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001469
1470 case Instruction::ZExt:
Chris Lattnerb2f3e702007-01-15 01:58:56 +00001471 return SCEVZeroExtendExpr::get(getSCEV(I->getOperand(0)), I->getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001472
1473 case Instruction::BitCast:
1474 // BitCasts are no-op casts so we just eliminate the cast.
Chris Lattner42a75512007-01-15 02:27:26 +00001475 if (I->getType()->isInteger() &&
1476 I->getOperand(0)->getType()->isInteger())
Chris Lattner82e8a8f2006-12-11 00:12:31 +00001477 return getSCEV(I->getOperand(0));
1478 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001479
1480 case Instruction::PHI:
1481 return createNodeForPHI(cast<PHINode>(I));
1482
1483 default: // We cannot analyze this expression.
1484 break;
1485 }
1486 }
1487
1488 return SCEVUnknown::get(V);
1489}
1490
1491
1492
1493//===----------------------------------------------------------------------===//
1494// Iteration Count Computation Code
1495//
1496
1497/// getIterationCount - If the specified loop has a predictable iteration
1498/// count, return it. Note that it is not valid to call this method on a
1499/// loop without a loop-invariant iteration count.
1500SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1501 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1502 if (I == IterationCounts.end()) {
1503 SCEVHandle ItCount = ComputeIterationCount(L);
1504 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1505 if (ItCount != UnknownValue) {
1506 assert(ItCount->isLoopInvariant(L) &&
1507 "Computed trip count isn't loop invariant for loop!");
1508 ++NumTripCountsComputed;
1509 } else if (isa<PHINode>(L->getHeader()->begin())) {
1510 // Only count loops that have phi nodes as not being computable.
1511 ++NumTripCountsNotComputed;
1512 }
1513 }
1514 return I->second;
1515}
1516
1517/// ComputeIterationCount - Compute the number of times the specified loop
1518/// will iterate.
1519SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1520 // If the loop has a non-one exit block count, we can't analyze it.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001521 std::vector<BasicBlock*> ExitBlocks;
1522 L->getExitBlocks(ExitBlocks);
1523 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001524
1525 // Okay, there is one exit block. Try to find the condition that causes the
1526 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001527 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001528
1529 BasicBlock *ExitingBlock = 0;
1530 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1531 PI != E; ++PI)
1532 if (L->contains(*PI)) {
1533 if (ExitingBlock == 0)
1534 ExitingBlock = *PI;
1535 else
1536 return UnknownValue; // More than one block exiting!
1537 }
1538 assert(ExitingBlock && "No exits from loop, something is broken!");
1539
1540 // Okay, we've computed the exiting block. See what condition causes us to
1541 // exit.
1542 //
1543 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00001544 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1545 if (ExitBr == 0) return UnknownValue;
1546 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00001547
1548 // At this point, we know we have a conditional branch that determines whether
1549 // the loop is exited. However, we don't know if the branch is executed each
1550 // time through the loop. If not, then the execution count of the branch will
1551 // not be equal to the trip count of the loop.
1552 //
1553 // Currently we check for this by checking to see if the Exit branch goes to
1554 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00001555 // times as the loop. We also handle the case where the exit block *is* the
1556 // loop header. This is common for un-rotated loops. More extensive analysis
1557 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001558 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00001559 ExitBr->getSuccessor(1) != L->getHeader() &&
1560 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00001561 return UnknownValue;
1562
Reid Spencere4d87aa2006-12-23 06:05:41 +00001563 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1564
1565 // If its not an integer comparison then compute it the hard way.
1566 // Note that ICmpInst deals with pointer comparisons too so we must check
1567 // the type of the operand.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001568 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Chris Lattner7980fb92004-04-17 18:36:24 +00001569 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1570 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001571
Reid Spencere4d87aa2006-12-23 06:05:41 +00001572 // If the condition was exit on true, convert the condition to exit on false
1573 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00001574 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001575 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001576 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00001577 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001578
1579 // Handle common loops like: for (X = "string"; *X; ++X)
1580 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1581 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1582 SCEVHandle ItCnt =
1583 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1584 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1585 }
1586
Chris Lattner53e677a2004-04-02 20:23:17 +00001587 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1588 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1589
1590 // Try to evaluate any dependencies out of the loop.
1591 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1592 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1593 Tmp = getSCEVAtScope(RHS, L);
1594 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1595
Reid Spencere4d87aa2006-12-23 06:05:41 +00001596 // At this point, we would like to compute how many iterations of the
1597 // loop the predicate will return true for these inputs.
Chris Lattner53e677a2004-04-02 20:23:17 +00001598 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1599 // If there is a constant, force it into the RHS.
1600 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001601 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00001602 }
1603
1604 // FIXME: think about handling pointer comparisons! i.e.:
1605 // while (P != P+100) ++P;
1606
1607 // If we have a comparison of a chrec against a constant, try to use value
1608 // ranges to answer this query.
1609 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1610 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1611 if (AddRec->getLoop() == L) {
1612 // Form the comparison range using the constant of the correct type so
1613 // that the ConstantRange class knows to do a signed or unsigned
1614 // comparison.
1615 ConstantInt *CompVal = RHSC->getValue();
1616 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00001617 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00001618 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00001619 if (CompVal) {
1620 // Form the constant range.
Reid Spencerc6aedf72007-02-28 22:03:51 +00001621 ConstantRange CompRange(
1622 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001623
Reid Spencere4d87aa2006-12-23 06:05:41 +00001624 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange,
Reid Spencerc5b206b2006-12-31 05:48:39 +00001625 false /*Always treat as unsigned range*/);
Chris Lattner53e677a2004-04-02 20:23:17 +00001626 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1627 }
1628 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001629
Chris Lattner53e677a2004-04-02 20:23:17 +00001630 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001631 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00001632 // Convert to: while (X-Y != 0)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001633 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L);
1634 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00001635 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001636 }
1637 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00001638 // Convert to: while (X-Y == 0) // while (X == Y)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001639 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L);
1640 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00001641 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001642 }
1643 case ICmpInst::ICMP_SLT: {
1644 SCEVHandle TC = HowManyLessThans(LHS, RHS, L);
1645 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001646 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001647 }
1648 case ICmpInst::ICMP_SGT: {
1649 SCEVHandle TC = HowManyLessThans(RHS, LHS, L);
1650 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001651 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001652 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001653 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001654#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001655 cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00001656 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendlinge8156192006-12-07 01:30:32 +00001657 cerr << "[unsigned] ";
1658 cerr << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00001659 << Instruction::getOpcodeName(Instruction::ICmp)
1660 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001661#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00001662 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001663 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001664 return ComputeIterationCountExhaustively(L, ExitCond,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001665 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00001666}
1667
Chris Lattner673e02b2004-10-12 01:49:27 +00001668static ConstantInt *
1669EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1670 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1671 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1672 assert(isa<SCEVConstant>(Val) &&
1673 "Evaluation of SCEV at constant didn't fold correctly?");
1674 return cast<SCEVConstant>(Val)->getValue();
1675}
1676
1677/// GetAddressedElementFromGlobal - Given a global variable with an initializer
1678/// and a GEP expression (missing the pointer index) indexing into it, return
1679/// the addressed element of the initializer or null if the index expression is
1680/// invalid.
1681static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001682GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00001683 const std::vector<ConstantInt*> &Indices) {
1684 Constant *Init = GV->getInitializer();
1685 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001686 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00001687 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1688 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1689 Init = cast<Constant>(CS->getOperand(Idx));
1690 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1691 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1692 Init = cast<Constant>(CA->getOperand(Idx));
1693 } else if (isa<ConstantAggregateZero>(Init)) {
1694 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1695 assert(Idx < STy->getNumElements() && "Bad struct index!");
1696 Init = Constant::getNullValue(STy->getElementType(Idx));
1697 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1698 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1699 Init = Constant::getNullValue(ATy->getElementType());
1700 } else {
1701 assert(0 && "Unknown constant aggregate type!");
1702 }
1703 return 0;
1704 } else {
1705 return 0; // Unknown initializer type
1706 }
1707 }
1708 return Init;
1709}
1710
1711/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1712/// 'setcc load X, cst', try to se if we can compute the trip count.
1713SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001714ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001715 const Loop *L,
1716 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00001717 if (LI->isVolatile()) return UnknownValue;
1718
1719 // Check to see if the loaded pointer is a getelementptr of a global.
1720 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1721 if (!GEP) return UnknownValue;
1722
1723 // Make sure that it is really a constant global we are gepping, with an
1724 // initializer, and make sure the first IDX is really 0.
1725 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1726 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1727 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1728 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1729 return UnknownValue;
1730
1731 // Okay, we allow one non-constant index into the GEP instruction.
1732 Value *VarIdx = 0;
1733 std::vector<ConstantInt*> Indexes;
1734 unsigned VarIdxNum = 0;
1735 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1736 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1737 Indexes.push_back(CI);
1738 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1739 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1740 VarIdx = GEP->getOperand(i);
1741 VarIdxNum = i-2;
1742 Indexes.push_back(0);
1743 }
1744
1745 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1746 // Check to see if X is a loop variant variable value now.
1747 SCEVHandle Idx = getSCEV(VarIdx);
1748 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1749 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1750
1751 // We can only recognize very limited forms of loop index expressions, in
1752 // particular, only affine AddRec's like {C1,+,C2}.
1753 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1754 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1755 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1756 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1757 return UnknownValue;
1758
1759 unsigned MaxSteps = MaxBruteForceIterations;
1760 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001761 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00001762 ConstantInt::get(IdxExpr->getType(), IterationNum);
Chris Lattner673e02b2004-10-12 01:49:27 +00001763 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1764
1765 // Form the GEP offset.
1766 Indexes[VarIdxNum] = Val;
1767
1768 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1769 if (Result == 0) break; // Cannot compute!
1770
1771 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001772 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001773 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00001774 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00001775#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001776 cerr << "\n***\n*** Computed loop count " << *ItCst
1777 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1778 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00001779#endif
1780 ++NumArrayLenItCounts;
1781 return SCEVConstant::get(ItCst); // Found terminating iteration!
1782 }
1783 }
1784 return UnknownValue;
1785}
1786
1787
Chris Lattner3221ad02004-04-17 22:58:41 +00001788/// CanConstantFold - Return true if we can constant fold an instruction of the
1789/// specified type, assuming that all operands were constants.
1790static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00001791 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00001792 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1793 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001794
Chris Lattner3221ad02004-04-17 22:58:41 +00001795 if (const CallInst *CI = dyn_cast<CallInst>(I))
1796 if (const Function *F = CI->getCalledFunction())
1797 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1798 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00001799}
1800
Chris Lattner3221ad02004-04-17 22:58:41 +00001801/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1802/// in the loop that V is derived from. We allow arbitrary operations along the
1803/// way, but the operands of an operation must either be constants or a value
1804/// derived from a constant PHI. If this expression does not fit with these
1805/// constraints, return null.
1806static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1807 // If this is not an instruction, or if this is an instruction outside of the
1808 // loop, it can't be derived from a loop PHI.
1809 Instruction *I = dyn_cast<Instruction>(V);
1810 if (I == 0 || !L->contains(I->getParent())) return 0;
1811
1812 if (PHINode *PN = dyn_cast<PHINode>(I))
1813 if (L->getHeader() == I->getParent())
1814 return PN;
1815 else
1816 // We don't currently keep track of the control flow needed to evaluate
1817 // PHIs, so we cannot handle PHIs inside of loops.
1818 return 0;
1819
1820 // If we won't be able to constant fold this expression even if the operands
1821 // are constants, return early.
1822 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001823
Chris Lattner3221ad02004-04-17 22:58:41 +00001824 // Otherwise, we can evaluate this instruction if all of its operands are
1825 // constant or derived from a PHI node themselves.
1826 PHINode *PHI = 0;
1827 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1828 if (!(isa<Constant>(I->getOperand(Op)) ||
1829 isa<GlobalValue>(I->getOperand(Op)))) {
1830 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1831 if (P == 0) return 0; // Not evolving from PHI
1832 if (PHI == 0)
1833 PHI = P;
1834 else if (PHI != P)
1835 return 0; // Evolving from multiple different PHIs.
1836 }
1837
1838 // This is a expression evolving from a constant PHI!
1839 return PHI;
1840}
1841
1842/// EvaluateExpression - Given an expression that passes the
1843/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1844/// in the loop has the value PHIVal. If we can't fold this expression for some
1845/// reason, return null.
1846static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1847 if (isa<PHINode>(V)) return PHIVal;
Chris Lattner3221ad02004-04-17 22:58:41 +00001848 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
Reid Spencere8404342004-07-18 00:18:30 +00001849 return GV;
1850 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00001851 Instruction *I = cast<Instruction>(V);
1852
1853 std::vector<Constant*> Operands;
1854 Operands.resize(I->getNumOperands());
1855
1856 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1857 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1858 if (Operands[i] == 0) return 0;
1859 }
1860
Chris Lattner2e3a1d12007-01-30 23:52:44 +00001861 return ConstantFoldInstOperands(I, &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00001862}
1863
1864/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1865/// in the header of its containing loop, we know the loop executes a
1866/// constant number of times, and the PHI node is just a recurrence
1867/// involving constants, fold it.
1868Constant *ScalarEvolutionsImpl::
Reid Spencere8019bb2007-03-01 07:25:48 +00001869getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00001870 std::map<PHINode*, Constant*>::iterator I =
1871 ConstantEvolutionLoopExitValue.find(PN);
1872 if (I != ConstantEvolutionLoopExitValue.end())
1873 return I->second;
1874
Reid Spencere8019bb2007-03-01 07:25:48 +00001875 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00001876 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1877
1878 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1879
1880 // Since the loop is canonicalized, the PHI node must have two entries. One
1881 // entry must be a constant (coming in from outside of the loop), and the
1882 // second must be derived from the same PHI.
1883 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1884 Constant *StartCST =
1885 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1886 if (StartCST == 0)
1887 return RetVal = 0; // Must be a constant.
1888
1889 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1890 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1891 if (PN2 != PN)
1892 return RetVal = 0; // Not derived from same PHI.
1893
1894 // Execute the loop symbolically to determine the exit value.
Reid Spencere8019bb2007-03-01 07:25:48 +00001895 if (Its.getActiveBits() >= 32)
1896 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00001897
Reid Spencere8019bb2007-03-01 07:25:48 +00001898 unsigned NumIterations = Its.getZExtValue(); // must be in range
1899 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00001900 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1901 if (IterationNum == NumIterations)
1902 return RetVal = PHIVal; // Got exit value!
1903
1904 // Compute the value of the PHI node for the next iteration.
1905 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1906 if (NextPHI == PHIVal)
1907 return RetVal = NextPHI; // Stopped evolving!
1908 if (NextPHI == 0)
1909 return 0; // Couldn't evaluate!
1910 PHIVal = NextPHI;
1911 }
1912}
1913
Chris Lattner7980fb92004-04-17 18:36:24 +00001914/// ComputeIterationCountExhaustively - If the trip is known to execute a
1915/// constant number of times (the condition evolves only from constants),
1916/// try to evaluate a few iterations of the loop until we get the exit
1917/// condition gets a value of ExitWhen (true or false). If we cannot
1918/// evaluate the trip count of the loop, return UnknownValue.
1919SCEVHandle ScalarEvolutionsImpl::
1920ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1921 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1922 if (PN == 0) return UnknownValue;
1923
1924 // Since the loop is canonicalized, the PHI node must have two entries. One
1925 // entry must be a constant (coming in from outside of the loop), and the
1926 // second must be derived from the same PHI.
1927 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1928 Constant *StartCST =
1929 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1930 if (StartCST == 0) return UnknownValue; // Must be a constant.
1931
1932 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1933 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1934 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1935
1936 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1937 // the loop symbolically to determine when the condition gets a value of
1938 // "ExitWhen".
1939 unsigned IterationNum = 0;
1940 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1941 for (Constant *PHIVal = StartCST;
1942 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001943 ConstantInt *CondVal =
1944 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00001945
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001946 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00001947 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001948
Reid Spencere8019bb2007-03-01 07:25:48 +00001949 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00001950 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00001951 ++NumBruteForceTripCountsComputed;
Reid Spencerc5b206b2006-12-31 05:48:39 +00001952 return SCEVConstant::get(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00001953 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001954
Chris Lattner3221ad02004-04-17 22:58:41 +00001955 // Compute the value of the PHI node for the next iteration.
1956 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1957 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00001958 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00001959 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00001960 }
1961
1962 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00001963 return UnknownValue;
1964}
1965
1966/// getSCEVAtScope - Compute the value of the specified expression within the
1967/// indicated loop (which may be null to indicate in no loop). If the
1968/// expression cannot be evaluated, return UnknownValue.
1969SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1970 // FIXME: this should be turned into a virtual method on SCEV!
1971
Chris Lattner3221ad02004-04-17 22:58:41 +00001972 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001973
Chris Lattner3221ad02004-04-17 22:58:41 +00001974 // If this instruction is evolves from a constant-evolving PHI, compute the
1975 // exit value from the loop without using SCEVs.
1976 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1977 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1978 const Loop *LI = this->LI[I->getParent()];
1979 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1980 if (PHINode *PN = dyn_cast<PHINode>(I))
1981 if (PN->getParent() == LI->getHeader()) {
1982 // Okay, there is no closed form solution for the PHI node. Check
1983 // to see if the loop that contains it has a known iteration count.
1984 // If so, we may be able to force computation of the exit value.
1985 SCEVHandle IterationCount = getIterationCount(LI);
1986 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1987 // Okay, we know how many times the containing loop executes. If
1988 // this is a constant evolving PHI node, get the final value at
1989 // the specified iteration number.
1990 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencere8019bb2007-03-01 07:25:48 +00001991 ICC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00001992 LI);
1993 if (RV) return SCEVUnknown::get(RV);
1994 }
1995 }
1996
Reid Spencer09906f32006-12-04 21:33:23 +00001997 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00001998 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00001999 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00002000 // result. This is particularly useful for computing loop exit values.
2001 if (CanConstantFold(I)) {
2002 std::vector<Constant*> Operands;
2003 Operands.reserve(I->getNumOperands());
2004 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2005 Value *Op = I->getOperand(i);
2006 if (Constant *C = dyn_cast<Constant>(Op)) {
2007 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002008 } else {
2009 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2010 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
Reid Spencerd977d862006-12-12 23:36:14 +00002011 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2012 Op->getType(),
2013 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002014 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2015 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
Reid Spencerd977d862006-12-12 23:36:14 +00002016 Operands.push_back(ConstantExpr::getIntegerCast(C,
2017 Op->getType(),
2018 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002019 else
2020 return V;
2021 } else {
2022 return V;
2023 }
2024 }
2025 }
Chris Lattner2e3a1d12007-01-30 23:52:44 +00002026 Constant *C =ConstantFoldInstOperands(I, &Operands[0], Operands.size());
2027 return SCEVUnknown::get(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002028 }
2029 }
2030
2031 // This is some other type of SCEVUnknown, just return it.
2032 return V;
2033 }
2034
Chris Lattner53e677a2004-04-02 20:23:17 +00002035 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2036 // Avoid performing the look-up in the common case where the specified
2037 // expression has no loop-variant portions.
2038 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2039 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2040 if (OpAtScope != Comm->getOperand(i)) {
2041 if (OpAtScope == UnknownValue) return UnknownValue;
2042 // Okay, at least one of these operands is loop variant but might be
2043 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002044 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002045 NewOps.push_back(OpAtScope);
2046
2047 for (++i; i != e; ++i) {
2048 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2049 if (OpAtScope == UnknownValue) return UnknownValue;
2050 NewOps.push_back(OpAtScope);
2051 }
2052 if (isa<SCEVAddExpr>(Comm))
2053 return SCEVAddExpr::get(NewOps);
2054 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
2055 return SCEVMulExpr::get(NewOps);
2056 }
2057 }
2058 // If we got here, all operands are loop invariant.
2059 return Comm;
2060 }
2061
Chris Lattner60a05cc2006-04-01 04:48:52 +00002062 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
2063 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002064 if (LHS == UnknownValue) return LHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002065 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002066 if (RHS == UnknownValue) return RHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002067 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2068 return Div; // must be loop invariant
2069 return SCEVSDivExpr::get(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002070 }
2071
2072 // If this is a loop recurrence for a loop that does not contain L, then we
2073 // are dealing with the final value computed by the loop.
2074 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2075 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2076 // To evaluate this recurrence, we need to know how many times the AddRec
2077 // loop iterates. Compute this now.
2078 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2079 if (IterationCount == UnknownValue) return UnknownValue;
2080 IterationCount = getTruncateOrZeroExtend(IterationCount,
2081 AddRec->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002082
Chris Lattner53e677a2004-04-02 20:23:17 +00002083 // If the value is affine, simplify the expression evaluation to just
2084 // Start + Step*IterationCount.
2085 if (AddRec->isAffine())
2086 return SCEVAddExpr::get(AddRec->getStart(),
2087 SCEVMulExpr::get(IterationCount,
2088 AddRec->getOperand(1)));
2089
2090 // Otherwise, evaluate it the hard way.
2091 return AddRec->evaluateAtIteration(IterationCount);
2092 }
2093 return UnknownValue;
2094 }
2095
2096 //assert(0 && "Unknown SCEV type!");
2097 return UnknownValue;
2098}
2099
2100
2101/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2102/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2103/// might be the same) or two SCEVCouldNotCompute objects.
2104///
2105static std::pair<SCEVHandle,SCEVHandle>
2106SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2107 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Reid Spencere8019bb2007-03-01 07:25:48 +00002108 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2109 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2110 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002111
Chris Lattner53e677a2004-04-02 20:23:17 +00002112 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00002113 if (!LC || !MC || !NC) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002114 SCEV *CNC = new SCEVCouldNotCompute();
2115 return std::make_pair(CNC, CNC);
2116 }
2117
Reid Spencere8019bb2007-03-01 07:25:48 +00002118 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00002119 const APInt &L = LC->getValue()->getValue();
2120 const APInt &M = MC->getValue()->getValue();
2121 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00002122 APInt Two(BitWidth, 2);
2123 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002124
Reid Spencere8019bb2007-03-01 07:25:48 +00002125 {
2126 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00002127 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00002128 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2129 // The B coefficient is M-N/2
2130 APInt B(M);
2131 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002132
Reid Spencere8019bb2007-03-01 07:25:48 +00002133 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00002134 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00002135
Reid Spencere8019bb2007-03-01 07:25:48 +00002136 // Compute the B^2-4ac term.
2137 APInt SqrtTerm(B);
2138 SqrtTerm *= B;
2139 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00002140
Reid Spencere8019bb2007-03-01 07:25:48 +00002141 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2142 // integer value or else APInt::sqrt() will assert.
2143 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002144
Reid Spencere8019bb2007-03-01 07:25:48 +00002145 // Compute the two solutions for the quadratic formula.
2146 // The divisions must be performed as signed divisions.
2147 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00002148 APInt TwoA( A << 1 );
Reid Spencere8019bb2007-03-01 07:25:48 +00002149 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2150 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002151
Reid Spencere8019bb2007-03-01 07:25:48 +00002152 return std::make_pair(SCEVUnknown::get(Solution1),
2153 SCEVUnknown::get(Solution2));
2154 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00002155}
2156
2157/// HowFarToZero - Return the number of times a backedge comparing the specified
2158/// value to zero will execute. If not computable, return UnknownValue
2159SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2160 // If the value is a constant
2161 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2162 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00002163 if (C->getValue()->isZero()) return C;
Chris Lattner53e677a2004-04-02 20:23:17 +00002164 return UnknownValue; // Otherwise it will loop infinitely.
2165 }
2166
2167 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2168 if (!AddRec || AddRec->getLoop() != L)
2169 return UnknownValue;
2170
2171 if (AddRec->isAffine()) {
2172 // If this is an affine expression the execution count of this branch is
2173 // equal to:
2174 //
2175 // (0 - Start/Step) iff Start % Step == 0
2176 //
2177 // Get the initial value for the loop.
2178 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002179 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002180 SCEVHandle Step = AddRec->getOperand(1);
2181
2182 Step = getSCEVAtScope(Step, L->getParentLoop());
2183
2184 // Figure out if Start % Step == 0.
2185 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2186 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2187 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
Chris Lattnerbac5b462005-03-09 05:34:41 +00002188 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start
Chris Lattner53e677a2004-04-02 20:23:17 +00002189 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2190 return Start; // 0 - Start/-1 == Start
2191
2192 // Check to see if Start is divisible by SC with no remainder.
2193 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2194 ConstantInt *StartCC = StartC->getValue();
2195 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
Reid Spencer0a783f72006-11-02 01:53:59 +00002196 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002197 if (Rem->isNullValue()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002198 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002199 return SCEVUnknown::get(Result);
2200 }
2201 }
2202 }
Chris Lattner42a75512007-01-15 02:27:26 +00002203 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002204 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2205 // the quadratic equation to solve it.
2206 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2207 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2208 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2209 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002210#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002211 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2212 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002213#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002214 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002215 if (ConstantInt *CB =
2216 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002217 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002218 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002219 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002220
Chris Lattner53e677a2004-04-02 20:23:17 +00002221 // We can only use this value if the chrec ends up with an exact zero
2222 // value at this index. When solving for "X*X != 5", for example, we
2223 // should not accept a root of 2.
2224 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2225 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
Reid Spencercae57542007-03-02 00:28:52 +00002226 if (EvalVal->getValue()->isZero())
Chris Lattner53e677a2004-04-02 20:23:17 +00002227 return R1; // We found a quadratic root!
2228 }
2229 }
2230 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002231
Chris Lattner53e677a2004-04-02 20:23:17 +00002232 return UnknownValue;
2233}
2234
2235/// HowFarToNonZero - Return the number of times a backedge checking the
2236/// specified value for nonzero will execute. If not computable, return
2237/// UnknownValue
2238SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2239 // Loops that look like: while (X == 0) are very strange indeed. We don't
2240 // handle them yet except for the trivial case. This could be expanded in the
2241 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002242
Chris Lattner53e677a2004-04-02 20:23:17 +00002243 // If the value is a constant, check to see if it is known to be non-zero
2244 // already. If so, the backedge will execute zero times.
2245 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2246 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002247 Constant *NonZero =
2248 ConstantExpr::getICmp(ICmpInst::ICMP_NE, C->getValue(), Zero);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002249 if (NonZero == ConstantInt::getTrue())
Chris Lattner53e677a2004-04-02 20:23:17 +00002250 return getSCEV(Zero);
2251 return UnknownValue; // Otherwise it will loop infinitely.
2252 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002253
Chris Lattner53e677a2004-04-02 20:23:17 +00002254 // We could implement others, but I really doubt anyone writes loops like
2255 // this, and if they did, they would already be constant folded.
2256 return UnknownValue;
2257}
2258
Chris Lattnerdb25de42005-08-15 23:33:51 +00002259/// HowManyLessThans - Return the number of times a backedge containing the
2260/// specified less-than comparison will execute. If not computable, return
2261/// UnknownValue.
2262SCEVHandle ScalarEvolutionsImpl::
2263HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) {
2264 // Only handle: "ADDREC < LoopInvariant".
2265 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2266
2267 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2268 if (!AddRec || AddRec->getLoop() != L)
2269 return UnknownValue;
2270
2271 if (AddRec->isAffine()) {
2272 // FORNOW: We only support unit strides.
2273 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType());
2274 if (AddRec->getOperand(1) != One)
2275 return UnknownValue;
2276
2277 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't
2278 // know that m is >= n on input to the loop. If it is, the condition return
2279 // true zero times. What we really should return, for full generality, is
2280 // SMAX(0, m-n). Since we cannot check this, we will instead check for a
2281 // canonical loop form: most do-loops will have a check that dominates the
2282 // loop, that only enters the loop if [n-1]<m. If we can find this check,
2283 // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2284
2285 // Search for the check.
2286 BasicBlock *Preheader = L->getLoopPreheader();
2287 BasicBlock *PreheaderDest = L->getHeader();
2288 if (Preheader == 0) return UnknownValue;
2289
2290 BranchInst *LoopEntryPredicate =
2291 dyn_cast<BranchInst>(Preheader->getTerminator());
2292 if (!LoopEntryPredicate) return UnknownValue;
2293
2294 // This might be a critical edge broken out. If the loop preheader ends in
2295 // an unconditional branch to the loop, check to see if the preheader has a
2296 // single predecessor, and if so, look for its terminator.
2297 while (LoopEntryPredicate->isUnconditional()) {
2298 PreheaderDest = Preheader;
2299 Preheader = Preheader->getSinglePredecessor();
2300 if (!Preheader) return UnknownValue; // Multiple preds.
2301
2302 LoopEntryPredicate =
2303 dyn_cast<BranchInst>(Preheader->getTerminator());
2304 if (!LoopEntryPredicate) return UnknownValue;
2305 }
2306
2307 // Now that we found a conditional branch that dominates the loop, check to
2308 // see if it is the comparison we are looking for.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002309 if (ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition())){
2310 Value *PreCondLHS = ICI->getOperand(0);
2311 Value *PreCondRHS = ICI->getOperand(1);
2312 ICmpInst::Predicate Cond;
2313 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2314 Cond = ICI->getPredicate();
2315 else
2316 Cond = ICI->getInversePredicate();
Chris Lattnerdb25de42005-08-15 23:33:51 +00002317
Reid Spencere4d87aa2006-12-23 06:05:41 +00002318 switch (Cond) {
2319 case ICmpInst::ICMP_UGT:
2320 std::swap(PreCondLHS, PreCondRHS);
2321 Cond = ICmpInst::ICMP_ULT;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002322 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002323 case ICmpInst::ICMP_SGT:
2324 std::swap(PreCondLHS, PreCondRHS);
2325 Cond = ICmpInst::ICMP_SLT;
2326 break;
2327 default: break;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002328 }
Chris Lattnerdb25de42005-08-15 23:33:51 +00002329
Reid Spencere4d87aa2006-12-23 06:05:41 +00002330 if (Cond == ICmpInst::ICMP_SLT) {
Chris Lattner42a75512007-01-15 02:27:26 +00002331 if (PreCondLHS->getType()->isInteger()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002332 if (RHS != getSCEV(PreCondRHS))
2333 return UnknownValue; // Not a comparison against 'm'.
2334
2335 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One)
2336 != getSCEV(PreCondLHS))
2337 return UnknownValue; // Not a comparison against 'n-1'.
2338 }
2339 else return UnknownValue;
2340 } else if (Cond == ICmpInst::ICMP_ULT)
2341 return UnknownValue;
2342
2343 // cerr << "Computed Loop Trip Count as: "
2344 // << // *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
2345 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0));
2346 }
2347 else
2348 return UnknownValue;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002349 }
2350
2351 return UnknownValue;
2352}
2353
Chris Lattner53e677a2004-04-02 20:23:17 +00002354/// getNumIterationsInRange - Return the number of iterations of this loop that
2355/// produce values in the specified constant range. Another way of looking at
2356/// this is that it returns the first iteration number where the value is not in
2357/// the condition, thus computing the exit count. If the iteration count can't
2358/// be computed, an instance of SCEVCouldNotCompute is returned.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002359SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2360 bool isSigned) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002361 if (Range.isFullSet()) // Infinite loop.
2362 return new SCEVCouldNotCompute();
2363
2364 // If the start is a non-zero constant, shift the range to simplify things.
2365 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00002366 if (!SC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002367 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Chris Lattnerb06432c2004-04-23 21:29:03 +00002368 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002369 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2370 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2371 return ShiftedAddRec->getNumIterationsInRange(
Reid Spencer581b0d42007-02-28 19:57:34 +00002372 Range.subtract(SC->getValue()->getValue()),isSigned);
Chris Lattner53e677a2004-04-02 20:23:17 +00002373 // This is strange and shouldn't happen.
2374 return new SCEVCouldNotCompute();
2375 }
2376
2377 // The only time we can solve this is when we have all constant indices.
2378 // Otherwise, we cannot determine the overflow conditions.
2379 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2380 if (!isa<SCEVConstant>(getOperand(i)))
2381 return new SCEVCouldNotCompute();
2382
2383
2384 // Okay at this point we know that all elements of the chrec are constants and
2385 // that the start element is zero.
2386
2387 // First check to see if the range contains zero. If not, the first
2388 // iteration exits.
Reid Spencera6e8a952007-03-01 07:54:15 +00002389 if (!Range.contains(APInt(getBitWidth(),0)))
Reid Spencer581b0d42007-02-28 19:57:34 +00002390 return SCEVConstant::get(ConstantInt::get(getType(),0));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002391
Chris Lattner53e677a2004-04-02 20:23:17 +00002392 if (isAffine()) {
2393 // If this is an affine expression then we have this situation:
2394 // Solve {0,+,A} in Range === Ax in Range
2395
2396 // Since we know that zero is in the range, we know that the upper value of
2397 // the range must be the first possible exit value. Also note that we
2398 // already checked for a full range.
Reid Spencer581b0d42007-02-28 19:57:34 +00002399 const APInt &Upper = Range.getUpper();
2400 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2401 APInt One(getBitWidth(),1);
Chris Lattner53e677a2004-04-02 20:23:17 +00002402
2403 // The exit value should be (Upper+A-1)/A.
Reid Spencer581b0d42007-02-28 19:57:34 +00002404 APInt ExitVal(Upper);
2405 if (A != One)
2406 ExitVal = (Upper + A - One).sdiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00002407 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002408
2409 // Evaluate at the exit value. If we really did fall out of the valid
2410 // range, then we computed our trip count, otherwise wrap around or other
2411 // things must have happened.
2412 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
Reid Spencera6e8a952007-03-01 07:54:15 +00002413 if (Range.contains(Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002414 return new SCEVCouldNotCompute(); // Something strange happened
2415
2416 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00002417 assert(Range.contains(
2418 EvaluateConstantChrecAtConstant(this,
Reid Spencerc7cd7a02007-03-01 19:32:33 +00002419 ConstantInt::get(ExitVal - One))->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002420 "Linear scev computation is off in a bad way!");
2421 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2422 } else if (isQuadratic()) {
2423 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2424 // quadratic equation to solve it. To do this, we must frame our problem in
2425 // terms of figuring out when zero is crossed, instead of when
2426 // Range.getUpper() is crossed.
2427 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Reid Spencer581b0d42007-02-28 19:57:34 +00002428 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(
Reid Spencerc7cd7a02007-03-01 19:32:33 +00002429 ConstantInt::get(Range.getUpper())));
Chris Lattner53e677a2004-04-02 20:23:17 +00002430 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2431
2432 // Next, solve the constructed addrec
2433 std::pair<SCEVHandle,SCEVHandle> Roots =
2434 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2435 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2436 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2437 if (R1) {
2438 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002439 if (ConstantInt *CB =
2440 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002441 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002442 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002443 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002444
Chris Lattner53e677a2004-04-02 20:23:17 +00002445 // Make sure the root is not off by one. The returned iteration should
2446 // not be in the range, but the previous one should be. When solving
2447 // for "X*X < 5", for example, we should not return a root of 2.
2448 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2449 R1->getValue());
Reid Spencera6e8a952007-03-01 07:54:15 +00002450 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002451 // The next iteration must be out of the range...
Zhou Shengfdc1e162007-04-07 17:40:57 +00002452 Constant *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002453
Chris Lattner53e677a2004-04-02 20:23:17 +00002454 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
Reid Spencera6e8a952007-03-01 07:54:15 +00002455 if (!Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002456 return SCEVUnknown::get(NextVal);
2457 return new SCEVCouldNotCompute(); // Something strange happened
2458 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002459
Chris Lattner53e677a2004-04-02 20:23:17 +00002460 // If R1 was not in the range, then it is a good return value. Make
2461 // sure that R1-1 WAS in the range though, just in case.
Zhou Shengfdc1e162007-04-07 17:40:57 +00002462 Constant *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Chris Lattner53e677a2004-04-02 20:23:17 +00002463 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
Reid Spencera6e8a952007-03-01 07:54:15 +00002464 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002465 return R1;
2466 return new SCEVCouldNotCompute(); // Something strange happened
2467 }
2468 }
2469 }
2470
2471 // Fallback, if this is a general polynomial, figure out the progression
2472 // through brute force: evaluate until we find an iteration that fails the
2473 // test. This is likely to be slow, but getting an accurate trip count is
2474 // incredibly important, we will be able to simplify the exit test a lot, and
2475 // we are almost guaranteed to get a trip count in this case.
2476 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00002477 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2478 do {
2479 ++NumBruteForceEvaluations;
2480 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2481 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2482 return new SCEVCouldNotCompute();
2483
2484 // Check to see if we found the value!
Reid Spencera6e8a952007-03-01 07:54:15 +00002485 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002486 return SCEVConstant::get(TestVal);
2487
2488 // Increment to test the next index.
Zhou Shengfdc1e162007-04-07 17:40:57 +00002489 TestVal = ConstantInt::get(TestVal->getValue()+1);
Chris Lattner53e677a2004-04-02 20:23:17 +00002490 } while (TestVal != EndVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002491
Chris Lattner53e677a2004-04-02 20:23:17 +00002492 return new SCEVCouldNotCompute();
2493}
2494
2495
2496
2497//===----------------------------------------------------------------------===//
2498// ScalarEvolution Class Implementation
2499//===----------------------------------------------------------------------===//
2500
2501bool ScalarEvolution::runOnFunction(Function &F) {
2502 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2503 return false;
2504}
2505
2506void ScalarEvolution::releaseMemory() {
2507 delete (ScalarEvolutionsImpl*)Impl;
2508 Impl = 0;
2509}
2510
2511void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2512 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00002513 AU.addRequiredTransitive<LoopInfo>();
2514}
2515
2516SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2517 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2518}
2519
Chris Lattnera0740fb2005-08-09 23:36:33 +00002520/// hasSCEV - Return true if the SCEV for this value has already been
2521/// computed.
2522bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00002523 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00002524}
2525
2526
2527/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2528/// the specified value.
2529void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2530 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2531}
2532
2533
Chris Lattner53e677a2004-04-02 20:23:17 +00002534SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2535 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2536}
2537
2538bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2539 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2540}
2541
2542SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2543 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2544}
2545
2546void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2547 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2548}
2549
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002550static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00002551 const Loop *L) {
2552 // Print all inner loops first
2553 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2554 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002555
Bill Wendlinge8156192006-12-07 01:30:32 +00002556 cerr << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002557
2558 std::vector<BasicBlock*> ExitBlocks;
2559 L->getExitBlocks(ExitBlocks);
2560 if (ExitBlocks.size() != 1)
Bill Wendlinge8156192006-12-07 01:30:32 +00002561 cerr << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002562
2563 if (SE->hasLoopInvariantIterationCount(L)) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002564 cerr << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002565 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +00002566 cerr << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002567 }
2568
Bill Wendlinge8156192006-12-07 01:30:32 +00002569 cerr << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00002570}
2571
Reid Spencerce9653c2004-12-07 04:03:45 +00002572void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002573 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2574 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2575
2576 OS << "Classifying expressions for: " << F.getName() << "\n";
2577 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner42a75512007-01-15 02:27:26 +00002578 if (I->getType()->isInteger()) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00002579 OS << *I;
Chris Lattner53e677a2004-04-02 20:23:17 +00002580 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002581 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00002582 SV->print(OS);
2583 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002584
Chris Lattner42a75512007-01-15 02:27:26 +00002585 if ((*I).getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002586 ConstantRange Bounds = SV->getValueRange();
2587 if (!Bounds.isFullSet())
2588 OS << "Bounds: " << Bounds << " ";
2589 }
2590
Chris Lattner6ffe5512004-04-27 15:13:33 +00002591 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002592 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002593 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002594 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2595 OS << "<<Unknown>>";
2596 } else {
2597 OS << *ExitValue;
2598 }
2599 }
2600
2601
2602 OS << "\n";
2603 }
2604
2605 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2606 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2607 PrintLoopInfo(OS, this, *I);
2608}
2609