blob: 32e9e96a6d8acc275590f791631ae8b973a94764 [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
17// can handle. These classes are reference counted, managed by the SCEVHandle
18// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000031//
Chris Lattner53e677a2004-04-02 20:23:17 +000032// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
Chris Lattner53e677a2004-04-02 20:23:17 +000036// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
Chris Lattner3b27d682006-12-19 22:30:33 +000062#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000063#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000064#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000066#include "llvm/GlobalVariable.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
John Criswella1156432005-10-27 15:54:34 +000068#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000069#include "llvm/Analysis/LoopInfo.h"
70#include "llvm/Assembly/Writer.h"
71#include "llvm/Transforms/Scalar.h"
72#include "llvm/Support/CFG.h"
Chris Lattner95255282006-06-28 23:17:24 +000073#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000074#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000075#include "llvm/Support/ConstantRange.h"
76#include "llvm/Support/InstIterator.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000077#include "llvm/Support/ManagedStatic.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000078#include "llvm/Support/MathExtras.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000079#include "llvm/Support/Streams.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000080#include "llvm/ADT/Statistic.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000081#include <ostream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000082#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000083#include <cmath>
Chris Lattner53e677a2004-04-02 20:23:17 +000084using namespace llvm;
85
Chris Lattner3b27d682006-12-19 22:30:33 +000086STATISTIC(NumBruteForceEvaluations,
87 "Number of brute force evaluations needed to "
88 "calculate high-order polynomial exit values");
89STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
97
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>
Devang Patel4f4c28f2008-03-20 02:25:21 +0000106 R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Chris Lattner53e677a2004-04-02 20:23:17 +0000107}
Devang Patel19974732007-05-03 01:11:54 +0000108char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000109
110//===----------------------------------------------------------------------===//
111// SCEV class definitions
112//===----------------------------------------------------------------------===//
113
114//===----------------------------------------------------------------------===//
115// Implementation of the SCEV class.
116//
Chris Lattner53e677a2004-04-02 20:23:17 +0000117SCEV::~SCEV() {}
118void SCEV::dump() const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000119 print(cerr);
Chris Lattner53e677a2004-04-02 20:23:17 +0000120}
121
122/// getValueRange - Return the tightest constant bounds that this value is
123/// known to have. This method is only valid on integer SCEV objects.
124ConstantRange SCEV::getValueRange() const {
125 const Type *Ty = getType();
Chris Lattner42a75512007-01-15 02:27:26 +0000126 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000127 // Default to a full range if no better information is available.
Reid Spencerc6aedf72007-02-28 22:03:51 +0000128 return ConstantRange(getBitWidth());
Chris Lattner53e677a2004-04-02 20:23:17 +0000129}
130
Reid Spencer581b0d42007-02-28 19:57:34 +0000131uint32_t SCEV::getBitWidth() const {
132 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
133 return ITy->getBitWidth();
134 return 0;
135}
136
Chris Lattner53e677a2004-04-02 20:23:17 +0000137
138SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
139
140bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000142 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000143}
144
145const Type *SCEVCouldNotCompute::getType() const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000147 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000148}
149
150bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
151 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
152 return false;
153}
154
Chris Lattner4dc534c2005-02-13 04:37:18 +0000155SCEVHandle SCEVCouldNotCompute::
156replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000157 const SCEVHandle &Conc,
158 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000159 return this;
160}
161
Chris Lattner53e677a2004-04-02 20:23:17 +0000162void SCEVCouldNotCompute::print(std::ostream &OS) const {
163 OS << "***COULDNOTCOMPUTE***";
164}
165
166bool SCEVCouldNotCompute::classof(const SCEV *S) {
167 return S->getSCEVType() == scCouldNotCompute;
168}
169
170
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000171// SCEVConstants - Only allow the creation of one SCEVConstant for any
172// particular value. Don't use a SCEVHandle here, or else the object will
173// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000174static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000175
Chris Lattner53e677a2004-04-02 20:23:17 +0000176
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000177SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000178 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000179}
Chris Lattner53e677a2004-04-02 20:23:17 +0000180
Dan Gohman246b2562007-10-22 18:31:58 +0000181SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Chris Lattnerb3364092006-10-04 21:49:37 +0000182 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000183 if (R == 0) R = new SCEVConstant(V);
184 return R;
185}
Chris Lattner53e677a2004-04-02 20:23:17 +0000186
Dan Gohman246b2562007-10-22 18:31:58 +0000187SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
188 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000189}
190
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000191ConstantRange SCEVConstant::getValueRange() const {
Reid Spencerdc5c1592007-02-28 18:57:32 +0000192 return ConstantRange(V->getValue());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000193}
Chris Lattner53e677a2004-04-02 20:23:17 +0000194
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000195const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000196
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000197void SCEVConstant::print(std::ostream &OS) const {
198 WriteAsOperand(OS, V, false);
199}
Chris Lattner53e677a2004-04-02 20:23:17 +0000200
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000201// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
202// particular input. Don't use a SCEVHandle here, or else the object will
203// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000204static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
205 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000206
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000207SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
208 : SCEV(scTruncate), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000209 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000210 "Cannot truncate non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000211 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
212 && "This is not a truncating conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000213}
Chris Lattner53e677a2004-04-02 20:23:17 +0000214
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000215SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000216 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000217}
Chris Lattner53e677a2004-04-02 20:23:17 +0000218
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219ConstantRange SCEVTruncateExpr::getValueRange() const {
Reid Spencerc6aedf72007-02-28 22:03:51 +0000220 return getOperand()->getValueRange().truncate(getBitWidth());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000221}
Chris Lattner53e677a2004-04-02 20:23:17 +0000222
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000223void SCEVTruncateExpr::print(std::ostream &OS) const {
224 OS << "(truncate " << *Op << " to " << *Ty << ")";
225}
226
227// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
228// particular input. Don't use a SCEVHandle here, or else the object will never
229// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000230static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
231 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000232
233SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000234 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000235 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000236 "Cannot zero extend non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000237 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
238 && "This is not an extending conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000239}
240
241SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000242 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000243}
244
245ConstantRange SCEVZeroExtendExpr::getValueRange() const {
Reid Spencerc6aedf72007-02-28 22:03:51 +0000246 return getOperand()->getValueRange().zeroExtend(getBitWidth());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000247}
248
249void SCEVZeroExtendExpr::print(std::ostream &OS) const {
250 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
251}
252
Dan Gohmand19534a2007-06-15 14:38:12 +0000253// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
254// particular input. Don't use a SCEVHandle here, or else the object will never
255// be deleted!
256static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
257 SCEVSignExtendExpr*> > SCEVSignExtends;
258
259SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
260 : SCEV(scSignExtend), Op(op), Ty(ty) {
261 assert(Op->getType()->isInteger() && Ty->isInteger() &&
262 "Cannot sign extend non-integer value!");
263 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
264 && "This is not an extending conversion!");
265}
266
267SCEVSignExtendExpr::~SCEVSignExtendExpr() {
268 SCEVSignExtends->erase(std::make_pair(Op, Ty));
269}
270
271ConstantRange SCEVSignExtendExpr::getValueRange() const {
272 return getOperand()->getValueRange().signExtend(getBitWidth());
273}
274
275void SCEVSignExtendExpr::print(std::ostream &OS) const {
276 OS << "(signextend " << *Op << " to " << *Ty << ")";
277}
278
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000279// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
280// particular input. Don't use a SCEVHandle here, or else the object will never
281// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000282static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
283 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000284
285SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000286 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
287 std::vector<SCEV*>(Operands.begin(),
288 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000289}
290
291void SCEVCommutativeExpr::print(std::ostream &OS) const {
292 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
293 const char *OpStr = getOperationStr();
294 OS << "(" << *Operands[0];
295 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
296 OS << OpStr << *Operands[i];
297 OS << ")";
298}
299
Chris Lattner4dc534c2005-02-13 04:37:18 +0000300SCEVHandle SCEVCommutativeExpr::
301replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000302 const SCEVHandle &Conc,
303 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000304 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000305 SCEVHandle H =
306 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000307 if (H != getOperand(i)) {
308 std::vector<SCEVHandle> NewOps;
309 NewOps.reserve(getNumOperands());
310 for (unsigned j = 0; j != i; ++j)
311 NewOps.push_back(getOperand(j));
312 NewOps.push_back(H);
313 for (++i; i != e; ++i)
314 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000315 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000316
317 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000318 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000319 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000320 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000321 else if (isa<SCEVSMaxExpr>(this))
322 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000323 else if (isa<SCEVUMaxExpr>(this))
324 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000325 else
326 assert(0 && "Unknown commutative expr!");
327 }
328 }
329 return this;
330}
331
332
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000333// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000334// input. Don't use a SCEVHandle here, or else the object will never be
335// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000336static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000337 SCEVUDivExpr*> > SCEVUDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000338
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000339SCEVUDivExpr::~SCEVUDivExpr() {
340 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000341}
342
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000343void SCEVUDivExpr::print(std::ostream &OS) const {
344 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000345}
346
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000347const Type *SCEVUDivExpr::getType() const {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000348 return LHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000349}
350
351// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
352// particular input. Don't use a SCEVHandle here, or else the object will never
353// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000354static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
355 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000356
357SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000358 SCEVAddRecExprs->erase(std::make_pair(L,
359 std::vector<SCEV*>(Operands.begin(),
360 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000361}
362
Chris Lattner4dc534c2005-02-13 04:37:18 +0000363SCEVHandle SCEVAddRecExpr::
364replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000365 const SCEVHandle &Conc,
366 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000367 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000368 SCEVHandle H =
369 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000370 if (H != getOperand(i)) {
371 std::vector<SCEVHandle> NewOps;
372 NewOps.reserve(getNumOperands());
373 for (unsigned j = 0; j != i; ++j)
374 NewOps.push_back(getOperand(j));
375 NewOps.push_back(H);
376 for (++i; i != e; ++i)
377 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000378 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000379
Dan Gohman246b2562007-10-22 18:31:58 +0000380 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000381 }
382 }
383 return this;
384}
385
386
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000387bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
388 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000389 // contain L and if the start is invariant.
390 return !QueryLoop->contains(L->getHeader()) &&
391 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000392}
393
394
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000395void SCEVAddRecExpr::print(std::ostream &OS) const {
396 OS << "{" << *Operands[0];
397 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
398 OS << ",+," << *Operands[i];
399 OS << "}<" << L->getHeader()->getName() + ">";
400}
Chris Lattner53e677a2004-04-02 20:23:17 +0000401
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000402// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
403// value. Don't use a SCEVHandle here, or else the object will never be
404// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000405static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000406
Chris Lattnerb3364092006-10-04 21:49:37 +0000407SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000408
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000409bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
410 // All non-instruction values are loop invariant. All instructions are loop
411 // invariant if they are not contained in the specified loop.
412 if (Instruction *I = dyn_cast<Instruction>(V))
413 return !L->contains(I->getParent());
414 return true;
415}
Chris Lattner53e677a2004-04-02 20:23:17 +0000416
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000417const Type *SCEVUnknown::getType() const {
418 return V->getType();
419}
Chris Lattner53e677a2004-04-02 20:23:17 +0000420
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000421void SCEVUnknown::print(std::ostream &OS) const {
422 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000423}
424
Chris Lattner8d741b82004-06-20 06:23:15 +0000425//===----------------------------------------------------------------------===//
426// SCEV Utilities
427//===----------------------------------------------------------------------===//
428
429namespace {
430 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
431 /// than the complexity of the RHS. This comparator is used to canonicalize
432 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000433 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000434 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Chris Lattner8d741b82004-06-20 06:23:15 +0000435 return LHS->getSCEVType() < RHS->getSCEVType();
436 }
437 };
438}
439
440/// GroupByComplexity - Given a list of SCEV objects, order them by their
441/// complexity, and group objects of the same complexity together by value.
442/// When this routine is finished, we know that any duplicates in the vector are
443/// consecutive and that complexity is monotonically increasing.
444///
445/// Note that we go take special precautions to ensure that we get determinstic
446/// results from this routine. In other words, we don't want the results of
447/// this to depend on where the addresses of various SCEV objects happened to
448/// land in memory.
449///
450static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
451 if (Ops.size() < 2) return; // Noop
452 if (Ops.size() == 2) {
453 // This is the common case, which also happens to be trivially simple.
454 // Special case it.
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000455 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000456 std::swap(Ops[0], Ops[1]);
457 return;
458 }
459
460 // Do the rough sort by complexity.
461 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
462
463 // Now that we are sorted by complexity, group elements of the same
464 // complexity. Note that this is, at worst, N^2, but the vector is likely to
465 // be extremely short in practice. Note that we take this approach because we
466 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000467 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000468 SCEV *S = Ops[i];
469 unsigned Complexity = S->getSCEVType();
470
471 // If there are any objects of the same complexity and same value as this
472 // one, group them.
473 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
474 if (Ops[j] == S) { // Found a duplicate.
475 // Move it to immediately after i'th element.
476 std::swap(Ops[i+1], Ops[j]);
477 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000478 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000479 }
480 }
481 }
482}
483
Chris Lattner53e677a2004-04-02 20:23:17 +0000484
Chris Lattner53e677a2004-04-02 20:23:17 +0000485
486//===----------------------------------------------------------------------===//
487// Simple SCEV method implementations
488//===----------------------------------------------------------------------===//
489
490/// getIntegerSCEV - Given an integer or FP type, create a constant for the
491/// specified signed integer value and return a SCEV for the constant.
Dan Gohman246b2562007-10-22 18:31:58 +0000492SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000493 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000494 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000495 C = Constant::getNullValue(Ty);
496 else if (Ty->isFloatingPoint())
Chris Lattner02a260a2008-04-20 00:41:09 +0000497 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
498 APFloat::IEEEdouble, Val));
Reid Spencere4d87aa2006-12-23 06:05:41 +0000499 else
Reid Spencerb83eb642006-10-20 07:07:24 +0000500 C = ConstantInt::get(Ty, Val);
Dan Gohman246b2562007-10-22 18:31:58 +0000501 return getUnknown(C);
Chris Lattner53e677a2004-04-02 20:23:17 +0000502}
503
504/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
505/// input value to the specified type. If the type must be extended, it is zero
506/// extended.
Dan Gohman246b2562007-10-22 18:31:58 +0000507static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty,
508 ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000509 const Type *SrcTy = V->getType();
Chris Lattner42a75512007-01-15 02:27:26 +0000510 assert(SrcTy->isInteger() && Ty->isInteger() &&
Chris Lattner53e677a2004-04-02 20:23:17 +0000511 "Cannot truncate or zero extend with non-integer arguments!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000512 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
Chris Lattner53e677a2004-04-02 20:23:17 +0000513 return V; // No conversion
Reid Spencere7ca0422007-01-08 01:26:33 +0000514 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
Dan Gohman246b2562007-10-22 18:31:58 +0000515 return SE.getTruncateExpr(V, Ty);
516 return SE.getZeroExtendExpr(V, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000517}
518
519/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
520///
Dan Gohman246b2562007-10-22 18:31:58 +0000521SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000522 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman246b2562007-10-22 18:31:58 +0000523 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000524
Nick Lewycky178f20a2008-02-20 06:58:55 +0000525 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
Nick Lewycky3e630762008-02-20 06:48:22 +0000526}
527
528/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
529SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
530 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
531 return getUnknown(ConstantExpr::getNot(VC->getValue()));
532
Nick Lewycky178f20a2008-02-20 06:58:55 +0000533 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
Nick Lewycky3e630762008-02-20 06:48:22 +0000534 return getMinusSCEV(AllOnes, V);
Chris Lattner53e677a2004-04-02 20:23:17 +0000535}
536
537/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
538///
Dan Gohman246b2562007-10-22 18:31:58 +0000539SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
540 const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000541 // X - Y --> X + -Y
Dan Gohman246b2562007-10-22 18:31:58 +0000542 return getAddExpr(LHS, getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000543}
544
545
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000546/// BinomialCoefficient - Compute BC(It, K). The result is of the same type as
547/// It. Assume, K > 0.
548static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
549 ScalarEvolution &SE) {
550 // We are using the following formula for BC(It, K):
551 //
552 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
553 //
554 // Suppose, W is the bitwidth of It (and of the return value as well). We
555 // must be prepared for overflow. Hence, we must assure that the result of
556 // our computation is equal to the accurate one modulo 2^W. Unfortunately,
557 // division isn't safe in modular arithmetic. This means we must perform the
558 // whole computation accurately and then truncate the result to W bits.
559 //
560 // The dividend of the formula is a multiplication of K integers of bitwidth
561 // W. K*W bits suffice to compute it accurately.
562 //
563 // FIXME: We assume the divisor can be accurately computed using 16-bit
564 // unsigned integer type. It is true up to K = 8 (AddRecs of length 9). In
565 // future we may use APInt to use the minimum number of bits necessary to
566 // compute it accurately.
567 //
568 // It is safe to use unsigned division here: the dividend is nonnegative and
569 // the divisor is positive.
570
571 // Handle the simplest case efficiently.
572 if (K == 1)
573 return It;
574
575 assert(K < 9 && "We cannot handle such long AddRecs yet.");
576
577 // FIXME: A temporary hack to remove in future. Arbitrary precision integers
578 // aren't supported by the code generator yet. For the dividend, the bitwidth
579 // we use is the smallest power of 2 greater or equal to K*W and less or equal
580 // to 64. Note that setting the upper bound for bitwidth may still lead to
581 // miscompilation in some cases.
582 unsigned DividendBits = 1U << Log2_32_Ceil(K * It->getBitWidth());
583 if (DividendBits > 64)
584 DividendBits = 64;
585#if 0 // Waiting for the APInt support in the code generator...
586 unsigned DividendBits = K * It->getBitWidth();
587#endif
588
589 const IntegerType *DividendTy = IntegerType::get(DividendBits);
590 const SCEVHandle ExIt = SE.getZeroExtendExpr(It, DividendTy);
591
592 // The final number of bits we need to perform the division is the maximum of
593 // dividend and divisor bitwidths.
594 const IntegerType *DivisionTy =
595 IntegerType::get(std::max(DividendBits, 16U));
596
597 // Compute K! We know K >= 2 here.
598 unsigned F = 2;
599 for (unsigned i = 3; i <= K; ++i)
600 F *= i;
601 APInt Divisor(DivisionTy->getBitWidth(), F);
602
Chris Lattner53e677a2004-04-02 20:23:17 +0000603 // Handle this case efficiently, it is common to have constant iteration
604 // counts while computing loop exit values.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000605 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(ExIt)) {
606 const APInt& N = SC->getValue()->getValue();
607 APInt Dividend(N.getBitWidth(), 1);
608 for (; K; --K)
609 Dividend *= N-(K-1);
610 if (DividendTy != DivisionTy)
611 Dividend = Dividend.zext(DivisionTy->getBitWidth());
612 return SE.getConstant(Dividend.udiv(Divisor).trunc(It->getBitWidth()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000613 }
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000614
615 SCEVHandle Dividend = ExIt;
616 for (unsigned i = 1; i != K; ++i)
617 Dividend =
618 SE.getMulExpr(Dividend,
619 SE.getMinusSCEV(ExIt, SE.getIntegerSCEV(i, DividendTy)));
620 if (DividendTy != DivisionTy)
621 Dividend = SE.getZeroExtendExpr(Dividend, DivisionTy);
622 return
623 SE.getTruncateExpr(SE.getUDivExpr(Dividend, SE.getConstant(Divisor)),
624 It->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +0000625}
626
Chris Lattner53e677a2004-04-02 20:23:17 +0000627/// evaluateAtIteration - Return the value of this chain of recurrences at
628/// the specified iteration number. We can evaluate this recurrence by
629/// multiplying each element in the chain by the binomial coefficient
630/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
631///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000632/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000633///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000634/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000635///
Dan Gohman246b2562007-10-22 18:31:58 +0000636SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
637 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000638 SCEVHandle Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000639 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000640 // The computation is correct in the face of overflow provided that the
641 // multiplication is performed _after_ the evaluation of the binomial
642 // coefficient.
643 SCEVHandle Val = SE.getMulExpr(getOperand(i),
644 BinomialCoefficient(It, i, SE));
Dan Gohman246b2562007-10-22 18:31:58 +0000645 Result = SE.getAddExpr(Result, Val);
Chris Lattner53e677a2004-04-02 20:23:17 +0000646 }
647 return Result;
648}
649
Chris Lattner53e677a2004-04-02 20:23:17 +0000650//===----------------------------------------------------------------------===//
651// SCEV Expression folder implementations
652//===----------------------------------------------------------------------===//
653
Dan Gohman246b2562007-10-22 18:31:58 +0000654SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000655 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000656 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000657 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000658
659 // If the input value is a chrec scev made out of constants, truncate
660 // all of the constants.
661 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
662 std::vector<SCEVHandle> Operands;
663 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
664 // FIXME: This should allow truncation of other expression types!
665 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman246b2562007-10-22 18:31:58 +0000666 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000667 else
668 break;
669 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman246b2562007-10-22 18:31:58 +0000670 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000671 }
672
Chris Lattnerb3364092006-10-04 21:49:37 +0000673 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000674 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
675 return Result;
676}
677
Dan Gohman246b2562007-10-22 18:31:58 +0000678SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000679 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000680 return getUnknown(
Reid Spencerd977d862006-12-12 23:36:14 +0000681 ConstantExpr::getZExt(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000682
683 // FIXME: If the input value is a chrec scev, and we can prove that the value
684 // did not overflow the old, smaller, value, we can zero extend all of the
685 // operands (often constants). This would allow analysis of something like
686 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
687
Chris Lattnerb3364092006-10-04 21:49:37 +0000688 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000689 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
690 return Result;
691}
692
Dan Gohman246b2562007-10-22 18:31:58 +0000693SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmand19534a2007-06-15 14:38:12 +0000694 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000695 return getUnknown(
Dan Gohmand19534a2007-06-15 14:38:12 +0000696 ConstantExpr::getSExt(SC->getValue(), Ty));
697
698 // FIXME: If the input value is a chrec scev, and we can prove that the value
699 // did not overflow the old, smaller, value, we can sign extend all of the
700 // operands (often constants). This would allow analysis of something like
701 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
702
703 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
704 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
705 return Result;
706}
707
Chris Lattner53e677a2004-04-02 20:23:17 +0000708// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman246b2562007-10-22 18:31:58 +0000709SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000710 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000711 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000712
713 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000714 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000715
716 // If there are any constants, fold them together.
717 unsigned Idx = 0;
718 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
719 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000720 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000721 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
722 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000723 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
724 RHSC->getValue()->getValue());
725 Ops[0] = getConstant(Fold);
726 Ops.erase(Ops.begin()+1); // Erase the folded element
727 if (Ops.size() == 1) return Ops[0];
728 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000729 }
730
731 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +0000732 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000733 Ops.erase(Ops.begin());
734 --Idx;
735 }
736 }
737
Chris Lattner627018b2004-04-07 16:16:11 +0000738 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000739
Chris Lattner53e677a2004-04-02 20:23:17 +0000740 // Okay, check to see if the same value occurs in the operand list twice. If
741 // so, merge them together into an multiply expression. Since we sorted the
742 // list, these values are required to be adjacent.
743 const Type *Ty = Ops[0]->getType();
744 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
745 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
746 // Found a match, merge the two values into a multiply, and add any
747 // remaining values to the result.
Dan Gohman246b2562007-10-22 18:31:58 +0000748 SCEVHandle Two = getIntegerSCEV(2, Ty);
749 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +0000750 if (Ops.size() == 2)
751 return Mul;
752 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
753 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +0000754 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000755 }
756
Dan Gohmanf50cd742007-06-18 19:30:09 +0000757 // Now we know the first non-constant operand. Skip past any cast SCEVs.
758 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
759 ++Idx;
760
761 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +0000762 if (Idx < Ops.size()) {
763 bool DeletedAdd = false;
764 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
765 // If we have an add, expand the add operands onto the end of the operands
766 // list.
767 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
768 Ops.erase(Ops.begin()+Idx);
769 DeletedAdd = true;
770 }
771
772 // If we deleted at least one add, we added operands to the end of the list,
773 // and they are not necessarily sorted. Recurse to resort and resimplify
774 // any operands we just aquired.
775 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +0000776 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000777 }
778
779 // Skip over the add expression until we get to a multiply.
780 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
781 ++Idx;
782
783 // If we are adding something to a multiply expression, make sure the
784 // something is not already an operand of the multiply. If so, merge it into
785 // the multiply.
786 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
787 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
788 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
789 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
790 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000791 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000792 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
793 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
794 if (Mul->getNumOperands() != 2) {
795 // If the multiply has more than two operands, we must get the
796 // Y*Z term.
797 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
798 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000799 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000800 }
Dan Gohman246b2562007-10-22 18:31:58 +0000801 SCEVHandle One = getIntegerSCEV(1, Ty);
802 SCEVHandle AddOne = getAddExpr(InnerMul, One);
803 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000804 if (Ops.size() == 2) return OuterMul;
805 if (AddOp < Idx) {
806 Ops.erase(Ops.begin()+AddOp);
807 Ops.erase(Ops.begin()+Idx-1);
808 } else {
809 Ops.erase(Ops.begin()+Idx);
810 Ops.erase(Ops.begin()+AddOp-1);
811 }
812 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000813 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000814 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000815
Chris Lattner53e677a2004-04-02 20:23:17 +0000816 // Check this multiply against other multiplies being added together.
817 for (unsigned OtherMulIdx = Idx+1;
818 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
819 ++OtherMulIdx) {
820 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
821 // If MulOp occurs in OtherMul, we can fold the two multiplies
822 // together.
823 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
824 OMulOp != e; ++OMulOp)
825 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
826 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
827 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
828 if (Mul->getNumOperands() != 2) {
829 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
830 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000831 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000832 }
833 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
834 if (OtherMul->getNumOperands() != 2) {
835 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
836 OtherMul->op_end());
837 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000838 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000839 }
Dan Gohman246b2562007-10-22 18:31:58 +0000840 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
841 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +0000842 if (Ops.size() == 2) return OuterMul;
843 Ops.erase(Ops.begin()+Idx);
844 Ops.erase(Ops.begin()+OtherMulIdx-1);
845 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000846 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000847 }
848 }
849 }
850 }
851
852 // If there are any add recurrences in the operands list, see if any other
853 // added values are loop invariant. If so, we can fold them into the
854 // recurrence.
855 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
856 ++Idx;
857
858 // Scan over all recurrences, trying to fold loop invariants into them.
859 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
860 // Scan all of the other operands to this add and add them to the vector if
861 // they are loop invariant w.r.t. the recurrence.
862 std::vector<SCEVHandle> LIOps;
863 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
864 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
865 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
866 LIOps.push_back(Ops[i]);
867 Ops.erase(Ops.begin()+i);
868 --i; --e;
869 }
870
871 // If we found some loop invariants, fold them into the recurrence.
872 if (!LIOps.empty()) {
873 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
874 LIOps.push_back(AddRec->getStart());
875
876 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +0000877 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000878
Dan Gohman246b2562007-10-22 18:31:58 +0000879 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000880 // If all of the other operands were loop invariant, we are done.
881 if (Ops.size() == 1) return NewRec;
882
883 // Otherwise, add the folded AddRec by the non-liv parts.
884 for (unsigned i = 0;; ++i)
885 if (Ops[i] == AddRec) {
886 Ops[i] = NewRec;
887 break;
888 }
Dan Gohman246b2562007-10-22 18:31:58 +0000889 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000890 }
891
892 // Okay, if there weren't any loop invariants to be folded, check to see if
893 // there are multiple AddRec's with the same loop induction variable being
894 // added together. If so, we can fold them.
895 for (unsigned OtherIdx = Idx+1;
896 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
897 if (OtherIdx != Idx) {
898 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
899 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
900 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
901 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
902 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
903 if (i >= NewOps.size()) {
904 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
905 OtherAddRec->op_end());
906 break;
907 }
Dan Gohman246b2562007-10-22 18:31:58 +0000908 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +0000909 }
Dan Gohman246b2562007-10-22 18:31:58 +0000910 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000911
912 if (Ops.size() == 2) return NewAddRec;
913
914 Ops.erase(Ops.begin()+Idx);
915 Ops.erase(Ops.begin()+OtherIdx-1);
916 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +0000917 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000918 }
919 }
920
921 // Otherwise couldn't fold anything into this recurrence. Move onto the
922 // next one.
923 }
924
925 // Okay, it looks like we really DO need an add expr. Check to see if we
926 // already have one, otherwise create a new one.
927 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000928 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
929 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000930 if (Result == 0) Result = new SCEVAddExpr(Ops);
931 return Result;
932}
933
934
Dan Gohman246b2562007-10-22 18:31:58 +0000935SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000936 assert(!Ops.empty() && "Cannot get empty mul!");
937
938 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000939 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000940
941 // If there are any constants, fold them together.
942 unsigned Idx = 0;
943 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
944
945 // C1*(C2+V) -> C1*C2 + C1*V
946 if (Ops.size() == 2)
947 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
948 if (Add->getNumOperands() == 2 &&
949 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +0000950 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
951 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000952
953
954 ++Idx;
955 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
956 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000957 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
958 RHSC->getValue()->getValue());
959 Ops[0] = getConstant(Fold);
960 Ops.erase(Ops.begin()+1); // Erase the folded element
961 if (Ops.size() == 1) return Ops[0];
962 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000963 }
964
965 // If we are left with a constant one being multiplied, strip it off.
966 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
967 Ops.erase(Ops.begin());
968 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +0000969 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000970 // If we have a multiply of zero, it will always be zero.
971 return Ops[0];
972 }
973 }
974
975 // Skip over the add expression until we get to a multiply.
976 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
977 ++Idx;
978
979 if (Ops.size() == 1)
980 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000981
Chris Lattner53e677a2004-04-02 20:23:17 +0000982 // If there are mul operands inline them all into this expression.
983 if (Idx < Ops.size()) {
984 bool DeletedMul = false;
985 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
986 // If we have an mul, expand the mul operands onto the end of the operands
987 // list.
988 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
989 Ops.erase(Ops.begin()+Idx);
990 DeletedMul = true;
991 }
992
993 // If we deleted at least one mul, we added operands to the end of the list,
994 // and they are not necessarily sorted. Recurse to resort and resimplify
995 // any operands we just aquired.
996 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +0000997 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000998 }
999
1000 // If there are any add recurrences in the operands list, see if any other
1001 // added values are loop invariant. If so, we can fold them into the
1002 // recurrence.
1003 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1004 ++Idx;
1005
1006 // Scan over all recurrences, trying to fold loop invariants into them.
1007 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1008 // Scan all of the other operands to this mul and add them to the vector if
1009 // they are loop invariant w.r.t. the recurrence.
1010 std::vector<SCEVHandle> LIOps;
1011 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1012 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1013 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1014 LIOps.push_back(Ops[i]);
1015 Ops.erase(Ops.begin()+i);
1016 --i; --e;
1017 }
1018
1019 // If we found some loop invariants, fold them into the recurrence.
1020 if (!LIOps.empty()) {
1021 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
1022 std::vector<SCEVHandle> NewOps;
1023 NewOps.reserve(AddRec->getNumOperands());
1024 if (LIOps.size() == 1) {
1025 SCEV *Scale = LIOps[0];
1026 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001027 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001028 } else {
1029 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1030 std::vector<SCEVHandle> MulOps(LIOps);
1031 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001032 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001033 }
1034 }
1035
Dan Gohman246b2562007-10-22 18:31:58 +00001036 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001037
1038 // If all of the other operands were loop invariant, we are done.
1039 if (Ops.size() == 1) return NewRec;
1040
1041 // Otherwise, multiply the folded AddRec by the non-liv parts.
1042 for (unsigned i = 0;; ++i)
1043 if (Ops[i] == AddRec) {
1044 Ops[i] = NewRec;
1045 break;
1046 }
Dan Gohman246b2562007-10-22 18:31:58 +00001047 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001048 }
1049
1050 // Okay, if there weren't any loop invariants to be folded, check to see if
1051 // there are multiple AddRec's with the same loop induction variable being
1052 // multiplied together. If so, we can fold them.
1053 for (unsigned OtherIdx = Idx+1;
1054 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1055 if (OtherIdx != Idx) {
1056 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1057 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1058 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1059 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman246b2562007-10-22 18:31:58 +00001060 SCEVHandle NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001061 G->getStart());
Dan Gohman246b2562007-10-22 18:31:58 +00001062 SCEVHandle B = F->getStepRecurrence(*this);
1063 SCEVHandle D = G->getStepRecurrence(*this);
1064 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1065 getMulExpr(G, B),
1066 getMulExpr(B, D));
1067 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1068 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001069 if (Ops.size() == 2) return NewAddRec;
1070
1071 Ops.erase(Ops.begin()+Idx);
1072 Ops.erase(Ops.begin()+OtherIdx-1);
1073 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001074 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001075 }
1076 }
1077
1078 // Otherwise couldn't fold anything into this recurrence. Move onto the
1079 // next one.
1080 }
1081
1082 // Okay, it looks like we really DO need an mul expr. Check to see if we
1083 // already have one, otherwise create a new one.
1084 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001085 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1086 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001087 if (Result == 0)
1088 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001089 return Result;
1090}
1091
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001092SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001093 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1094 if (RHSC->getValue()->equalsInt(1))
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001095 return LHS; // X udiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +00001096
1097 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1098 Constant *LHSCV = LHSC->getValue();
1099 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001100 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001101 }
1102 }
1103
1104 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1105
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001106 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1107 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001108 return Result;
1109}
1110
1111
1112/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1113/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001114SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Chris Lattner53e677a2004-04-02 20:23:17 +00001115 const SCEVHandle &Step, const Loop *L) {
1116 std::vector<SCEVHandle> Operands;
1117 Operands.push_back(Start);
1118 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1119 if (StepChrec->getLoop() == L) {
1120 Operands.insert(Operands.end(), StepChrec->op_begin(),
1121 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001122 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001123 }
1124
1125 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001126 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001127}
1128
1129/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1130/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001131SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Chris Lattner53e677a2004-04-02 20:23:17 +00001132 const Loop *L) {
1133 if (Operands.size() == 1) return Operands[0];
1134
1135 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
Reid Spencercae57542007-03-02 00:28:52 +00001136 if (StepC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001137 Operands.pop_back();
Dan Gohman246b2562007-10-22 18:31:58 +00001138 return getAddRecExpr(Operands, L); // { X,+,0 } --> X
Chris Lattner53e677a2004-04-02 20:23:17 +00001139 }
1140
1141 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001142 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1143 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001144 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1145 return Result;
1146}
1147
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001148SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1149 const SCEVHandle &RHS) {
1150 std::vector<SCEVHandle> Ops;
1151 Ops.push_back(LHS);
1152 Ops.push_back(RHS);
1153 return getSMaxExpr(Ops);
1154}
1155
1156SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1157 assert(!Ops.empty() && "Cannot get empty smax!");
1158 if (Ops.size() == 1) return Ops[0];
1159
1160 // Sort by complexity, this groups all similar expression types together.
1161 GroupByComplexity(Ops);
1162
1163 // If there are any constants, fold them together.
1164 unsigned Idx = 0;
1165 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1166 ++Idx;
1167 assert(Idx < Ops.size());
1168 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1169 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001170 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001171 APIntOps::smax(LHSC->getValue()->getValue(),
1172 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001173 Ops[0] = getConstant(Fold);
1174 Ops.erase(Ops.begin()+1); // Erase the folded element
1175 if (Ops.size() == 1) return Ops[0];
1176 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001177 }
1178
1179 // If we are left with a constant -inf, strip it off.
1180 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1181 Ops.erase(Ops.begin());
1182 --Idx;
1183 }
1184 }
1185
1186 if (Ops.size() == 1) return Ops[0];
1187
1188 // Find the first SMax
1189 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1190 ++Idx;
1191
1192 // Check to see if one of the operands is an SMax. If so, expand its operands
1193 // onto our operand list, and recurse to simplify.
1194 if (Idx < Ops.size()) {
1195 bool DeletedSMax = false;
1196 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1197 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1198 Ops.erase(Ops.begin()+Idx);
1199 DeletedSMax = true;
1200 }
1201
1202 if (DeletedSMax)
1203 return getSMaxExpr(Ops);
1204 }
1205
1206 // Okay, check to see if the same value occurs in the operand list twice. If
1207 // so, delete one. Since we sorted the list, these values are required to
1208 // be adjacent.
1209 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1210 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1211 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1212 --i; --e;
1213 }
1214
1215 if (Ops.size() == 1) return Ops[0];
1216
1217 assert(!Ops.empty() && "Reduced smax down to nothing!");
1218
Nick Lewycky3e630762008-02-20 06:48:22 +00001219 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001220 // already have one, otherwise create a new one.
1221 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1222 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1223 SCEVOps)];
1224 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1225 return Result;
1226}
1227
Nick Lewycky3e630762008-02-20 06:48:22 +00001228SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1229 const SCEVHandle &RHS) {
1230 std::vector<SCEVHandle> Ops;
1231 Ops.push_back(LHS);
1232 Ops.push_back(RHS);
1233 return getUMaxExpr(Ops);
1234}
1235
1236SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1237 assert(!Ops.empty() && "Cannot get empty umax!");
1238 if (Ops.size() == 1) return Ops[0];
1239
1240 // Sort by complexity, this groups all similar expression types together.
1241 GroupByComplexity(Ops);
1242
1243 // If there are any constants, fold them together.
1244 unsigned Idx = 0;
1245 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1246 ++Idx;
1247 assert(Idx < Ops.size());
1248 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1249 // We found two constants, fold them together!
1250 ConstantInt *Fold = ConstantInt::get(
1251 APIntOps::umax(LHSC->getValue()->getValue(),
1252 RHSC->getValue()->getValue()));
1253 Ops[0] = getConstant(Fold);
1254 Ops.erase(Ops.begin()+1); // Erase the folded element
1255 if (Ops.size() == 1) return Ops[0];
1256 LHSC = cast<SCEVConstant>(Ops[0]);
1257 }
1258
1259 // If we are left with a constant zero, strip it off.
1260 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1261 Ops.erase(Ops.begin());
1262 --Idx;
1263 }
1264 }
1265
1266 if (Ops.size() == 1) return Ops[0];
1267
1268 // Find the first UMax
1269 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1270 ++Idx;
1271
1272 // Check to see if one of the operands is a UMax. If so, expand its operands
1273 // onto our operand list, and recurse to simplify.
1274 if (Idx < Ops.size()) {
1275 bool DeletedUMax = false;
1276 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1277 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1278 Ops.erase(Ops.begin()+Idx);
1279 DeletedUMax = true;
1280 }
1281
1282 if (DeletedUMax)
1283 return getUMaxExpr(Ops);
1284 }
1285
1286 // Okay, check to see if the same value occurs in the operand list twice. If
1287 // so, delete one. Since we sorted the list, these values are required to
1288 // be adjacent.
1289 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1290 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1291 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1292 --i; --e;
1293 }
1294
1295 if (Ops.size() == 1) return Ops[0];
1296
1297 assert(!Ops.empty() && "Reduced umax down to nothing!");
1298
1299 // Okay, it looks like we really DO need a umax expr. Check to see if we
1300 // already have one, otherwise create a new one.
1301 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1302 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1303 SCEVOps)];
1304 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1305 return Result;
1306}
1307
Dan Gohman246b2562007-10-22 18:31:58 +00001308SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001309 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001310 return getConstant(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001311 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001312 if (Result == 0) Result = new SCEVUnknown(V);
1313 return Result;
1314}
1315
Chris Lattner53e677a2004-04-02 20:23:17 +00001316
1317//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001318// ScalarEvolutionsImpl Definition and Implementation
1319//===----------------------------------------------------------------------===//
1320//
1321/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1322/// evolution code.
1323///
1324namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001325 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohman246b2562007-10-22 18:31:58 +00001326 /// SE - A reference to the public ScalarEvolution object.
1327 ScalarEvolution &SE;
1328
Chris Lattner53e677a2004-04-02 20:23:17 +00001329 /// F - The function we are analyzing.
1330 ///
1331 Function &F;
1332
1333 /// LI - The loop information for the function we are currently analyzing.
1334 ///
1335 LoopInfo &LI;
1336
1337 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1338 /// things.
1339 SCEVHandle UnknownValue;
1340
1341 /// Scalars - This is a cache of the scalars we have analyzed so far.
1342 ///
1343 std::map<Value*, SCEVHandle> Scalars;
1344
1345 /// IterationCounts - Cache the iteration count of the loops for this
1346 /// function as they are computed.
1347 std::map<const Loop*, SCEVHandle> IterationCounts;
1348
Chris Lattner3221ad02004-04-17 22:58:41 +00001349 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1350 /// the PHI instructions that we attempt to compute constant evolutions for.
1351 /// This allows us to avoid potentially expensive recomputation of these
1352 /// properties. An instruction maps to null if we are unable to compute its
1353 /// exit value.
1354 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001355
Chris Lattner53e677a2004-04-02 20:23:17 +00001356 public:
Dan Gohman246b2562007-10-22 18:31:58 +00001357 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1358 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
Chris Lattner53e677a2004-04-02 20:23:17 +00001359
1360 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1361 /// expression and create a new one.
1362 SCEVHandle getSCEV(Value *V);
1363
Chris Lattnera0740fb2005-08-09 23:36:33 +00001364 /// hasSCEV - Return true if the SCEV for this value has already been
1365 /// computed.
1366 bool hasSCEV(Value *V) const {
1367 return Scalars.count(V);
1368 }
1369
1370 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1371 /// the specified value.
1372 void setSCEV(Value *V, const SCEVHandle &H) {
1373 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1374 assert(isNew && "This entry already existed!");
1375 }
1376
1377
Chris Lattner53e677a2004-04-02 20:23:17 +00001378 /// getSCEVAtScope - Compute the value of the specified expression within
1379 /// the indicated loop (which may be null to indicate in no loop). If the
1380 /// expression cannot be evaluated, return UnknownValue itself.
1381 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1382
1383
1384 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1385 /// an analyzable loop-invariant iteration count.
1386 bool hasLoopInvariantIterationCount(const Loop *L);
1387
1388 /// getIterationCount - If the specified loop has a predictable iteration
1389 /// count, return it. Note that it is not valid to call this method on a
1390 /// loop without a loop-invariant iteration count.
1391 SCEVHandle getIterationCount(const Loop *L);
1392
Dan Gohman5cec4db2007-06-19 14:28:31 +00001393 /// deleteValueFromRecords - This method should be called by the
1394 /// client before it removes a value from the program, to make sure
Chris Lattner53e677a2004-04-02 20:23:17 +00001395 /// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001396 void deleteValueFromRecords(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001397
1398 private:
1399 /// createSCEV - We know that there is no SCEV for the specified value.
1400 /// Analyze the expression.
1401 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001402
1403 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1404 /// SCEVs.
1405 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001406
1407 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1408 /// for the specified instruction and replaces any references to the
1409 /// symbolic value SymName with the specified value. This is used during
1410 /// PHI resolution.
1411 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1412 const SCEVHandle &SymName,
1413 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001414
1415 /// ComputeIterationCount - Compute the number of times the specified loop
1416 /// will iterate.
1417 SCEVHandle ComputeIterationCount(const Loop *L);
1418
Chris Lattner673e02b2004-10-12 01:49:27 +00001419 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001420 /// 'icmp op load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00001421 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1422 Constant *RHS,
1423 const Loop *L,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001424 ICmpInst::Predicate p);
Chris Lattner673e02b2004-10-12 01:49:27 +00001425
Chris Lattner7980fb92004-04-17 18:36:24 +00001426 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1427 /// constant number of times (the condition evolves only from constants),
1428 /// try to evaluate a few iterations of the loop until we get the exit
1429 /// condition gets a value of ExitWhen (true or false). If we cannot
1430 /// evaluate the trip count of the loop, return UnknownValue.
1431 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1432 bool ExitWhen);
1433
Chris Lattner53e677a2004-04-02 20:23:17 +00001434 /// HowFarToZero - Return the number of times a backedge comparing the
1435 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001436 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001437 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1438
1439 /// HowFarToNonZero - Return the number of times a backedge checking the
1440 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001441 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001442 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001443
Chris Lattnerdb25de42005-08-15 23:33:51 +00001444 /// HowManyLessThans - Return the number of times a backedge containing the
1445 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001446 /// UnknownValue. isSigned specifies whether the less-than is signed.
1447 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1448 bool isSigned);
Chris Lattnerdb25de42005-08-15 23:33:51 +00001449
Chris Lattner3221ad02004-04-17 22:58:41 +00001450 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1451 /// in the header of its containing loop, we know the loop executes a
1452 /// constant number of times, and the PHI node is just a recurrence
1453 /// involving constants, fold it.
Reid Spencere8019bb2007-03-01 07:25:48 +00001454 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
Chris Lattner3221ad02004-04-17 22:58:41 +00001455 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001456 };
1457}
1458
1459//===----------------------------------------------------------------------===//
1460// Basic SCEV Analysis and PHI Idiom Recognition Code
1461//
1462
Dan Gohman5cec4db2007-06-19 14:28:31 +00001463/// deleteValueFromRecords - This method should be called by the
Chris Lattner53e677a2004-04-02 20:23:17 +00001464/// client before it removes an instruction from the program, to make sure
1465/// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001466void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1467 SmallVector<Value *, 16> Worklist;
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001468
Dan Gohman5cec4db2007-06-19 14:28:31 +00001469 if (Scalars.erase(V)) {
1470 if (PHINode *PN = dyn_cast<PHINode>(V))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001471 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman5cec4db2007-06-19 14:28:31 +00001472 Worklist.push_back(V);
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001473 }
1474
1475 while (!Worklist.empty()) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001476 Value *VV = Worklist.back();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001477 Worklist.pop_back();
1478
Dan Gohman5cec4db2007-06-19 14:28:31 +00001479 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001480 UI != UE; ++UI) {
Nick Lewycky51e844b2007-06-06 11:26:20 +00001481 Instruction *Inst = cast<Instruction>(*UI);
1482 if (Scalars.erase(Inst)) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001483 if (PHINode *PN = dyn_cast<PHINode>(VV))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001484 ConstantEvolutionLoopExitValue.erase(PN);
1485 Worklist.push_back(Inst);
1486 }
1487 }
1488 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001489}
1490
1491
1492/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1493/// expression and create a new one.
1494SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1495 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1496
1497 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1498 if (I != Scalars.end()) return I->second;
1499 SCEVHandle S = createSCEV(V);
1500 Scalars.insert(std::make_pair(V, S));
1501 return S;
1502}
1503
Chris Lattner4dc534c2005-02-13 04:37:18 +00001504/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1505/// the specified instruction and replaces any references to the symbolic value
1506/// SymName with the specified value. This is used during PHI resolution.
1507void ScalarEvolutionsImpl::
1508ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1509 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001510 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001511 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001512
Chris Lattner4dc534c2005-02-13 04:37:18 +00001513 SCEVHandle NV =
Dan Gohman246b2562007-10-22 18:31:58 +00001514 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001515 if (NV == SI->second) return; // No change.
1516
1517 SI->second = NV; // Update the scalars map!
1518
1519 // Any instruction values that use this instruction might also need to be
1520 // updated!
1521 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1522 UI != E; ++UI)
1523 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1524}
Chris Lattner53e677a2004-04-02 20:23:17 +00001525
1526/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1527/// a loop header, making it a potential recurrence, or it doesn't.
1528///
1529SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1530 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1531 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1532 if (L->getHeader() == PN->getParent()) {
1533 // If it lives in the loop header, it has two incoming values, one
1534 // from outside the loop, and one from inside.
1535 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1536 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001537
Chris Lattner53e677a2004-04-02 20:23:17 +00001538 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman246b2562007-10-22 18:31:58 +00001539 SCEVHandle SymbolicName = SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001540 assert(Scalars.find(PN) == Scalars.end() &&
1541 "PHI node already processed?");
1542 Scalars.insert(std::make_pair(PN, SymbolicName));
1543
1544 // Using this symbolic name for the PHI, analyze the value coming around
1545 // the back-edge.
1546 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1547
1548 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1549 // has a special value for the first iteration of the loop.
1550
1551 // If the value coming around the backedge is an add with the symbolic
1552 // value we just inserted, then we found a simple induction variable!
1553 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1554 // If there is a single occurrence of the symbolic value, replace it
1555 // with a recurrence.
1556 unsigned FoundIndex = Add->getNumOperands();
1557 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1558 if (Add->getOperand(i) == SymbolicName)
1559 if (FoundIndex == e) {
1560 FoundIndex = i;
1561 break;
1562 }
1563
1564 if (FoundIndex != Add->getNumOperands()) {
1565 // Create an add with everything but the specified operand.
1566 std::vector<SCEVHandle> Ops;
1567 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1568 if (i != FoundIndex)
1569 Ops.push_back(Add->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001570 SCEVHandle Accum = SE.getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001571
1572 // This is not a valid addrec if the step amount is varying each
1573 // loop iteration, but is not itself an addrec in this loop.
1574 if (Accum->isLoopInvariant(L) ||
1575 (isa<SCEVAddRecExpr>(Accum) &&
1576 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1577 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman246b2562007-10-22 18:31:58 +00001578 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001579
1580 // Okay, for the entire analysis of this edge we assumed the PHI
1581 // to be symbolic. We now need to go back and update all of the
1582 // entries for the scalars that use the PHI (except for the PHI
1583 // itself) to use the new analyzed value instead of the "symbolic"
1584 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001585 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001586 return PHISCEV;
1587 }
1588 }
Chris Lattner97156e72006-04-26 18:34:07 +00001589 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1590 // Otherwise, this could be a loop like this:
1591 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1592 // In this case, j = {1,+,1} and BEValue is j.
1593 // Because the other in-value of i (0) fits the evolution of BEValue
1594 // i really is an addrec evolution.
1595 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1596 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1597
1598 // If StartVal = j.start - j.stride, we can use StartVal as the
1599 // initial step of the addrec evolution.
Dan Gohman246b2562007-10-22 18:31:58 +00001600 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1601 AddRec->getOperand(1))) {
Chris Lattner97156e72006-04-26 18:34:07 +00001602 SCEVHandle PHISCEV =
Dan Gohman246b2562007-10-22 18:31:58 +00001603 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00001604
1605 // Okay, for the entire analysis of this edge we assumed the PHI
1606 // to be symbolic. We now need to go back and update all of the
1607 // entries for the scalars that use the PHI (except for the PHI
1608 // itself) to use the new analyzed value instead of the "symbolic"
1609 // value.
1610 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1611 return PHISCEV;
1612 }
1613 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001614 }
1615
1616 return SymbolicName;
1617 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001618
Chris Lattner53e677a2004-04-02 20:23:17 +00001619 // If it's not a loop phi, we can't handle it yet.
Dan Gohman246b2562007-10-22 18:31:58 +00001620 return SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001621}
1622
Nick Lewycky83bb0052007-11-22 07:59:40 +00001623/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1624/// guaranteed to end in (at every loop iteration). It is, at the same time,
1625/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1626/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1627static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1628 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00001629 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00001630
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001631 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Nick Lewycky83bb0052007-11-22 07:59:40 +00001632 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1633
1634 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1635 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1636 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1637 }
1638
1639 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1640 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1641 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1642 }
1643
Chris Lattnera17f0392006-12-12 02:26:09 +00001644 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001645 // The result is the min of all operands results.
1646 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1647 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1648 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1649 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001650 }
1651
1652 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001653 // The result is the sum of all operands results.
1654 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1655 uint32_t BitWidth = M->getBitWidth();
1656 for (unsigned i = 1, e = M->getNumOperands();
1657 SumOpRes != BitWidth && i != e; ++i)
1658 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1659 BitWidth);
1660 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001661 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001662
Chris Lattnera17f0392006-12-12 02:26:09 +00001663 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001664 // The result is the min of all operands results.
1665 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1666 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1667 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1668 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001669 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001670
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001671 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1672 // The result is the min of all operands results.
1673 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1674 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1675 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1676 return MinOpRes;
1677 }
1678
Nick Lewycky3e630762008-02-20 06:48:22 +00001679 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1680 // The result is the min of all operands results.
1681 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1682 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1683 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1684 return MinOpRes;
1685 }
1686
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001687 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky83bb0052007-11-22 07:59:40 +00001688 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00001689}
Chris Lattner53e677a2004-04-02 20:23:17 +00001690
1691/// createSCEV - We know that there is no SCEV for the specified value.
1692/// Analyze the expression.
1693///
1694SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
Chris Lattner42b5e082007-11-23 08:46:22 +00001695 if (!isa<IntegerType>(V->getType()))
1696 return SE.getUnknown(V);
1697
Chris Lattner53e677a2004-04-02 20:23:17 +00001698 if (Instruction *I = dyn_cast<Instruction>(V)) {
1699 switch (I->getOpcode()) {
1700 case Instruction::Add:
Dan Gohman246b2562007-10-22 18:31:58 +00001701 return SE.getAddExpr(getSCEV(I->getOperand(0)),
1702 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001703 case Instruction::Mul:
Dan Gohman246b2562007-10-22 18:31:58 +00001704 return SE.getMulExpr(getSCEV(I->getOperand(0)),
1705 getSCEV(I->getOperand(1)));
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001706 case Instruction::UDiv:
1707 return SE.getUDivExpr(getSCEV(I->getOperand(0)),
Dan Gohman246b2562007-10-22 18:31:58 +00001708 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001709 case Instruction::Sub:
Dan Gohman246b2562007-10-22 18:31:58 +00001710 return SE.getMinusSCEV(getSCEV(I->getOperand(0)),
1711 getSCEV(I->getOperand(1)));
Chris Lattnera17f0392006-12-12 02:26:09 +00001712 case Instruction::Or:
1713 // If the RHS of the Or is a constant, we may have something like:
Nick Lewyckycf96db22007-11-20 08:24:44 +00001714 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
Chris Lattnera17f0392006-12-12 02:26:09 +00001715 // optimizations will transparently handle this case.
Nick Lewyckycf96db22007-11-20 08:24:44 +00001716 //
1717 // In order for this transformation to be safe, the LHS must be of the
1718 // form X*(2^n) and the Or constant must be less than 2^n.
Chris Lattnera17f0392006-12-12 02:26:09 +00001719 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1720 SCEVHandle LHS = getSCEV(I->getOperand(0));
Nick Lewyckycf96db22007-11-20 08:24:44 +00001721 const APInt &CIVal = CI->getValue();
Nick Lewycky83bb0052007-11-22 07:59:40 +00001722 if (GetMinTrailingZeros(LHS) >=
Nick Lewyckycf96db22007-11-20 08:24:44 +00001723 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Nick Lewycky83bb0052007-11-22 07:59:40 +00001724 return SE.getAddExpr(LHS, getSCEV(I->getOperand(1)));
Chris Lattnera17f0392006-12-12 02:26:09 +00001725 }
1726 break;
Chris Lattner2811f2a2007-04-02 05:41:38 +00001727 case Instruction::Xor:
1728 // If the RHS of the xor is a signbit, then this is just an add.
1729 // Instcombine turns add of signbit into xor as a strength reduction step.
1730 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1731 if (CI->getValue().isSignBit())
Dan Gohman246b2562007-10-22 18:31:58 +00001732 return SE.getAddExpr(getSCEV(I->getOperand(0)),
1733 getSCEV(I->getOperand(1)));
Nick Lewycky3e630762008-02-20 06:48:22 +00001734 else if (CI->isAllOnesValue())
1735 return SE.getNotSCEV(getSCEV(I->getOperand(0)));
Chris Lattner2811f2a2007-04-02 05:41:38 +00001736 }
1737 break;
1738
Chris Lattner53e677a2004-04-02 20:23:17 +00001739 case Instruction::Shl:
1740 // Turn shift left of a constant amount into a multiply.
1741 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfdc1e162007-04-07 17:40:57 +00001742 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1743 Constant *X = ConstantInt::get(
1744 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohman246b2562007-10-22 18:31:58 +00001745 return SE.getMulExpr(getSCEV(I->getOperand(0)), getSCEV(X));
Chris Lattner53e677a2004-04-02 20:23:17 +00001746 }
1747 break;
1748
Reid Spencer3da59db2006-11-27 01:05:10 +00001749 case Instruction::Trunc:
Dan Gohman246b2562007-10-22 18:31:58 +00001750 return SE.getTruncateExpr(getSCEV(I->getOperand(0)), I->getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001751
1752 case Instruction::ZExt:
Dan Gohman246b2562007-10-22 18:31:58 +00001753 return SE.getZeroExtendExpr(getSCEV(I->getOperand(0)), I->getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001754
Dan Gohmand19534a2007-06-15 14:38:12 +00001755 case Instruction::SExt:
Dan Gohman246b2562007-10-22 18:31:58 +00001756 return SE.getSignExtendExpr(getSCEV(I->getOperand(0)), I->getType());
Dan Gohmand19534a2007-06-15 14:38:12 +00001757
Reid Spencer3da59db2006-11-27 01:05:10 +00001758 case Instruction::BitCast:
1759 // BitCasts are no-op casts so we just eliminate the cast.
Chris Lattner42a75512007-01-15 02:27:26 +00001760 if (I->getType()->isInteger() &&
1761 I->getOperand(0)->getType()->isInteger())
Chris Lattner82e8a8f2006-12-11 00:12:31 +00001762 return getSCEV(I->getOperand(0));
1763 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001764
1765 case Instruction::PHI:
1766 return createNodeForPHI(cast<PHINode>(I));
1767
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001768 case Instruction::Select:
Nick Lewycky3e630762008-02-20 06:48:22 +00001769 // This could be a smax or umax that was lowered earlier.
1770 // Try to recover it.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001771 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I->getOperand(0))) {
1772 Value *LHS = ICI->getOperand(0);
1773 Value *RHS = ICI->getOperand(1);
1774 switch (ICI->getPredicate()) {
1775 case ICmpInst::ICMP_SLT:
1776 case ICmpInst::ICMP_SLE:
1777 std::swap(LHS, RHS);
1778 // fall through
1779 case ICmpInst::ICMP_SGT:
1780 case ICmpInst::ICMP_SGE:
1781 if (LHS == I->getOperand(1) && RHS == I->getOperand(2))
1782 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Nick Lewycky3e630762008-02-20 06:48:22 +00001783 else if (LHS == I->getOperand(2) && RHS == I->getOperand(1))
1784 // -smax(-x, -y) == smin(x, y).
1785 return SE.getNegativeSCEV(SE.getSMaxExpr(
1786 SE.getNegativeSCEV(getSCEV(LHS)),
1787 SE.getNegativeSCEV(getSCEV(RHS))));
1788 break;
1789 case ICmpInst::ICMP_ULT:
1790 case ICmpInst::ICMP_ULE:
1791 std::swap(LHS, RHS);
1792 // fall through
1793 case ICmpInst::ICMP_UGT:
1794 case ICmpInst::ICMP_UGE:
1795 if (LHS == I->getOperand(1) && RHS == I->getOperand(2))
1796 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1797 else if (LHS == I->getOperand(2) && RHS == I->getOperand(1))
1798 // ~umax(~x, ~y) == umin(x, y)
1799 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
1800 SE.getNotSCEV(getSCEV(RHS))));
1801 break;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001802 default:
1803 break;
1804 }
1805 }
1806
Chris Lattner53e677a2004-04-02 20:23:17 +00001807 default: // We cannot analyze this expression.
1808 break;
1809 }
1810 }
1811
Dan Gohman246b2562007-10-22 18:31:58 +00001812 return SE.getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001813}
1814
1815
1816
1817//===----------------------------------------------------------------------===//
1818// Iteration Count Computation Code
1819//
1820
1821/// getIterationCount - If the specified loop has a predictable iteration
1822/// count, return it. Note that it is not valid to call this method on a
1823/// loop without a loop-invariant iteration count.
1824SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1825 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1826 if (I == IterationCounts.end()) {
1827 SCEVHandle ItCount = ComputeIterationCount(L);
1828 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1829 if (ItCount != UnknownValue) {
1830 assert(ItCount->isLoopInvariant(L) &&
1831 "Computed trip count isn't loop invariant for loop!");
1832 ++NumTripCountsComputed;
1833 } else if (isa<PHINode>(L->getHeader()->begin())) {
1834 // Only count loops that have phi nodes as not being computable.
1835 ++NumTripCountsNotComputed;
1836 }
1837 }
1838 return I->second;
1839}
1840
1841/// ComputeIterationCount - Compute the number of times the specified loop
1842/// will iterate.
1843SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1844 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patelb7211a22007-08-21 00:31:24 +00001845 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001846 L->getExitBlocks(ExitBlocks);
1847 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001848
1849 // Okay, there is one exit block. Try to find the condition that causes the
1850 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001851 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001852
1853 BasicBlock *ExitingBlock = 0;
1854 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1855 PI != E; ++PI)
1856 if (L->contains(*PI)) {
1857 if (ExitingBlock == 0)
1858 ExitingBlock = *PI;
1859 else
1860 return UnknownValue; // More than one block exiting!
1861 }
1862 assert(ExitingBlock && "No exits from loop, something is broken!");
1863
1864 // Okay, we've computed the exiting block. See what condition causes us to
1865 // exit.
1866 //
1867 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00001868 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1869 if (ExitBr == 0) return UnknownValue;
1870 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00001871
1872 // At this point, we know we have a conditional branch that determines whether
1873 // the loop is exited. However, we don't know if the branch is executed each
1874 // time through the loop. If not, then the execution count of the branch will
1875 // not be equal to the trip count of the loop.
1876 //
1877 // Currently we check for this by checking to see if the Exit branch goes to
1878 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00001879 // times as the loop. We also handle the case where the exit block *is* the
1880 // loop header. This is common for un-rotated loops. More extensive analysis
1881 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001882 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00001883 ExitBr->getSuccessor(1) != L->getHeader() &&
1884 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00001885 return UnknownValue;
1886
Reid Spencere4d87aa2006-12-23 06:05:41 +00001887 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1888
Nick Lewycky3b711652008-02-21 08:34:02 +00001889 // If it's not an integer comparison then compute it the hard way.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001890 // Note that ICmpInst deals with pointer comparisons too so we must check
1891 // the type of the operand.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001892 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Chris Lattner7980fb92004-04-17 18:36:24 +00001893 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1894 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001895
Reid Spencere4d87aa2006-12-23 06:05:41 +00001896 // If the condition was exit on true, convert the condition to exit on false
1897 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00001898 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001899 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001900 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00001901 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001902
1903 // Handle common loops like: for (X = "string"; *X; ++X)
1904 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1905 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1906 SCEVHandle ItCnt =
1907 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1908 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1909 }
1910
Chris Lattner53e677a2004-04-02 20:23:17 +00001911 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1912 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1913
1914 // Try to evaluate any dependencies out of the loop.
1915 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1916 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1917 Tmp = getSCEVAtScope(RHS, L);
1918 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1919
Reid Spencere4d87aa2006-12-23 06:05:41 +00001920 // At this point, we would like to compute how many iterations of the
1921 // loop the predicate will return true for these inputs.
Evan Chengb9a90572008-02-25 03:57:32 +00001922 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1923 // If there is a constant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00001924 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001925 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00001926 }
1927
1928 // FIXME: think about handling pointer comparisons! i.e.:
1929 // while (P != P+100) ++P;
1930
1931 // If we have a comparison of a chrec against a constant, try to use value
1932 // ranges to answer this query.
1933 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1934 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1935 if (AddRec->getLoop() == L) {
1936 // Form the comparison range using the constant of the correct type so
1937 // that the ConstantRange class knows to do a signed or unsigned
1938 // comparison.
1939 ConstantInt *CompVal = RHSC->getValue();
1940 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00001941 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00001942 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00001943 if (CompVal) {
1944 // Form the constant range.
Reid Spencerc6aedf72007-02-28 22:03:51 +00001945 ConstantRange CompRange(
1946 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001947
Dan Gohman246b2562007-10-22 18:31:58 +00001948 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00001949 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1950 }
1951 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001952
Chris Lattner53e677a2004-04-02 20:23:17 +00001953 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001954 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00001955 // Convert to: while (X-Y != 0)
Dan Gohman246b2562007-10-22 18:31:58 +00001956 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001957 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00001958 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001959 }
1960 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00001961 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman246b2562007-10-22 18:31:58 +00001962 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001963 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00001964 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001965 }
1966 case ICmpInst::ICMP_SLT: {
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001967 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001968 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001969 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001970 }
1971 case ICmpInst::ICMP_SGT: {
Dan Gohman246b2562007-10-22 18:31:58 +00001972 SCEVHandle TC = HowManyLessThans(SE.getNegativeSCEV(LHS),
1973 SE.getNegativeSCEV(RHS), L, true);
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001974 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1975 break;
1976 }
1977 case ICmpInst::ICMP_ULT: {
1978 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
1979 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1980 break;
1981 }
1982 case ICmpInst::ICMP_UGT: {
Dale Johannesencf363182008-04-18 21:38:31 +00001983 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001984 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001985 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001986 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001987 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001988#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001989 cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00001990 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendlinge8156192006-12-07 01:30:32 +00001991 cerr << "[unsigned] ";
1992 cerr << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00001993 << Instruction::getOpcodeName(Instruction::ICmp)
1994 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001995#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00001996 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001997 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001998 return ComputeIterationCountExhaustively(L, ExitCond,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001999 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00002000}
2001
Chris Lattner673e02b2004-10-12 01:49:27 +00002002static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00002003EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2004 ScalarEvolution &SE) {
2005 SCEVHandle InVal = SE.getConstant(C);
2006 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002007 assert(isa<SCEVConstant>(Val) &&
2008 "Evaluation of SCEV at constant didn't fold correctly?");
2009 return cast<SCEVConstant>(Val)->getValue();
2010}
2011
2012/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2013/// and a GEP expression (missing the pointer index) indexing into it, return
2014/// the addressed element of the initializer or null if the index expression is
2015/// invalid.
2016static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002017GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00002018 const std::vector<ConstantInt*> &Indices) {
2019 Constant *Init = GV->getInitializer();
2020 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002021 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00002022 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2023 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2024 Init = cast<Constant>(CS->getOperand(Idx));
2025 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2026 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2027 Init = cast<Constant>(CA->getOperand(Idx));
2028 } else if (isa<ConstantAggregateZero>(Init)) {
2029 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2030 assert(Idx < STy->getNumElements() && "Bad struct index!");
2031 Init = Constant::getNullValue(STy->getElementType(Idx));
2032 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2033 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2034 Init = Constant::getNullValue(ATy->getElementType());
2035 } else {
2036 assert(0 && "Unknown constant aggregate type!");
2037 }
2038 return 0;
2039 } else {
2040 return 0; // Unknown initializer type
2041 }
2042 }
2043 return Init;
2044}
2045
2046/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky6e801dc2007-11-20 08:44:50 +00002047/// 'icmp op load X, cst', try to se if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00002048SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002049ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002050 const Loop *L,
2051 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002052 if (LI->isVolatile()) return UnknownValue;
2053
2054 // Check to see if the loaded pointer is a getelementptr of a global.
2055 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2056 if (!GEP) return UnknownValue;
2057
2058 // Make sure that it is really a constant global we are gepping, with an
2059 // initializer, and make sure the first IDX is really 0.
2060 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2061 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2062 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2063 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2064 return UnknownValue;
2065
2066 // Okay, we allow one non-constant index into the GEP instruction.
2067 Value *VarIdx = 0;
2068 std::vector<ConstantInt*> Indexes;
2069 unsigned VarIdxNum = 0;
2070 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2071 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2072 Indexes.push_back(CI);
2073 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2074 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2075 VarIdx = GEP->getOperand(i);
2076 VarIdxNum = i-2;
2077 Indexes.push_back(0);
2078 }
2079
2080 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2081 // Check to see if X is a loop variant variable value now.
2082 SCEVHandle Idx = getSCEV(VarIdx);
2083 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2084 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2085
2086 // We can only recognize very limited forms of loop index expressions, in
2087 // particular, only affine AddRec's like {C1,+,C2}.
2088 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2089 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2090 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2091 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2092 return UnknownValue;
2093
2094 unsigned MaxSteps = MaxBruteForceIterations;
2095 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002096 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00002097 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohman246b2562007-10-22 18:31:58 +00002098 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002099
2100 // Form the GEP offset.
2101 Indexes[VarIdxNum] = Val;
2102
2103 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2104 if (Result == 0) break; // Cannot compute!
2105
2106 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002107 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002108 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00002109 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002110#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002111 cerr << "\n***\n*** Computed loop count " << *ItCst
2112 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2113 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00002114#endif
2115 ++NumArrayLenItCounts;
Dan Gohman246b2562007-10-22 18:31:58 +00002116 return SE.getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00002117 }
2118 }
2119 return UnknownValue;
2120}
2121
2122
Chris Lattner3221ad02004-04-17 22:58:41 +00002123/// CanConstantFold - Return true if we can constant fold an instruction of the
2124/// specified type, assuming that all operands were constants.
2125static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00002126 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00002127 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2128 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002129
Chris Lattner3221ad02004-04-17 22:58:41 +00002130 if (const CallInst *CI = dyn_cast<CallInst>(I))
2131 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00002132 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00002133 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00002134}
2135
Chris Lattner3221ad02004-04-17 22:58:41 +00002136/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2137/// in the loop that V is derived from. We allow arbitrary operations along the
2138/// way, but the operands of an operation must either be constants or a value
2139/// derived from a constant PHI. If this expression does not fit with these
2140/// constraints, return null.
2141static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2142 // If this is not an instruction, or if this is an instruction outside of the
2143 // loop, it can't be derived from a loop PHI.
2144 Instruction *I = dyn_cast<Instruction>(V);
2145 if (I == 0 || !L->contains(I->getParent())) return 0;
2146
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002147 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002148 if (L->getHeader() == I->getParent())
2149 return PN;
2150 else
2151 // We don't currently keep track of the control flow needed to evaluate
2152 // PHIs, so we cannot handle PHIs inside of loops.
2153 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002154 }
Chris Lattner3221ad02004-04-17 22:58:41 +00002155
2156 // If we won't be able to constant fold this expression even if the operands
2157 // are constants, return early.
2158 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002159
Chris Lattner3221ad02004-04-17 22:58:41 +00002160 // Otherwise, we can evaluate this instruction if all of its operands are
2161 // constant or derived from a PHI node themselves.
2162 PHINode *PHI = 0;
2163 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2164 if (!(isa<Constant>(I->getOperand(Op)) ||
2165 isa<GlobalValue>(I->getOperand(Op)))) {
2166 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2167 if (P == 0) return 0; // Not evolving from PHI
2168 if (PHI == 0)
2169 PHI = P;
2170 else if (PHI != P)
2171 return 0; // Evolving from multiple different PHIs.
2172 }
2173
2174 // This is a expression evolving from a constant PHI!
2175 return PHI;
2176}
2177
2178/// EvaluateExpression - Given an expression that passes the
2179/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2180/// in the loop has the value PHIVal. If we can't fold this expression for some
2181/// reason, return null.
2182static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2183 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00002184 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00002185 Instruction *I = cast<Instruction>(V);
2186
2187 std::vector<Constant*> Operands;
2188 Operands.resize(I->getNumOperands());
2189
2190 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2191 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2192 if (Operands[i] == 0) return 0;
2193 }
2194
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002195 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2196 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2197 &Operands[0], Operands.size());
2198 else
2199 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2200 &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00002201}
2202
2203/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2204/// in the header of its containing loop, we know the loop executes a
2205/// constant number of times, and the PHI node is just a recurrence
2206/// involving constants, fold it.
2207Constant *ScalarEvolutionsImpl::
Reid Spencere8019bb2007-03-01 07:25:48 +00002208getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00002209 std::map<PHINode*, Constant*>::iterator I =
2210 ConstantEvolutionLoopExitValue.find(PN);
2211 if (I != ConstantEvolutionLoopExitValue.end())
2212 return I->second;
2213
Reid Spencere8019bb2007-03-01 07:25:48 +00002214 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00002215 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2216
2217 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2218
2219 // Since the loop is canonicalized, the PHI node must have two entries. One
2220 // entry must be a constant (coming in from outside of the loop), and the
2221 // second must be derived from the same PHI.
2222 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2223 Constant *StartCST =
2224 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2225 if (StartCST == 0)
2226 return RetVal = 0; // Must be a constant.
2227
2228 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2229 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2230 if (PN2 != PN)
2231 return RetVal = 0; // Not derived from same PHI.
2232
2233 // Execute the loop symbolically to determine the exit value.
Reid Spencere8019bb2007-03-01 07:25:48 +00002234 if (Its.getActiveBits() >= 32)
2235 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00002236
Reid Spencere8019bb2007-03-01 07:25:48 +00002237 unsigned NumIterations = Its.getZExtValue(); // must be in range
2238 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00002239 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2240 if (IterationNum == NumIterations)
2241 return RetVal = PHIVal; // Got exit value!
2242
2243 // Compute the value of the PHI node for the next iteration.
2244 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2245 if (NextPHI == PHIVal)
2246 return RetVal = NextPHI; // Stopped evolving!
2247 if (NextPHI == 0)
2248 return 0; // Couldn't evaluate!
2249 PHIVal = NextPHI;
2250 }
2251}
2252
Chris Lattner7980fb92004-04-17 18:36:24 +00002253/// ComputeIterationCountExhaustively - If the trip is known to execute a
2254/// constant number of times (the condition evolves only from constants),
2255/// try to evaluate a few iterations of the loop until we get the exit
2256/// condition gets a value of ExitWhen (true or false). If we cannot
2257/// evaluate the trip count of the loop, return UnknownValue.
2258SCEVHandle ScalarEvolutionsImpl::
2259ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2260 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2261 if (PN == 0) return UnknownValue;
2262
2263 // Since the loop is canonicalized, the PHI node must have two entries. One
2264 // entry must be a constant (coming in from outside of the loop), and the
2265 // second must be derived from the same PHI.
2266 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2267 Constant *StartCST =
2268 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2269 if (StartCST == 0) return UnknownValue; // Must be a constant.
2270
2271 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2272 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2273 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2274
2275 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2276 // the loop symbolically to determine when the condition gets a value of
2277 // "ExitWhen".
2278 unsigned IterationNum = 0;
2279 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2280 for (Constant *PHIVal = StartCST;
2281 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002282 ConstantInt *CondVal =
2283 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00002284
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002285 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00002286 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002287
Reid Spencere8019bb2007-03-01 07:25:48 +00002288 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002289 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00002290 ++NumBruteForceTripCountsComputed;
Dan Gohman246b2562007-10-22 18:31:58 +00002291 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00002292 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002293
Chris Lattner3221ad02004-04-17 22:58:41 +00002294 // Compute the value of the PHI node for the next iteration.
2295 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2296 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00002297 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00002298 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00002299 }
2300
2301 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00002302 return UnknownValue;
2303}
2304
2305/// getSCEVAtScope - Compute the value of the specified expression within the
2306/// indicated loop (which may be null to indicate in no loop). If the
2307/// expression cannot be evaluated, return UnknownValue.
2308SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2309 // FIXME: this should be turned into a virtual method on SCEV!
2310
Chris Lattner3221ad02004-04-17 22:58:41 +00002311 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002312
Nick Lewycky3e630762008-02-20 06:48:22 +00002313 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00002314 // exit value from the loop without using SCEVs.
2315 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2316 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2317 const Loop *LI = this->LI[I->getParent()];
2318 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2319 if (PHINode *PN = dyn_cast<PHINode>(I))
2320 if (PN->getParent() == LI->getHeader()) {
2321 // Okay, there is no closed form solution for the PHI node. Check
2322 // to see if the loop that contains it has a known iteration count.
2323 // If so, we may be able to force computation of the exit value.
2324 SCEVHandle IterationCount = getIterationCount(LI);
2325 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2326 // Okay, we know how many times the containing loop executes. If
2327 // this is a constant evolving PHI node, get the final value at
2328 // the specified iteration number.
2329 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencere8019bb2007-03-01 07:25:48 +00002330 ICC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00002331 LI);
Dan Gohman246b2562007-10-22 18:31:58 +00002332 if (RV) return SE.getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00002333 }
2334 }
2335
Reid Spencer09906f32006-12-04 21:33:23 +00002336 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00002337 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00002338 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00002339 // result. This is particularly useful for computing loop exit values.
2340 if (CanConstantFold(I)) {
2341 std::vector<Constant*> Operands;
2342 Operands.reserve(I->getNumOperands());
2343 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2344 Value *Op = I->getOperand(i);
2345 if (Constant *C = dyn_cast<Constant>(Op)) {
2346 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002347 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00002348 // If any of the operands is non-constant and if they are
2349 // non-integer, don't even try to analyze them with scev techniques.
2350 if (!isa<IntegerType>(Op->getType()))
2351 return V;
2352
Chris Lattner3221ad02004-04-17 22:58:41 +00002353 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2354 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
Reid Spencerd977d862006-12-12 23:36:14 +00002355 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2356 Op->getType(),
2357 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002358 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2359 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
Reid Spencerd977d862006-12-12 23:36:14 +00002360 Operands.push_back(ConstantExpr::getIntegerCast(C,
2361 Op->getType(),
2362 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002363 else
2364 return V;
2365 } else {
2366 return V;
2367 }
2368 }
2369 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002370
2371 Constant *C;
2372 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2373 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2374 &Operands[0], Operands.size());
2375 else
2376 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2377 &Operands[0], Operands.size());
Dan Gohman246b2562007-10-22 18:31:58 +00002378 return SE.getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002379 }
2380 }
2381
2382 // This is some other type of SCEVUnknown, just return it.
2383 return V;
2384 }
2385
Chris Lattner53e677a2004-04-02 20:23:17 +00002386 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2387 // Avoid performing the look-up in the common case where the specified
2388 // expression has no loop-variant portions.
2389 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2390 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2391 if (OpAtScope != Comm->getOperand(i)) {
2392 if (OpAtScope == UnknownValue) return UnknownValue;
2393 // Okay, at least one of these operands is loop variant but might be
2394 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002395 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002396 NewOps.push_back(OpAtScope);
2397
2398 for (++i; i != e; ++i) {
2399 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2400 if (OpAtScope == UnknownValue) return UnknownValue;
2401 NewOps.push_back(OpAtScope);
2402 }
2403 if (isa<SCEVAddExpr>(Comm))
Dan Gohman246b2562007-10-22 18:31:58 +00002404 return SE.getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002405 if (isa<SCEVMulExpr>(Comm))
2406 return SE.getMulExpr(NewOps);
2407 if (isa<SCEVSMaxExpr>(Comm))
2408 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00002409 if (isa<SCEVUMaxExpr>(Comm))
2410 return SE.getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002411 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002412 }
2413 }
2414 // If we got here, all operands are loop invariant.
2415 return Comm;
2416 }
2417
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00002418 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Chris Lattner60a05cc2006-04-01 04:48:52 +00002419 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002420 if (LHS == UnknownValue) return LHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002421 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002422 if (RHS == UnknownValue) return RHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002423 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2424 return Div; // must be loop invariant
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00002425 return SE.getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002426 }
2427
2428 // If this is a loop recurrence for a loop that does not contain L, then we
2429 // are dealing with the final value computed by the loop.
2430 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2431 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2432 // To evaluate this recurrence, we need to know how many times the AddRec
2433 // loop iterates. Compute this now.
2434 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2435 if (IterationCount == UnknownValue) return UnknownValue;
2436 IterationCount = getTruncateOrZeroExtend(IterationCount,
Dan Gohman246b2562007-10-22 18:31:58 +00002437 AddRec->getType(), SE);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002438
Chris Lattner53e677a2004-04-02 20:23:17 +00002439 // If the value is affine, simplify the expression evaluation to just
2440 // Start + Step*IterationCount.
2441 if (AddRec->isAffine())
Dan Gohman246b2562007-10-22 18:31:58 +00002442 return SE.getAddExpr(AddRec->getStart(),
2443 SE.getMulExpr(IterationCount,
2444 AddRec->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00002445
2446 // Otherwise, evaluate it the hard way.
Dan Gohman246b2562007-10-22 18:31:58 +00002447 return AddRec->evaluateAtIteration(IterationCount, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002448 }
2449 return UnknownValue;
2450 }
2451
2452 //assert(0 && "Unknown SCEV type!");
2453 return UnknownValue;
2454}
2455
2456
2457/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2458/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2459/// might be the same) or two SCEVCouldNotCompute objects.
2460///
2461static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman246b2562007-10-22 18:31:58 +00002462SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002463 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Reid Spencere8019bb2007-03-01 07:25:48 +00002464 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2465 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2466 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002467
Chris Lattner53e677a2004-04-02 20:23:17 +00002468 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00002469 if (!LC || !MC || !NC) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002470 SCEV *CNC = new SCEVCouldNotCompute();
2471 return std::make_pair(CNC, CNC);
2472 }
2473
Reid Spencere8019bb2007-03-01 07:25:48 +00002474 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00002475 const APInt &L = LC->getValue()->getValue();
2476 const APInt &M = MC->getValue()->getValue();
2477 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00002478 APInt Two(BitWidth, 2);
2479 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002480
Reid Spencere8019bb2007-03-01 07:25:48 +00002481 {
2482 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00002483 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00002484 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2485 // The B coefficient is M-N/2
2486 APInt B(M);
2487 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002488
Reid Spencere8019bb2007-03-01 07:25:48 +00002489 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00002490 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00002491
Reid Spencere8019bb2007-03-01 07:25:48 +00002492 // Compute the B^2-4ac term.
2493 APInt SqrtTerm(B);
2494 SqrtTerm *= B;
2495 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00002496
Reid Spencere8019bb2007-03-01 07:25:48 +00002497 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2498 // integer value or else APInt::sqrt() will assert.
2499 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002500
Reid Spencere8019bb2007-03-01 07:25:48 +00002501 // Compute the two solutions for the quadratic formula.
2502 // The divisions must be performed as signed divisions.
2503 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00002504 APInt TwoA( A << 1 );
Reid Spencere8019bb2007-03-01 07:25:48 +00002505 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2506 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002507
Dan Gohman246b2562007-10-22 18:31:58 +00002508 return std::make_pair(SE.getConstant(Solution1),
2509 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00002510 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00002511}
2512
2513/// HowFarToZero - Return the number of times a backedge comparing the specified
2514/// value to zero will execute. If not computable, return UnknownValue
2515SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2516 // If the value is a constant
2517 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2518 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00002519 if (C->getValue()->isZero()) return C;
Chris Lattner53e677a2004-04-02 20:23:17 +00002520 return UnknownValue; // Otherwise it will loop infinitely.
2521 }
2522
2523 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2524 if (!AddRec || AddRec->getLoop() != L)
2525 return UnknownValue;
2526
2527 if (AddRec->isAffine()) {
2528 // If this is an affine expression the execution count of this branch is
2529 // equal to:
2530 //
2531 // (0 - Start/Step) iff Start % Step == 0
2532 //
2533 // Get the initial value for the loop.
2534 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002535 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002536 SCEVHandle Step = AddRec->getOperand(1);
2537
2538 Step = getSCEVAtScope(Step, L->getParentLoop());
2539
2540 // Figure out if Start % Step == 0.
2541 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2542 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2543 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
Dan Gohman246b2562007-10-22 18:31:58 +00002544 return SE.getNegativeSCEV(Start); // 0 - Start/1 == -Start
Chris Lattner53e677a2004-04-02 20:23:17 +00002545 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2546 return Start; // 0 - Start/-1 == Start
2547
2548 // Check to see if Start is divisible by SC with no remainder.
2549 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2550 ConstantInt *StartCC = StartC->getValue();
2551 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
Reid Spencer0a783f72006-11-02 01:53:59 +00002552 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002553 if (Rem->isNullValue()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002554 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
Dan Gohman246b2562007-10-22 18:31:58 +00002555 return SE.getUnknown(Result);
Chris Lattner53e677a2004-04-02 20:23:17 +00002556 }
2557 }
2558 }
Chris Lattner42a75512007-01-15 02:27:26 +00002559 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002560 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2561 // the quadratic equation to solve it.
Dan Gohman246b2562007-10-22 18:31:58 +00002562 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002563 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2564 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2565 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002566#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002567 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2568 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002569#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002570 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002571 if (ConstantInt *CB =
2572 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002573 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002574 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002575 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002576
Chris Lattner53e677a2004-04-02 20:23:17 +00002577 // We can only use this value if the chrec ends up with an exact zero
2578 // value at this index. When solving for "X*X != 5", for example, we
2579 // should not accept a root of 2.
Dan Gohman246b2562007-10-22 18:31:58 +00002580 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002581 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
Reid Spencercae57542007-03-02 00:28:52 +00002582 if (EvalVal->getValue()->isZero())
Chris Lattner53e677a2004-04-02 20:23:17 +00002583 return R1; // We found a quadratic root!
2584 }
2585 }
2586 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002587
Chris Lattner53e677a2004-04-02 20:23:17 +00002588 return UnknownValue;
2589}
2590
2591/// HowFarToNonZero - Return the number of times a backedge checking the
2592/// specified value for nonzero will execute. If not computable, return
2593/// UnknownValue
2594SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2595 // Loops that look like: while (X == 0) are very strange indeed. We don't
2596 // handle them yet except for the trivial case. This could be expanded in the
2597 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002598
Chris Lattner53e677a2004-04-02 20:23:17 +00002599 // If the value is a constant, check to see if it is known to be non-zero
2600 // already. If so, the backedge will execute zero times.
2601 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00002602 if (!C->getValue()->isNullValue())
2603 return SE.getIntegerSCEV(0, C->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002604 return UnknownValue; // Otherwise it will loop infinitely.
2605 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002606
Chris Lattner53e677a2004-04-02 20:23:17 +00002607 // We could implement others, but I really doubt anyone writes loops like
2608 // this, and if they did, they would already be constant folded.
2609 return UnknownValue;
2610}
2611
Chris Lattnerdb25de42005-08-15 23:33:51 +00002612/// HowManyLessThans - Return the number of times a backedge containing the
2613/// specified less-than comparison will execute. If not computable, return
2614/// UnknownValue.
2615SCEVHandle ScalarEvolutionsImpl::
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002616HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00002617 // Only handle: "ADDREC < LoopInvariant".
2618 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2619
2620 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2621 if (!AddRec || AddRec->getLoop() != L)
2622 return UnknownValue;
2623
2624 if (AddRec->isAffine()) {
2625 // FORNOW: We only support unit strides.
Dan Gohman246b2562007-10-22 18:31:58 +00002626 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
Chris Lattnerdb25de42005-08-15 23:33:51 +00002627 if (AddRec->getOperand(1) != One)
2628 return UnknownValue;
2629
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002630 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
2631 // m. So, we count the number of iterations in which {n,+,1} < m is true.
2632 // Note that we cannot simply return max(m-n,0) because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00002633 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00002634
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002635 // First, we get the value of the LHS in the first iteration: n
2636 SCEVHandle Start = AddRec->getOperand(0);
2637
2638 // Then, we get the value of the LHS in the first iteration in which the
2639 // above condition doesn't hold. This equals to max(m,n).
Nick Lewycky3e630762008-02-20 06:48:22 +00002640 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
2641 : SE.getUMaxExpr(RHS, Start);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002642
2643 // Finally, we subtract these two values to get the number of times the
2644 // backedge is executed: max(m,n)-n.
Wojciech Matyjewicz7b5b7682008-02-12 15:09:36 +00002645 return SE.getMinusSCEV(End, Start);
Chris Lattnerdb25de42005-08-15 23:33:51 +00002646 }
2647
2648 return UnknownValue;
2649}
2650
Chris Lattner53e677a2004-04-02 20:23:17 +00002651/// getNumIterationsInRange - Return the number of iterations of this loop that
2652/// produce values in the specified constant range. Another way of looking at
2653/// this is that it returns the first iteration number where the value is not in
2654/// the condition, thus computing the exit count. If the iteration count can't
2655/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman246b2562007-10-22 18:31:58 +00002656SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2657 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002658 if (Range.isFullSet()) // Infinite loop.
2659 return new SCEVCouldNotCompute();
2660
2661 // If the start is a non-zero constant, shift the range to simplify things.
2662 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00002663 if (!SC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002664 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00002665 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2666 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002667 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2668 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00002669 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002670 // This is strange and shouldn't happen.
2671 return new SCEVCouldNotCompute();
2672 }
2673
2674 // The only time we can solve this is when we have all constant indices.
2675 // Otherwise, we cannot determine the overflow conditions.
2676 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2677 if (!isa<SCEVConstant>(getOperand(i)))
2678 return new SCEVCouldNotCompute();
2679
2680
2681 // Okay at this point we know that all elements of the chrec are constants and
2682 // that the start element is zero.
2683
2684 // First check to see if the range contains zero. If not, the first
2685 // iteration exits.
Reid Spencera6e8a952007-03-01 07:54:15 +00002686 if (!Range.contains(APInt(getBitWidth(),0)))
Dan Gohman246b2562007-10-22 18:31:58 +00002687 return SE.getConstant(ConstantInt::get(getType(),0));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002688
Chris Lattner53e677a2004-04-02 20:23:17 +00002689 if (isAffine()) {
2690 // If this is an affine expression then we have this situation:
2691 // Solve {0,+,A} in Range === Ax in Range
2692
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002693 // We know that zero is in the range. If A is positive then we know that
2694 // the upper value of the range must be the first possible exit value.
2695 // If A is negative then the lower of the range is the last possible loop
2696 // value. Also note that we already checked for a full range.
Reid Spencer581b0d42007-02-28 19:57:34 +00002697 APInt One(getBitWidth(),1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002698 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2699 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00002700
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002701 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00002702 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00002703 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002704
2705 // Evaluate at the exit value. If we really did fall out of the valid
2706 // range, then we computed our trip count, otherwise wrap around or other
2707 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00002708 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002709 if (Range.contains(Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002710 return new SCEVCouldNotCompute(); // Something strange happened
2711
2712 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00002713 assert(Range.contains(
2714 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00002715 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002716 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00002717 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00002718 } else if (isQuadratic()) {
2719 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2720 // quadratic equation to solve it. To do this, we must frame our problem in
2721 // terms of figuring out when zero is crossed, instead of when
2722 // Range.getUpper() is crossed.
2723 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00002724 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
2725 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002726
2727 // Next, solve the constructed addrec
2728 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00002729 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002730 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2731 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2732 if (R1) {
2733 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002734 if (ConstantInt *CB =
2735 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002736 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002737 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002738 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002739
Chris Lattner53e677a2004-04-02 20:23:17 +00002740 // Make sure the root is not off by one. The returned iteration should
2741 // not be in the range, but the previous one should be. When solving
2742 // for "X*X < 5", for example, we should not return a root of 2.
2743 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00002744 R1->getValue(),
2745 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002746 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002747 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00002748 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002749
Dan Gohman246b2562007-10-22 18:31:58 +00002750 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002751 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00002752 return SE.getConstant(NextVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002753 return new SCEVCouldNotCompute(); // Something strange happened
2754 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002755
Chris Lattner53e677a2004-04-02 20:23:17 +00002756 // If R1 was not in the range, then it is a good return value. Make
2757 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00002758 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00002759 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002760 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002761 return R1;
2762 return new SCEVCouldNotCompute(); // Something strange happened
2763 }
2764 }
2765 }
2766
2767 // Fallback, if this is a general polynomial, figure out the progression
2768 // through brute force: evaluate until we find an iteration that fails the
2769 // test. This is likely to be slow, but getting an accurate trip count is
2770 // incredibly important, we will be able to simplify the exit test a lot, and
2771 // we are almost guaranteed to get a trip count in this case.
2772 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00002773 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2774 do {
2775 ++NumBruteForceEvaluations;
Dan Gohman246b2562007-10-22 18:31:58 +00002776 SCEVHandle Val = evaluateAtIteration(SE.getConstant(TestVal), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002777 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2778 return new SCEVCouldNotCompute();
2779
2780 // Check to see if we found the value!
Reid Spencera6e8a952007-03-01 07:54:15 +00002781 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00002782 return SE.getConstant(TestVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002783
2784 // Increment to test the next index.
Zhou Shengfdc1e162007-04-07 17:40:57 +00002785 TestVal = ConstantInt::get(TestVal->getValue()+1);
Chris Lattner53e677a2004-04-02 20:23:17 +00002786 } while (TestVal != EndVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002787
Chris Lattner53e677a2004-04-02 20:23:17 +00002788 return new SCEVCouldNotCompute();
2789}
2790
2791
2792
2793//===----------------------------------------------------------------------===//
2794// ScalarEvolution Class Implementation
2795//===----------------------------------------------------------------------===//
2796
2797bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohman246b2562007-10-22 18:31:58 +00002798 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
Chris Lattner53e677a2004-04-02 20:23:17 +00002799 return false;
2800}
2801
2802void ScalarEvolution::releaseMemory() {
2803 delete (ScalarEvolutionsImpl*)Impl;
2804 Impl = 0;
2805}
2806
2807void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2808 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00002809 AU.addRequiredTransitive<LoopInfo>();
2810}
2811
2812SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2813 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2814}
2815
Chris Lattnera0740fb2005-08-09 23:36:33 +00002816/// hasSCEV - Return true if the SCEV for this value has already been
2817/// computed.
2818bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00002819 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00002820}
2821
2822
2823/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2824/// the specified value.
2825void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2826 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2827}
2828
2829
Chris Lattner53e677a2004-04-02 20:23:17 +00002830SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2831 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2832}
2833
2834bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2835 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2836}
2837
2838SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2839 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2840}
2841
Dan Gohman5cec4db2007-06-19 14:28:31 +00002842void ScalarEvolution::deleteValueFromRecords(Value *V) const {
2843 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002844}
2845
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002846static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00002847 const Loop *L) {
2848 // Print all inner loops first
2849 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2850 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002851
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00002852 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002853
Devang Patelb7211a22007-08-21 00:31:24 +00002854 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002855 L->getExitBlocks(ExitBlocks);
2856 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00002857 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002858
2859 if (SE->hasLoopInvariantIterationCount(L)) {
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00002860 OS << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002861 } else {
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00002862 OS << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002863 }
2864
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00002865 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00002866}
2867
Reid Spencerce9653c2004-12-07 04:03:45 +00002868void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002869 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2870 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2871
2872 OS << "Classifying expressions for: " << F.getName() << "\n";
2873 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner42a75512007-01-15 02:27:26 +00002874 if (I->getType()->isInteger()) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00002875 OS << *I;
Chris Lattner53e677a2004-04-02 20:23:17 +00002876 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002877 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00002878 SV->print(OS);
2879 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002880
Chris Lattner42a75512007-01-15 02:27:26 +00002881 if ((*I).getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002882 ConstantRange Bounds = SV->getValueRange();
2883 if (!Bounds.isFullSet())
2884 OS << "Bounds: " << Bounds << " ";
2885 }
2886
Chris Lattner6ffe5512004-04-27 15:13:33 +00002887 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002888 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002889 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002890 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2891 OS << "<<Unknown>>";
2892 } else {
2893 OS << *ExitValue;
2894 }
2895 }
2896
2897
2898 OS << "\n";
2899 }
2900
2901 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2902 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2903 PrintLoopInfo(OS, this, *I);
2904}