blob: f7f1849b6da861d40a3cc68e5b8c634408e80bbd [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"
Evan Cheng5a6c1a82009-02-17 00:13:06 +000069#include "llvm/Analysis/Dominators.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000070#include "llvm/Analysis/LoopInfo.h"
71#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000072#include "llvm/Target/TargetData.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"
Dan Gohman2d1be872009-04-16 03:18:22 +000076#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000077#include "llvm/Support/InstIterator.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000078#include "llvm/Support/ManagedStatic.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000079#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000080#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000081#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000082#include "llvm/ADT/STLExtras.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000083#include <ostream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000084#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000085using namespace llvm;
86
Chris Lattner3b27d682006-12-19 22:30:33 +000087STATISTIC(NumArrayLenItCounts,
88 "Number of trip counts computed with array length");
89STATISTIC(NumTripCountsComputed,
90 "Number of loops with predictable loop counts");
91STATISTIC(NumTripCountsNotComputed,
92 "Number of loops without predictable loop counts");
93STATISTIC(NumBruteForceTripCountsComputed,
94 "Number of loops with trip counts computed by force");
95
Dan Gohman844731a2008-05-13 00:00:25 +000096static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +000097MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
98 cl::desc("Maximum number of iterations SCEV will "
99 "symbolically execute a constant derived loop"),
100 cl::init(100));
101
Dan Gohman844731a2008-05-13 00:00:25 +0000102static RegisterPass<ScalarEvolution>
103R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000104char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000105
106//===----------------------------------------------------------------------===//
107// SCEV class definitions
108//===----------------------------------------------------------------------===//
109
110//===----------------------------------------------------------------------===//
111// Implementation of the SCEV class.
112//
Chris Lattner53e677a2004-04-02 20:23:17 +0000113SCEV::~SCEV() {}
114void SCEV::dump() const {
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000115 print(errs());
116 errs() << '\n';
117}
118
119void SCEV::print(std::ostream &o) const {
120 raw_os_ostream OS(o);
121 print(OS);
Chris Lattner53e677a2004-04-02 20:23:17 +0000122}
123
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000124bool SCEV::isZero() const {
125 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
126 return SC->getValue()->isZero();
127 return false;
128}
129
Dan Gohman70a1fe72009-05-18 15:22:39 +0000130bool SCEV::isOne() const {
131 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
132 return SC->getValue()->isOne();
133 return false;
134}
Chris Lattner53e677a2004-04-02 20:23:17 +0000135
136SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
Dan Gohmanf8a8be82009-04-21 23:15:49 +0000137SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
Chris Lattner53e677a2004-04-02 20:23:17 +0000138
139bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
140 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000141 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000142}
143
144const Type *SCEVCouldNotCompute::getType() const {
145 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000146 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000147}
148
149bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
150 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
151 return false;
152}
153
Chris Lattner4dc534c2005-02-13 04:37:18 +0000154SCEVHandle SCEVCouldNotCompute::
155replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000156 const SCEVHandle &Conc,
157 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000158 return this;
159}
160
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000161void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000162 OS << "***COULDNOTCOMPUTE***";
163}
164
165bool SCEVCouldNotCompute::classof(const SCEV *S) {
166 return S->getSCEVType() == scCouldNotCompute;
167}
168
169
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000170// SCEVConstants - Only allow the creation of one SCEVConstant for any
171// particular value. Don't use a SCEVHandle here, or else the object will
172// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000173static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000174
Chris Lattner53e677a2004-04-02 20:23:17 +0000175
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000176SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000177 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000178}
Chris Lattner53e677a2004-04-02 20:23:17 +0000179
Dan Gohman246b2562007-10-22 18:31:58 +0000180SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Chris Lattnerb3364092006-10-04 21:49:37 +0000181 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000182 if (R == 0) R = new SCEVConstant(V);
183 return R;
184}
Chris Lattner53e677a2004-04-02 20:23:17 +0000185
Dan Gohman246b2562007-10-22 18:31:58 +0000186SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
187 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000188}
189
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000190const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000191
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000192void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000193 WriteAsOperand(OS, V, false);
194}
Chris Lattner53e677a2004-04-02 20:23:17 +0000195
Dan Gohman84923602009-04-21 01:25:57 +0000196SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
197 const SCEVHandle &op, const Type *ty)
198 : SCEV(SCEVTy), Op(op), Ty(ty) {}
199
200SCEVCastExpr::~SCEVCastExpr() {}
201
202bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
203 return Op->dominates(BB, DT);
204}
205
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000206// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
207// particular input. Don't use a SCEVHandle here, or else the object will
208// never be deleted!
Dan Gohman35738ac2009-05-04 22:30:44 +0000209static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Chris Lattnerb3364092006-10-04 21:49:37 +0000210 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000211
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000212SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman84923602009-04-21 01:25:57 +0000213 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000214 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
215 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000216 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000217}
Chris Lattner53e677a2004-04-02 20:23:17 +0000218
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000220 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000221}
Chris Lattner53e677a2004-04-02 20:23:17 +0000222
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000223void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000224 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000225}
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!
Dan Gohman35738ac2009-05-04 22:30:44 +0000230static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Chris Lattnerb3364092006-10-04 21:49:37 +0000231 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000232
233SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman84923602009-04-21 01:25:57 +0000234 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000235 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
236 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000237 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000238}
239
240SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000241 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000242}
243
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000244void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000245 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000246}
247
Dan Gohmand19534a2007-06-15 14:38:12 +0000248// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
249// particular input. Don't use a SCEVHandle here, or else the object will never
250// be deleted!
Dan Gohman35738ac2009-05-04 22:30:44 +0000251static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmand19534a2007-06-15 14:38:12 +0000252 SCEVSignExtendExpr*> > SCEVSignExtends;
253
254SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman84923602009-04-21 01:25:57 +0000255 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000256 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
257 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000258 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000259}
260
261SCEVSignExtendExpr::~SCEVSignExtendExpr() {
262 SCEVSignExtends->erase(std::make_pair(Op, Ty));
263}
264
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000265void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000266 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000267}
268
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000269// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
270// particular input. Don't use a SCEVHandle here, or else the object will never
271// be deleted!
Dan Gohman35738ac2009-05-04 22:30:44 +0000272static ManagedStatic<std::map<std::pair<unsigned, std::vector<const SCEV*> >,
Chris Lattnerb3364092006-10-04 21:49:37 +0000273 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000274
275SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Dan Gohman35738ac2009-05-04 22:30:44 +0000276 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
277 SCEVCommExprs->erase(std::make_pair(getSCEVType(), SCEVOps));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000278}
279
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000280void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000281 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
282 const char *OpStr = getOperationStr();
283 OS << "(" << *Operands[0];
284 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
285 OS << OpStr << *Operands[i];
286 OS << ")";
287}
288
Chris Lattner4dc534c2005-02-13 04:37:18 +0000289SCEVHandle SCEVCommutativeExpr::
290replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000291 const SCEVHandle &Conc,
292 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000293 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000294 SCEVHandle H =
295 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000296 if (H != getOperand(i)) {
297 std::vector<SCEVHandle> NewOps;
298 NewOps.reserve(getNumOperands());
299 for (unsigned j = 0; j != i; ++j)
300 NewOps.push_back(getOperand(j));
301 NewOps.push_back(H);
302 for (++i; i != e; ++i)
303 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000304 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000305
306 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000307 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000308 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000309 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000310 else if (isa<SCEVSMaxExpr>(this))
311 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000312 else if (isa<SCEVUMaxExpr>(this))
313 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000314 else
315 assert(0 && "Unknown commutative expr!");
316 }
317 }
318 return this;
319}
320
Dan Gohmanecb403a2009-05-07 14:00:19 +0000321bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000322 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
323 if (!getOperand(i)->dominates(BB, DT))
324 return false;
325 }
326 return true;
327}
328
Chris Lattner4dc534c2005-02-13 04:37:18 +0000329
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000330// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000331// input. Don't use a SCEVHandle here, or else the object will never be
332// deleted!
Dan Gohman35738ac2009-05-04 22:30:44 +0000333static ManagedStatic<std::map<std::pair<const SCEV*, const SCEV*>,
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000334 SCEVUDivExpr*> > SCEVUDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000335
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000336SCEVUDivExpr::~SCEVUDivExpr() {
337 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000338}
339
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000340bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
341 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
342}
343
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000344void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000345 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000346}
347
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000348const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000349 // In most cases the types of LHS and RHS will be the same, but in some
350 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
351 // depend on the type for correctness, but handling types carefully can
352 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
353 // a pointer type than the RHS, so use the RHS' type here.
354 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000355}
356
357// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
358// particular input. Don't use a SCEVHandle here, or else the object will never
359// be deleted!
Dan Gohman35738ac2009-05-04 22:30:44 +0000360static ManagedStatic<std::map<std::pair<const Loop *,
361 std::vector<const SCEV*> >,
Chris Lattnerb3364092006-10-04 21:49:37 +0000362 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000363
364SCEVAddRecExpr::~SCEVAddRecExpr() {
Dan Gohman35738ac2009-05-04 22:30:44 +0000365 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
366 SCEVAddRecExprs->erase(std::make_pair(L, SCEVOps));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000367}
368
Chris Lattner4dc534c2005-02-13 04:37:18 +0000369SCEVHandle SCEVAddRecExpr::
370replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000371 const SCEVHandle &Conc,
372 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000373 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000374 SCEVHandle H =
375 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000376 if (H != getOperand(i)) {
377 std::vector<SCEVHandle> NewOps;
378 NewOps.reserve(getNumOperands());
379 for (unsigned j = 0; j != i; ++j)
380 NewOps.push_back(getOperand(j));
381 NewOps.push_back(H);
382 for (++i; i != e; ++i)
383 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000384 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000385
Dan Gohman246b2562007-10-22 18:31:58 +0000386 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000387 }
388 }
389 return this;
390}
391
392
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000393bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
394 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000395 // contain L and if the start is invariant.
Dan Gohmana3035a62009-05-20 01:01:24 +0000396 // Add recurrences are never invariant in the function-body (null loop).
397 return QueryLoop &&
398 !QueryLoop->contains(L->getHeader()) &&
Chris Lattnerff2006a2005-08-16 00:37:01 +0000399 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000400}
401
402
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000403void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000404 OS << "{" << *Operands[0];
405 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
406 OS << ",+," << *Operands[i];
407 OS << "}<" << L->getHeader()->getName() + ">";
408}
Chris Lattner53e677a2004-04-02 20:23:17 +0000409
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000410// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
411// value. Don't use a SCEVHandle here, or else the object will never be
412// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000413static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000414
Chris Lattnerb3364092006-10-04 21:49:37 +0000415SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000416
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000417bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
418 // All non-instruction values are loop invariant. All instructions are loop
419 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000420 // Instructions are never considered invariant in the function body
421 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000422 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmana3035a62009-05-20 01:01:24 +0000423 return L && !L->contains(I->getParent());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000424 return true;
425}
Chris Lattner53e677a2004-04-02 20:23:17 +0000426
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000427bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
428 if (Instruction *I = dyn_cast<Instruction>(getValue()))
429 return DT->dominates(I->getParent(), BB);
430 return true;
431}
432
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000433const Type *SCEVUnknown::getType() const {
434 return V->getType();
435}
Chris Lattner53e677a2004-04-02 20:23:17 +0000436
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000437void SCEVUnknown::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000438 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000439}
440
Chris Lattner8d741b82004-06-20 06:23:15 +0000441//===----------------------------------------------------------------------===//
442// SCEV Utilities
443//===----------------------------------------------------------------------===//
444
445namespace {
446 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
447 /// than the complexity of the RHS. This comparator is used to canonicalize
448 /// expressions.
Dan Gohman72861302009-05-07 14:39:04 +0000449 class VISIBILITY_HIDDEN SCEVComplexityCompare {
450 LoopInfo *LI;
451 public:
452 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
453
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000454 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman72861302009-05-07 14:39:04 +0000455 // Primarily, sort the SCEVs by their getSCEVType().
456 if (LHS->getSCEVType() != RHS->getSCEVType())
457 return LHS->getSCEVType() < RHS->getSCEVType();
458
459 // Aside from the getSCEVType() ordering, the particular ordering
460 // isn't very important except that it's beneficial to be consistent,
461 // so that (a + b) and (b + a) don't end up as different expressions.
462
463 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
464 // not as complete as it could be.
465 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
466 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
467
Dan Gohman5be18e82009-05-19 02:15:55 +0000468 // Order pointer values after integer values. This helps SCEVExpander
469 // form GEPs.
470 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
471 return false;
472 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
473 return true;
474
Dan Gohman72861302009-05-07 14:39:04 +0000475 // Compare getValueID values.
476 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
477 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
478
479 // Sort arguments by their position.
480 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
481 const Argument *RA = cast<Argument>(RU->getValue());
482 return LA->getArgNo() < RA->getArgNo();
483 }
484
485 // For instructions, compare their loop depth, and their opcode.
486 // This is pretty loose.
487 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
488 Instruction *RV = cast<Instruction>(RU->getValue());
489
490 // Compare loop depths.
491 if (LI->getLoopDepth(LV->getParent()) !=
492 LI->getLoopDepth(RV->getParent()))
493 return LI->getLoopDepth(LV->getParent()) <
494 LI->getLoopDepth(RV->getParent());
495
496 // Compare opcodes.
497 if (LV->getOpcode() != RV->getOpcode())
498 return LV->getOpcode() < RV->getOpcode();
499
500 // Compare the number of operands.
501 if (LV->getNumOperands() != RV->getNumOperands())
502 return LV->getNumOperands() < RV->getNumOperands();
503 }
504
505 return false;
506 }
507
508 // Constant sorting doesn't matter since they'll be folded.
509 if (isa<SCEVConstant>(LHS))
510 return false;
511
512 // Lexicographically compare n-ary expressions.
513 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
514 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
515 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
516 if (i >= RC->getNumOperands())
517 return false;
518 if (operator()(LC->getOperand(i), RC->getOperand(i)))
519 return true;
520 if (operator()(RC->getOperand(i), LC->getOperand(i)))
521 return false;
522 }
523 return LC->getNumOperands() < RC->getNumOperands();
524 }
525
Dan Gohmana6b35e22009-05-07 19:23:21 +0000526 // Lexicographically compare udiv expressions.
527 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
528 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
529 if (operator()(LC->getLHS(), RC->getLHS()))
530 return true;
531 if (operator()(RC->getLHS(), LC->getLHS()))
532 return false;
533 if (operator()(LC->getRHS(), RC->getRHS()))
534 return true;
535 if (operator()(RC->getRHS(), LC->getRHS()))
536 return false;
537 return false;
538 }
539
Dan Gohman72861302009-05-07 14:39:04 +0000540 // Compare cast expressions by operand.
541 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
542 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
543 return operator()(LC->getOperand(), RC->getOperand());
544 }
545
546 assert(0 && "Unknown SCEV kind!");
547 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000548 }
549 };
550}
551
552/// GroupByComplexity - Given a list of SCEV objects, order them by their
553/// complexity, and group objects of the same complexity together by value.
554/// When this routine is finished, we know that any duplicates in the vector are
555/// consecutive and that complexity is monotonically increasing.
556///
557/// Note that we go take special precautions to ensure that we get determinstic
558/// results from this routine. In other words, we don't want the results of
559/// this to depend on where the addresses of various SCEV objects happened to
560/// land in memory.
561///
Dan Gohman72861302009-05-07 14:39:04 +0000562static void GroupByComplexity(std::vector<SCEVHandle> &Ops,
563 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000564 if (Ops.size() < 2) return; // Noop
565 if (Ops.size() == 2) {
566 // This is the common case, which also happens to be trivially simple.
567 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000568 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000569 std::swap(Ops[0], Ops[1]);
570 return;
571 }
572
573 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000574 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000575
576 // Now that we are sorted by complexity, group elements of the same
577 // complexity. Note that this is, at worst, N^2, but the vector is likely to
578 // be extremely short in practice. Note that we take this approach because we
579 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000580 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000581 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000582 unsigned Complexity = S->getSCEVType();
583
584 // If there are any objects of the same complexity and same value as this
585 // one, group them.
586 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
587 if (Ops[j] == S) { // Found a duplicate.
588 // Move it to immediately after i'th element.
589 std::swap(Ops[i+1], Ops[j]);
590 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000591 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000592 }
593 }
594 }
595}
596
Chris Lattner53e677a2004-04-02 20:23:17 +0000597
Chris Lattner53e677a2004-04-02 20:23:17 +0000598
599//===----------------------------------------------------------------------===//
600// Simple SCEV method implementations
601//===----------------------------------------------------------------------===//
602
Eli Friedmanb42a6262008-08-04 23:49:06 +0000603/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000604/// Assume, K > 0.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000605static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedmanb42a6262008-08-04 23:49:06 +0000606 ScalarEvolution &SE,
Dan Gohman2d1be872009-04-16 03:18:22 +0000607 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000608 // Handle the simplest case efficiently.
609 if (K == 1)
610 return SE.getTruncateOrZeroExtend(It, ResultTy);
611
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000612 // We are using the following formula for BC(It, K):
613 //
614 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
615 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000616 // Suppose, W is the bitwidth of the return value. We must be prepared for
617 // overflow. Hence, we must assure that the result of our computation is
618 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
619 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000620 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000621 // However, this code doesn't use exactly that formula; the formula it uses
622 // is something like the following, where T is the number of factors of 2 in
623 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
624 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000625 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000626 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000627 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000628 // This formula is trivially equivalent to the previous formula. However,
629 // this formula can be implemented much more efficiently. The trick is that
630 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
631 // arithmetic. To do exact division in modular arithmetic, all we have
632 // to do is multiply by the inverse. Therefore, this step can be done at
633 // width W.
634 //
635 // The next issue is how to safely do the division by 2^T. The way this
636 // is done is by doing the multiplication step at a width of at least W + T
637 // bits. This way, the bottom W+T bits of the product are accurate. Then,
638 // when we perform the division by 2^T (which is equivalent to a right shift
639 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
640 // truncated out after the division by 2^T.
641 //
642 // In comparison to just directly using the first formula, this technique
643 // is much more efficient; using the first formula requires W * K bits,
644 // but this formula less than W + K bits. Also, the first formula requires
645 // a division step, whereas this formula only requires multiplies and shifts.
646 //
647 // It doesn't matter whether the subtraction step is done in the calculation
648 // width or the input iteration count's width; if the subtraction overflows,
649 // the result must be zero anyway. We prefer here to do it in the width of
650 // the induction variable because it helps a lot for certain cases; CodeGen
651 // isn't smart enough to ignore the overflow, which leads to much less
652 // efficient code if the width of the subtraction is wider than the native
653 // register width.
654 //
655 // (It's possible to not widen at all by pulling out factors of 2 before
656 // the multiplication; for example, K=2 can be calculated as
657 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
658 // extra arithmetic, so it's not an obvious win, and it gets
659 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000660
Eli Friedmanb42a6262008-08-04 23:49:06 +0000661 // Protection from insane SCEVs; this bound is conservative,
662 // but it probably doesn't matter.
663 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000664 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000665
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000666 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000667
Eli Friedmanb42a6262008-08-04 23:49:06 +0000668 // Calculate K! / 2^T and T; we divide out the factors of two before
669 // multiplying for calculating K! / 2^T to avoid overflow.
670 // Other overflow doesn't matter because we only care about the bottom
671 // W bits of the result.
672 APInt OddFactorial(W, 1);
673 unsigned T = 1;
674 for (unsigned i = 3; i <= K; ++i) {
675 APInt Mult(W, i);
676 unsigned TwoFactors = Mult.countTrailingZeros();
677 T += TwoFactors;
678 Mult = Mult.lshr(TwoFactors);
679 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000680 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000681
Eli Friedmanb42a6262008-08-04 23:49:06 +0000682 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000683 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000684
685 // Calcuate 2^T, at width T+W.
686 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
687
688 // Calculate the multiplicative inverse of K! / 2^T;
689 // this multiplication factor will perform the exact division by
690 // K! / 2^T.
691 APInt Mod = APInt::getSignedMinValue(W+1);
692 APInt MultiplyFactor = OddFactorial.zext(W+1);
693 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
694 MultiplyFactor = MultiplyFactor.trunc(W);
695
696 // Calculate the product, at width T+W
697 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
698 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
699 for (unsigned i = 1; i != K; ++i) {
700 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
701 Dividend = SE.getMulExpr(Dividend,
702 SE.getTruncateOrZeroExtend(S, CalculationTy));
703 }
704
705 // Divide by 2^T
706 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
707
708 // Truncate the result, and divide by K! / 2^T.
709
710 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
711 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000712}
713
Chris Lattner53e677a2004-04-02 20:23:17 +0000714/// evaluateAtIteration - Return the value of this chain of recurrences at
715/// the specified iteration number. We can evaluate this recurrence by
716/// multiplying each element in the chain by the binomial coefficient
717/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
718///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000719/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000720///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000721/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000722///
Dan Gohman246b2562007-10-22 18:31:58 +0000723SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
724 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000725 SCEVHandle Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000726 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000727 // The computation is correct in the face of overflow provided that the
728 // multiplication is performed _after_ the evaluation of the binomial
729 // coefficient.
Dan Gohman2d1be872009-04-16 03:18:22 +0000730 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000731 if (isa<SCEVCouldNotCompute>(Coeff))
732 return Coeff;
733
734 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000735 }
736 return Result;
737}
738
Chris Lattner53e677a2004-04-02 20:23:17 +0000739//===----------------------------------------------------------------------===//
740// SCEV Expression folder implementations
741//===----------------------------------------------------------------------===//
742
Dan Gohman99243b32009-05-01 16:44:56 +0000743SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
744 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000745 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000746 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000747 assert(isSCEVable(Ty) &&
748 "This is not a conversion to a SCEVable type!");
749 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000750
Dan Gohman622ed672009-05-04 22:02:23 +0000751 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000752 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000753 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000754
Dan Gohman20900ca2009-04-22 16:20:48 +0000755 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000756 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000757 return getTruncateExpr(ST->getOperand(), Ty);
758
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000759 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000760 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000761 return getTruncateOrSignExtend(SS->getOperand(), Ty);
762
763 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000764 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000765 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
766
Chris Lattner53e677a2004-04-02 20:23:17 +0000767 // If the input value is a chrec scev made out of constants, truncate
768 // all of the constants.
Dan Gohman622ed672009-05-04 22:02:23 +0000769 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000770 std::vector<SCEVHandle> Operands;
771 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000772 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
773 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000774 }
775
Chris Lattnerb3364092006-10-04 21:49:37 +0000776 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000777 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
778 return Result;
779}
780
Dan Gohman8170a682009-04-16 19:25:55 +0000781SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
782 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000783 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000784 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000785 assert(isSCEVable(Ty) &&
786 "This is not a conversion to a SCEVable type!");
787 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000788
Dan Gohman622ed672009-05-04 22:02:23 +0000789 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000790 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000791 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
792 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
793 return getUnknown(C);
794 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000795
Dan Gohman20900ca2009-04-22 16:20:48 +0000796 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000797 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000798 return getZeroExtendExpr(SZ->getOperand(), Ty);
799
Dan Gohman01ecca22009-04-27 20:16:15 +0000800 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000801 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000802 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000803 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000804 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000805 if (AR->isAffine()) {
806 // Check whether the backedge-taken count is SCEVCouldNotCompute.
807 // Note that this serves two purposes: It filters out loops that are
808 // simply not analyzable, and it covers the case where this code is
809 // being called from within backedge-taken count analysis, such that
810 // attempting to ask for the backedge-taken count would likely result
811 // in infinite recursion. In the later case, the analysis code will
812 // cope with a conservative value, and it will take care to purge
813 // that value once it has finished.
Dan Gohmana1af7572009-04-30 20:47:05 +0000814 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
815 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000816 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000817 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000818 SCEVHandle Start = AR->getStart();
819 SCEVHandle Step = AR->getStepRecurrence(*this);
820
821 // Check whether the backedge-taken count can be losslessly casted to
822 // the addrec's type. The count is always unsigned.
Dan Gohmana1af7572009-04-30 20:47:05 +0000823 SCEVHandle CastedMaxBECount =
824 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman5183cae2009-05-18 15:58:39 +0000825 SCEVHandle RecastedMaxBECount =
826 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
827 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000828 const Type *WideTy =
829 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000830 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000831 SCEVHandle ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000832 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000833 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000834 SCEVHandle Add = getAddExpr(Start, ZMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000835 SCEVHandle OperandExtendedAdd =
836 getAddExpr(getZeroExtendExpr(Start, WideTy),
837 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
838 getZeroExtendExpr(Step, WideTy)));
839 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000840 // Return the expression with the addrec on the outside.
841 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
842 getZeroExtendExpr(Step, Ty),
843 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000844
845 // Similar to above, only this time treat the step value as signed.
846 // This covers loops that count down.
847 SCEVHandle SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000848 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000849 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000850 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000851 OperandExtendedAdd =
852 getAddExpr(getZeroExtendExpr(Start, WideTy),
853 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
854 getSignExtendExpr(Step, WideTy)));
855 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000856 // Return the expression with the addrec on the outside.
857 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
858 getSignExtendExpr(Step, Ty),
859 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000860 }
861 }
862 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000863
Chris Lattnerb3364092006-10-04 21:49:37 +0000864 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000865 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
866 return Result;
867}
868
Dan Gohman01ecca22009-04-27 20:16:15 +0000869SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
870 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000871 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000872 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000873 assert(isSCEVable(Ty) &&
874 "This is not a conversion to a SCEVable type!");
875 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000876
Dan Gohman622ed672009-05-04 22:02:23 +0000877 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000878 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000879 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
880 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
881 return getUnknown(C);
882 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000883
Dan Gohman20900ca2009-04-22 16:20:48 +0000884 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000885 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000886 return getSignExtendExpr(SS->getOperand(), Ty);
887
Dan Gohman01ecca22009-04-27 20:16:15 +0000888 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000889 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000890 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000891 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000892 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000893 if (AR->isAffine()) {
894 // Check whether the backedge-taken count is SCEVCouldNotCompute.
895 // Note that this serves two purposes: It filters out loops that are
896 // simply not analyzable, and it covers the case where this code is
897 // being called from within backedge-taken count analysis, such that
898 // attempting to ask for the backedge-taken count would likely result
899 // in infinite recursion. In the later case, the analysis code will
900 // cope with a conservative value, and it will take care to purge
901 // that value once it has finished.
Dan Gohmana1af7572009-04-30 20:47:05 +0000902 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
903 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000904 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000905 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000906 SCEVHandle Start = AR->getStart();
907 SCEVHandle Step = AR->getStepRecurrence(*this);
908
909 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000910 // the addrec's type. The count is always unsigned.
Dan Gohmana1af7572009-04-30 20:47:05 +0000911 SCEVHandle CastedMaxBECount =
912 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman5183cae2009-05-18 15:58:39 +0000913 SCEVHandle RecastedMaxBECount =
914 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
915 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000916 const Type *WideTy =
917 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000918 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000919 SCEVHandle SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000920 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000921 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000922 SCEVHandle Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000923 SCEVHandle OperandExtendedAdd =
924 getAddExpr(getSignExtendExpr(Start, WideTy),
925 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
926 getSignExtendExpr(Step, WideTy)));
927 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000928 // Return the expression with the addrec on the outside.
929 return getAddRecExpr(getSignExtendExpr(Start, Ty),
930 getSignExtendExpr(Step, Ty),
931 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000932 }
933 }
934 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000935
936 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
937 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
938 return Result;
939}
940
Dan Gohman6c0866c2009-05-24 23:45:28 +0000941/// getAddExpr - Get a canonical add expression, or something simpler if
942/// possible.
Dan Gohman246b2562007-10-22 18:31:58 +0000943SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000944 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000945 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +0000946#ifndef NDEBUG
947 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
948 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
949 getEffectiveSCEVType(Ops[0]->getType()) &&
950 "SCEVAddExpr operand types don't match!");
951#endif
Chris Lattner53e677a2004-04-02 20:23:17 +0000952
953 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +0000954 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +0000955
956 // If there are any constants, fold them together.
957 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +0000958 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000959 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000960 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +0000961 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000962 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000963 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
964 RHSC->getValue()->getValue());
965 Ops[0] = getConstant(Fold);
966 Ops.erase(Ops.begin()+1); // Erase the folded element
967 if (Ops.size() == 1) return Ops[0];
968 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000969 }
970
971 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +0000972 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000973 Ops.erase(Ops.begin());
974 --Idx;
975 }
976 }
977
Chris Lattner627018b2004-04-07 16:16:11 +0000978 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000979
Chris Lattner53e677a2004-04-02 20:23:17 +0000980 // Okay, check to see if the same value occurs in the operand list twice. If
981 // so, merge them together into an multiply expression. Since we sorted the
982 // list, these values are required to be adjacent.
983 const Type *Ty = Ops[0]->getType();
984 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
985 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
986 // Found a match, merge the two values into a multiply, and add any
987 // remaining values to the result.
Dan Gohman246b2562007-10-22 18:31:58 +0000988 SCEVHandle Two = getIntegerSCEV(2, Ty);
989 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +0000990 if (Ops.size() == 2)
991 return Mul;
992 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
993 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +0000994 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000995 }
996
Dan Gohman728c7f32009-05-08 21:03:19 +0000997 // Check for truncates. If all the operands are truncated from the same
998 // type, see if factoring out the truncate would permit the result to be
999 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1000 // if the contents of the resulting outer trunc fold to something simple.
1001 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1002 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1003 const Type *DstType = Trunc->getType();
1004 const Type *SrcType = Trunc->getOperand()->getType();
1005 std::vector<SCEVHandle> LargeOps;
1006 bool Ok = true;
1007 // Check all the operands to see if they can be represented in the
1008 // source type of the truncate.
1009 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1010 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1011 if (T->getOperand()->getType() != SrcType) {
1012 Ok = false;
1013 break;
1014 }
1015 LargeOps.push_back(T->getOperand());
1016 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1017 // This could be either sign or zero extension, but sign extension
1018 // is much more likely to be foldable here.
1019 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1020 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1021 std::vector<SCEVHandle> LargeMulOps;
1022 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1023 if (const SCEVTruncateExpr *T =
1024 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1025 if (T->getOperand()->getType() != SrcType) {
1026 Ok = false;
1027 break;
1028 }
1029 LargeMulOps.push_back(T->getOperand());
1030 } else if (const SCEVConstant *C =
1031 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1032 // This could be either sign or zero extension, but sign extension
1033 // is much more likely to be foldable here.
1034 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1035 } else {
1036 Ok = false;
1037 break;
1038 }
1039 }
1040 if (Ok)
1041 LargeOps.push_back(getMulExpr(LargeMulOps));
1042 } else {
1043 Ok = false;
1044 break;
1045 }
1046 }
1047 if (Ok) {
1048 // Evaluate the expression in the larger type.
1049 SCEVHandle Fold = getAddExpr(LargeOps);
1050 // If it folds to something simple, use it. Otherwise, don't.
1051 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1052 return getTruncateExpr(Fold, DstType);
1053 }
1054 }
1055
1056 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001057 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1058 ++Idx;
1059
1060 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001061 if (Idx < Ops.size()) {
1062 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001063 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001064 // If we have an add, expand the add operands onto the end of the operands
1065 // list.
1066 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1067 Ops.erase(Ops.begin()+Idx);
1068 DeletedAdd = true;
1069 }
1070
1071 // If we deleted at least one add, we added operands to the end of the list,
1072 // and they are not necessarily sorted. Recurse to resort and resimplify
1073 // any operands we just aquired.
1074 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001075 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001076 }
1077
1078 // Skip over the add expression until we get to a multiply.
1079 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1080 ++Idx;
1081
1082 // If we are adding something to a multiply expression, make sure the
1083 // something is not already an operand of the multiply. If so, merge it into
1084 // the multiply.
1085 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001086 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001087 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001088 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001089 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001090 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001091 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1092 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
1093 if (Mul->getNumOperands() != 2) {
1094 // If the multiply has more than two operands, we must get the
1095 // Y*Z term.
1096 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1097 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001098 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001099 }
Dan Gohman246b2562007-10-22 18:31:58 +00001100 SCEVHandle One = getIntegerSCEV(1, Ty);
1101 SCEVHandle AddOne = getAddExpr(InnerMul, One);
1102 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001103 if (Ops.size() == 2) return OuterMul;
1104 if (AddOp < Idx) {
1105 Ops.erase(Ops.begin()+AddOp);
1106 Ops.erase(Ops.begin()+Idx-1);
1107 } else {
1108 Ops.erase(Ops.begin()+Idx);
1109 Ops.erase(Ops.begin()+AddOp-1);
1110 }
1111 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001112 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001113 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001114
Chris Lattner53e677a2004-04-02 20:23:17 +00001115 // Check this multiply against other multiplies being added together.
1116 for (unsigned OtherMulIdx = Idx+1;
1117 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1118 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001119 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001120 // If MulOp occurs in OtherMul, we can fold the two multiplies
1121 // together.
1122 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1123 OMulOp != e; ++OMulOp)
1124 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1125 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1126 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1127 if (Mul->getNumOperands() != 2) {
1128 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1129 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001130 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001131 }
1132 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1133 if (OtherMul->getNumOperands() != 2) {
1134 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
1135 OtherMul->op_end());
1136 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001137 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001138 }
Dan Gohman246b2562007-10-22 18:31:58 +00001139 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1140 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001141 if (Ops.size() == 2) return OuterMul;
1142 Ops.erase(Ops.begin()+Idx);
1143 Ops.erase(Ops.begin()+OtherMulIdx-1);
1144 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001145 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001146 }
1147 }
1148 }
1149 }
1150
1151 // If there are any add recurrences in the operands list, see if any other
1152 // added values are loop invariant. If so, we can fold them into the
1153 // recurrence.
1154 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1155 ++Idx;
1156
1157 // Scan over all recurrences, trying to fold loop invariants into them.
1158 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1159 // Scan all of the other operands to this add and add them to the vector if
1160 // they are loop invariant w.r.t. the recurrence.
1161 std::vector<SCEVHandle> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001162 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001163 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1164 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1165 LIOps.push_back(Ops[i]);
1166 Ops.erase(Ops.begin()+i);
1167 --i; --e;
1168 }
1169
1170 // If we found some loop invariants, fold them into the recurrence.
1171 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001172 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001173 LIOps.push_back(AddRec->getStart());
1174
1175 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001176 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001177
Dan Gohman246b2562007-10-22 18:31:58 +00001178 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001179 // If all of the other operands were loop invariant, we are done.
1180 if (Ops.size() == 1) return NewRec;
1181
1182 // Otherwise, add the folded AddRec by the non-liv parts.
1183 for (unsigned i = 0;; ++i)
1184 if (Ops[i] == AddRec) {
1185 Ops[i] = NewRec;
1186 break;
1187 }
Dan Gohman246b2562007-10-22 18:31:58 +00001188 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001189 }
1190
1191 // Okay, if there weren't any loop invariants to be folded, check to see if
1192 // there are multiple AddRec's with the same loop induction variable being
1193 // added together. If so, we can fold them.
1194 for (unsigned OtherIdx = Idx+1;
1195 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1196 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001197 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001198 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1199 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1200 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1201 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1202 if (i >= NewOps.size()) {
1203 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1204 OtherAddRec->op_end());
1205 break;
1206 }
Dan Gohman246b2562007-10-22 18:31:58 +00001207 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001208 }
Dan Gohman246b2562007-10-22 18:31:58 +00001209 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001210
1211 if (Ops.size() == 2) return NewAddRec;
1212
1213 Ops.erase(Ops.begin()+Idx);
1214 Ops.erase(Ops.begin()+OtherIdx-1);
1215 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001216 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001217 }
1218 }
1219
1220 // Otherwise couldn't fold anything into this recurrence. Move onto the
1221 // next one.
1222 }
1223
1224 // Okay, it looks like we really DO need an add expr. Check to see if we
1225 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001226 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001227 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1228 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +00001229 if (Result == 0) Result = new SCEVAddExpr(Ops);
1230 return Result;
1231}
1232
1233
Dan Gohman6c0866c2009-05-24 23:45:28 +00001234/// getMulExpr - Get a canonical multiply expression, or something simpler if
1235/// possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001236SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001237 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00001238#ifndef NDEBUG
1239 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1240 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1241 getEffectiveSCEVType(Ops[0]->getType()) &&
1242 "SCEVMulExpr operand types don't match!");
1243#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001244
1245 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001246 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001247
1248 // If there are any constants, fold them together.
1249 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001250 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001251
1252 // C1*(C2+V) -> C1*C2 + C1*V
1253 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001254 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001255 if (Add->getNumOperands() == 2 &&
1256 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001257 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1258 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001259
1260
1261 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001262 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001263 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001264 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1265 RHSC->getValue()->getValue());
1266 Ops[0] = getConstant(Fold);
1267 Ops.erase(Ops.begin()+1); // Erase the folded element
1268 if (Ops.size() == 1) return Ops[0];
1269 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001270 }
1271
1272 // If we are left with a constant one being multiplied, strip it off.
1273 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1274 Ops.erase(Ops.begin());
1275 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001276 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001277 // If we have a multiply of zero, it will always be zero.
1278 return Ops[0];
1279 }
1280 }
1281
1282 // Skip over the add expression until we get to a multiply.
1283 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1284 ++Idx;
1285
1286 if (Ops.size() == 1)
1287 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001288
Chris Lattner53e677a2004-04-02 20:23:17 +00001289 // If there are mul operands inline them all into this expression.
1290 if (Idx < Ops.size()) {
1291 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001292 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001293 // If we have an mul, expand the mul operands onto the end of the operands
1294 // list.
1295 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1296 Ops.erase(Ops.begin()+Idx);
1297 DeletedMul = true;
1298 }
1299
1300 // If we deleted at least one mul, we added operands to the end of the list,
1301 // and they are not necessarily sorted. Recurse to resort and resimplify
1302 // any operands we just aquired.
1303 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001304 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001305 }
1306
1307 // If there are any add recurrences in the operands list, see if any other
1308 // added values are loop invariant. If so, we can fold them into the
1309 // recurrence.
1310 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1311 ++Idx;
1312
1313 // Scan over all recurrences, trying to fold loop invariants into them.
1314 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1315 // Scan all of the other operands to this mul and add them to the vector if
1316 // they are loop invariant w.r.t. the recurrence.
1317 std::vector<SCEVHandle> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001318 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001319 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1320 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1321 LIOps.push_back(Ops[i]);
1322 Ops.erase(Ops.begin()+i);
1323 --i; --e;
1324 }
1325
1326 // If we found some loop invariants, fold them into the recurrence.
1327 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001328 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001329 std::vector<SCEVHandle> NewOps;
1330 NewOps.reserve(AddRec->getNumOperands());
1331 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001332 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001333 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001334 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001335 } else {
1336 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1337 std::vector<SCEVHandle> MulOps(LIOps);
1338 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001339 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001340 }
1341 }
1342
Dan Gohman246b2562007-10-22 18:31:58 +00001343 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001344
1345 // If all of the other operands were loop invariant, we are done.
1346 if (Ops.size() == 1) return NewRec;
1347
1348 // Otherwise, multiply the folded AddRec by the non-liv parts.
1349 for (unsigned i = 0;; ++i)
1350 if (Ops[i] == AddRec) {
1351 Ops[i] = NewRec;
1352 break;
1353 }
Dan Gohman246b2562007-10-22 18:31:58 +00001354 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001355 }
1356
1357 // Okay, if there weren't any loop invariants to be folded, check to see if
1358 // there are multiple AddRec's with the same loop induction variable being
1359 // multiplied together. If so, we can fold them.
1360 for (unsigned OtherIdx = Idx+1;
1361 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1362 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001363 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001364 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1365 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001366 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman246b2562007-10-22 18:31:58 +00001367 SCEVHandle NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001368 G->getStart());
Dan Gohman246b2562007-10-22 18:31:58 +00001369 SCEVHandle B = F->getStepRecurrence(*this);
1370 SCEVHandle D = G->getStepRecurrence(*this);
1371 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1372 getMulExpr(G, B),
1373 getMulExpr(B, D));
1374 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1375 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001376 if (Ops.size() == 2) return NewAddRec;
1377
1378 Ops.erase(Ops.begin()+Idx);
1379 Ops.erase(Ops.begin()+OtherIdx-1);
1380 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001381 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001382 }
1383 }
1384
1385 // Otherwise couldn't fold anything into this recurrence. Move onto the
1386 // next one.
1387 }
1388
1389 // Okay, it looks like we really DO need an mul expr. Check to see if we
1390 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001391 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001392 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1393 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001394 if (Result == 0)
1395 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001396 return Result;
1397}
1398
Dan Gohman6c0866c2009-05-24 23:45:28 +00001399/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1400/// possible.
Dan Gohmanbf2176a2009-05-04 22:23:18 +00001401SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1402 const SCEVHandle &RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001403 assert(getEffectiveSCEVType(LHS->getType()) ==
1404 getEffectiveSCEVType(RHS->getType()) &&
1405 "SCEVUDivExpr operand types don't match!");
1406
Dan Gohman622ed672009-05-04 22:02:23 +00001407 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001408 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky789558d2009-01-13 09:18:58 +00001409 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001410 if (RHSC->isZero())
1411 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001412
Dan Gohman185cf032009-05-08 20:18:49 +00001413 // Determine if the division can be folded into the operands of
1414 // its operands.
1415 // TODO: Generalize this to non-constants by using known-bits information.
1416 const Type *Ty = LHS->getType();
1417 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1418 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1419 // For non-power-of-two values, effectively round the value up to the
1420 // nearest power of two.
1421 if (!RHSC->getValue()->getValue().isPowerOf2())
1422 ++MaxShiftAmt;
1423 const IntegerType *ExtTy =
1424 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1425 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1426 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1427 if (const SCEVConstant *Step =
1428 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1429 if (!Step->getValue()->getValue()
1430 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001431 getZeroExtendExpr(AR, ExtTy) ==
1432 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1433 getZeroExtendExpr(Step, ExtTy),
1434 AR->getLoop())) {
Dan Gohman185cf032009-05-08 20:18:49 +00001435 std::vector<SCEVHandle> Operands;
1436 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1437 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1438 return getAddRecExpr(Operands, AR->getLoop());
1439 }
1440 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001441 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1442 std::vector<SCEVHandle> Operands;
1443 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1444 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1445 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001446 // Find an operand that's safely divisible.
1447 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1448 SCEVHandle Op = M->getOperand(i);
1449 SCEVHandle Div = getUDivExpr(Op, RHSC);
1450 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohmanb0285932009-05-08 23:11:16 +00001451 Operands = M->getOperands();
Dan Gohman185cf032009-05-08 20:18:49 +00001452 Operands[i] = Div;
1453 return getMulExpr(Operands);
1454 }
1455 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001456 }
Dan Gohman185cf032009-05-08 20:18:49 +00001457 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001458 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1459 std::vector<SCEVHandle> Operands;
1460 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1461 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1462 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1463 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001464 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1465 SCEVHandle Op = getUDivExpr(A->getOperand(i), RHS);
1466 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1467 break;
1468 Operands.push_back(Op);
1469 }
1470 if (Operands.size() == A->getNumOperands())
1471 return getAddExpr(Operands);
1472 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001473 }
Dan Gohman185cf032009-05-08 20:18:49 +00001474
1475 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001476 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001477 Constant *LHSCV = LHSC->getValue();
1478 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001479 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001480 }
1481 }
1482
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001483 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1484 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001485 return Result;
1486}
1487
1488
Dan Gohman6c0866c2009-05-24 23:45:28 +00001489/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1490/// Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001491SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Chris Lattner53e677a2004-04-02 20:23:17 +00001492 const SCEVHandle &Step, const Loop *L) {
1493 std::vector<SCEVHandle> Operands;
1494 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001495 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001496 if (StepChrec->getLoop() == L) {
1497 Operands.insert(Operands.end(), StepChrec->op_begin(),
1498 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001499 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001500 }
1501
1502 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001503 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001504}
1505
Dan Gohman6c0866c2009-05-24 23:45:28 +00001506/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1507/// Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001508SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001509 const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001510 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001511#ifndef NDEBUG
1512 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1513 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1514 getEffectiveSCEVType(Operands[0]->getType()) &&
1515 "SCEVAddRecExpr operand types don't match!");
1516#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001517
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001518 if (Operands.back()->isZero()) {
1519 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001520 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001521 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001522
Dan Gohmand9cc7492008-08-08 18:33:12 +00001523 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001524 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmand9cc7492008-08-08 18:33:12 +00001525 const Loop* NestedLoop = NestedAR->getLoop();
1526 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1527 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1528 NestedAR->op_end());
1529 SCEVHandle NestedARHandle(NestedAR);
1530 Operands[0] = NestedAR->getStart();
1531 NestedOperands[0] = getAddRecExpr(Operands, L);
1532 return getAddRecExpr(NestedOperands, NestedLoop);
1533 }
1534 }
1535
Dan Gohman35738ac2009-05-04 22:30:44 +00001536 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1537 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +00001538 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1539 return Result;
1540}
1541
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001542SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1543 const SCEVHandle &RHS) {
1544 std::vector<SCEVHandle> Ops;
1545 Ops.push_back(LHS);
1546 Ops.push_back(RHS);
1547 return getSMaxExpr(Ops);
1548}
1549
1550SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1551 assert(!Ops.empty() && "Cannot get empty smax!");
1552 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001553#ifndef NDEBUG
1554 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1555 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1556 getEffectiveSCEVType(Ops[0]->getType()) &&
1557 "SCEVSMaxExpr operand types don't match!");
1558#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001559
1560 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001561 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001562
1563 // If there are any constants, fold them together.
1564 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001565 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001566 ++Idx;
1567 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001568 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001569 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001570 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001571 APIntOps::smax(LHSC->getValue()->getValue(),
1572 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001573 Ops[0] = getConstant(Fold);
1574 Ops.erase(Ops.begin()+1); // Erase the folded element
1575 if (Ops.size() == 1) return Ops[0];
1576 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001577 }
1578
1579 // If we are left with a constant -inf, strip it off.
1580 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1581 Ops.erase(Ops.begin());
1582 --Idx;
1583 }
1584 }
1585
1586 if (Ops.size() == 1) return Ops[0];
1587
1588 // Find the first SMax
1589 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1590 ++Idx;
1591
1592 // Check to see if one of the operands is an SMax. If so, expand its operands
1593 // onto our operand list, and recurse to simplify.
1594 if (Idx < Ops.size()) {
1595 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001596 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001597 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1598 Ops.erase(Ops.begin()+Idx);
1599 DeletedSMax = true;
1600 }
1601
1602 if (DeletedSMax)
1603 return getSMaxExpr(Ops);
1604 }
1605
1606 // Okay, check to see if the same value occurs in the operand list twice. If
1607 // so, delete one. Since we sorted the list, these values are required to
1608 // be adjacent.
1609 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1610 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1611 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1612 --i; --e;
1613 }
1614
1615 if (Ops.size() == 1) return Ops[0];
1616
1617 assert(!Ops.empty() && "Reduced smax down to nothing!");
1618
Nick Lewycky3e630762008-02-20 06:48:22 +00001619 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001620 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001621 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001622 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1623 SCEVOps)];
1624 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1625 return Result;
1626}
1627
Nick Lewycky3e630762008-02-20 06:48:22 +00001628SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1629 const SCEVHandle &RHS) {
1630 std::vector<SCEVHandle> Ops;
1631 Ops.push_back(LHS);
1632 Ops.push_back(RHS);
1633 return getUMaxExpr(Ops);
1634}
1635
1636SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1637 assert(!Ops.empty() && "Cannot get empty umax!");
1638 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001639#ifndef NDEBUG
1640 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1641 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1642 getEffectiveSCEVType(Ops[0]->getType()) &&
1643 "SCEVUMaxExpr operand types don't match!");
1644#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00001645
1646 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001647 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00001648
1649 // If there are any constants, fold them together.
1650 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001651 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001652 ++Idx;
1653 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001654 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001655 // We found two constants, fold them together!
1656 ConstantInt *Fold = ConstantInt::get(
1657 APIntOps::umax(LHSC->getValue()->getValue(),
1658 RHSC->getValue()->getValue()));
1659 Ops[0] = getConstant(Fold);
1660 Ops.erase(Ops.begin()+1); // Erase the folded element
1661 if (Ops.size() == 1) return Ops[0];
1662 LHSC = cast<SCEVConstant>(Ops[0]);
1663 }
1664
1665 // If we are left with a constant zero, strip it off.
1666 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1667 Ops.erase(Ops.begin());
1668 --Idx;
1669 }
1670 }
1671
1672 if (Ops.size() == 1) return Ops[0];
1673
1674 // Find the first UMax
1675 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1676 ++Idx;
1677
1678 // Check to see if one of the operands is a UMax. If so, expand its operands
1679 // onto our operand list, and recurse to simplify.
1680 if (Idx < Ops.size()) {
1681 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001682 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001683 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1684 Ops.erase(Ops.begin()+Idx);
1685 DeletedUMax = true;
1686 }
1687
1688 if (DeletedUMax)
1689 return getUMaxExpr(Ops);
1690 }
1691
1692 // Okay, check to see if the same value occurs in the operand list twice. If
1693 // so, delete one. Since we sorted the list, these values are required to
1694 // be adjacent.
1695 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1696 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1697 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1698 --i; --e;
1699 }
1700
1701 if (Ops.size() == 1) return Ops[0];
1702
1703 assert(!Ops.empty() && "Reduced umax down to nothing!");
1704
1705 // Okay, it looks like we really DO need a umax expr. Check to see if we
1706 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001707 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewycky3e630762008-02-20 06:48:22 +00001708 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1709 SCEVOps)];
1710 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1711 return Result;
1712}
1713
Dan Gohman246b2562007-10-22 18:31:58 +00001714SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001715 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001716 return getConstant(CI);
Dan Gohman2d1be872009-04-16 03:18:22 +00001717 if (isa<ConstantPointerNull>(V))
1718 return getIntegerSCEV(0, V->getType());
Chris Lattnerb3364092006-10-04 21:49:37 +00001719 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001720 if (Result == 0) Result = new SCEVUnknown(V);
1721 return Result;
1722}
1723
Chris Lattner53e677a2004-04-02 20:23:17 +00001724//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001725// Basic SCEV Analysis and PHI Idiom Recognition Code
1726//
1727
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001728/// isSCEVable - Test if values of the given type are analyzable within
1729/// the SCEV framework. This primarily includes integer types, and it
1730/// can optionally include pointer types if the ScalarEvolution class
1731/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001732bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001733 // Integers are always SCEVable.
1734 if (Ty->isInteger())
1735 return true;
1736
1737 // Pointers are SCEVable if TargetData information is available
1738 // to provide pointer size information.
1739 if (isa<PointerType>(Ty))
1740 return TD != NULL;
1741
1742 // Otherwise it's not SCEVable.
1743 return false;
1744}
1745
1746/// getTypeSizeInBits - Return the size in bits of the specified type,
1747/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001748uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001749 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1750
1751 // If we have a TargetData, use it!
1752 if (TD)
1753 return TD->getTypeSizeInBits(Ty);
1754
1755 // Otherwise, we support only integer types.
1756 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1757 return Ty->getPrimitiveSizeInBits();
1758}
1759
1760/// getEffectiveSCEVType - Return a type with the same bitwidth as
1761/// the given type and which represents how SCEV will treat the given
1762/// type, for which isSCEVable must return true. For pointer types,
1763/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001764const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001765 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1766
1767 if (Ty->isInteger())
1768 return Ty;
1769
1770 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1771 return TD->getIntPtrType();
Dan Gohman2d1be872009-04-16 03:18:22 +00001772}
Chris Lattner53e677a2004-04-02 20:23:17 +00001773
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001774SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00001775 return UnknownValue;
1776}
1777
Dan Gohman92fa56e2009-05-04 22:20:30 +00001778/// hasSCEV - Return true if the SCEV for this value has already been
Torok Edwine3d12852009-05-01 08:33:47 +00001779/// computed.
1780bool ScalarEvolution::hasSCEV(Value *V) const {
1781 return Scalars.count(V);
1782}
1783
Chris Lattner53e677a2004-04-02 20:23:17 +00001784/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1785/// expression and create a new one.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001786SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001787 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00001788
Dan Gohman35738ac2009-05-04 22:30:44 +00001789 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001790 if (I != Scalars.end()) return I->second;
1791 SCEVHandle S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00001792 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00001793 return S;
1794}
1795
Dan Gohman2d1be872009-04-16 03:18:22 +00001796/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1797/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001798SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1799 Ty = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001800 Constant *C;
1801 if (Val == 0)
1802 C = Constant::getNullValue(Ty);
1803 else if (Ty->isFloatingPoint())
1804 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1805 APFloat::IEEEdouble, Val));
1806 else
1807 C = ConstantInt::get(Ty, Val);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001808 return getUnknown(C);
Dan Gohman2d1be872009-04-16 03:18:22 +00001809}
1810
1811/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1812///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001813SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohman622ed672009-05-04 22:02:23 +00001814 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001815 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman2d1be872009-04-16 03:18:22 +00001816
1817 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001818 Ty = getEffectiveSCEVType(Ty);
1819 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00001820}
1821
1822/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001823SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohman622ed672009-05-04 22:02:23 +00001824 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001825 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman2d1be872009-04-16 03:18:22 +00001826
1827 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001828 Ty = getEffectiveSCEVType(Ty);
1829 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman2d1be872009-04-16 03:18:22 +00001830 return getMinusSCEV(AllOnes, V);
1831}
1832
1833/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1834///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001835SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001836 const SCEVHandle &RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001837 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001838 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00001839}
1840
1841/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1842/// input value to the specified type. If the type must be extended, it is zero
1843/// extended.
1844SCEVHandle
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001845ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001846 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001847 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001848 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1849 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00001850 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001851 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00001852 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001853 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001854 return getTruncateExpr(V, Ty);
1855 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001856}
1857
1858/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1859/// input value to the specified type. If the type must be extended, it is sign
1860/// extended.
1861SCEVHandle
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001862ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001863 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001864 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001865 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1866 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00001867 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001868 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00001869 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001870 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001871 return getTruncateExpr(V, Ty);
1872 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001873}
1874
Dan Gohman467c4302009-05-13 03:46:30 +00001875/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
1876/// input value to the specified type. If the type must be extended, it is zero
1877/// extended. The conversion must not be narrowing.
1878SCEVHandle
1879ScalarEvolution::getNoopOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
1880 const Type *SrcTy = V->getType();
1881 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1882 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1883 "Cannot noop or zero extend with non-integer arguments!");
1884 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
1885 "getNoopOrZeroExtend cannot truncate!");
1886 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1887 return V; // No conversion
1888 return getZeroExtendExpr(V, Ty);
1889}
1890
1891/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
1892/// input value to the specified type. If the type must be extended, it is sign
1893/// extended. The conversion must not be narrowing.
1894SCEVHandle
1895ScalarEvolution::getNoopOrSignExtend(const SCEVHandle &V, const Type *Ty) {
1896 const Type *SrcTy = V->getType();
1897 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1898 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1899 "Cannot noop or sign extend with non-integer arguments!");
1900 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
1901 "getNoopOrSignExtend cannot truncate!");
1902 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1903 return V; // No conversion
1904 return getSignExtendExpr(V, Ty);
1905}
1906
1907/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
1908/// input value to the specified type. The conversion must not be widening.
1909SCEVHandle
1910ScalarEvolution::getTruncateOrNoop(const SCEVHandle &V, const Type *Ty) {
1911 const Type *SrcTy = V->getType();
1912 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1913 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1914 "Cannot truncate or noop with non-integer arguments!");
1915 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
1916 "getTruncateOrNoop cannot extend!");
1917 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1918 return V; // No conversion
1919 return getTruncateExpr(V, Ty);
1920}
1921
Chris Lattner4dc534c2005-02-13 04:37:18 +00001922/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1923/// the specified instruction and replaces any references to the symbolic value
1924/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001925void ScalarEvolution::
Chris Lattner4dc534c2005-02-13 04:37:18 +00001926ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1927 const SCEVHandle &NewVal) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001928 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
1929 Scalars.find(SCEVCallbackVH(I, this));
Chris Lattner4dc534c2005-02-13 04:37:18 +00001930 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001931
Chris Lattner4dc534c2005-02-13 04:37:18 +00001932 SCEVHandle NV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001933 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001934 if (NV == SI->second) return; // No change.
1935
1936 SI->second = NV; // Update the scalars map!
1937
1938 // Any instruction values that use this instruction might also need to be
1939 // updated!
1940 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1941 UI != E; ++UI)
1942 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1943}
Chris Lattner53e677a2004-04-02 20:23:17 +00001944
1945/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1946/// a loop header, making it a potential recurrence, or it doesn't.
1947///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001948SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001949 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001950 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00001951 if (L->getHeader() == PN->getParent()) {
1952 // If it lives in the loop header, it has two incoming values, one
1953 // from outside the loop, and one from inside.
1954 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1955 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001956
Chris Lattner53e677a2004-04-02 20:23:17 +00001957 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001958 SCEVHandle SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001959 assert(Scalars.find(PN) == Scalars.end() &&
1960 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00001961 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00001962
1963 // Using this symbolic name for the PHI, analyze the value coming around
1964 // the back-edge.
1965 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1966
1967 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1968 // has a special value for the first iteration of the loop.
1969
1970 // If the value coming around the backedge is an add with the symbolic
1971 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00001972 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001973 // If there is a single occurrence of the symbolic value, replace it
1974 // with a recurrence.
1975 unsigned FoundIndex = Add->getNumOperands();
1976 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1977 if (Add->getOperand(i) == SymbolicName)
1978 if (FoundIndex == e) {
1979 FoundIndex = i;
1980 break;
1981 }
1982
1983 if (FoundIndex != Add->getNumOperands()) {
1984 // Create an add with everything but the specified operand.
1985 std::vector<SCEVHandle> Ops;
1986 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1987 if (i != FoundIndex)
1988 Ops.push_back(Add->getOperand(i));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001989 SCEVHandle Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001990
1991 // This is not a valid addrec if the step amount is varying each
1992 // loop iteration, but is not itself an addrec in this loop.
1993 if (Accum->isLoopInvariant(L) ||
1994 (isa<SCEVAddRecExpr>(Accum) &&
1995 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1996 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001997 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001998
1999 // Okay, for the entire analysis of this edge we assumed the PHI
2000 // to be symbolic. We now need to go back and update all of the
2001 // entries for the scalars that use the PHI (except for the PHI
2002 // itself) to use the new analyzed value instead of the "symbolic"
2003 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00002004 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002005 return PHISCEV;
2006 }
2007 }
Dan Gohman622ed672009-05-04 22:02:23 +00002008 } else if (const SCEVAddRecExpr *AddRec =
2009 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002010 // Otherwise, this could be a loop like this:
2011 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2012 // In this case, j = {1,+,1} and BEValue is j.
2013 // Because the other in-value of i (0) fits the evolution of BEValue
2014 // i really is an addrec evolution.
2015 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2016 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2017
2018 // If StartVal = j.start - j.stride, we can use StartVal as the
2019 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002020 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002021 AddRec->getOperand(1))) {
Chris Lattner97156e72006-04-26 18:34:07 +00002022 SCEVHandle PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002023 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002024
2025 // Okay, for the entire analysis of this edge we assumed the PHI
2026 // to be symbolic. We now need to go back and update all of the
2027 // entries for the scalars that use the PHI (except for the PHI
2028 // itself) to use the new analyzed value instead of the "symbolic"
2029 // value.
2030 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2031 return PHISCEV;
2032 }
2033 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002034 }
2035
2036 return SymbolicName;
2037 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002038
Chris Lattner53e677a2004-04-02 20:23:17 +00002039 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002040 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002041}
2042
Dan Gohman26466c02009-05-08 20:26:55 +00002043/// createNodeForGEP - Expand GEP instructions into add and multiply
2044/// operations. This allows them to be analyzed by regular SCEV code.
2045///
Dan Gohmanfb791602009-05-08 20:58:38 +00002046SCEVHandle ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002047
2048 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmane810b0d2009-05-08 20:36:47 +00002049 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002050 // Don't attempt to analyze GEPs over unsized objects.
2051 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2052 return getUnknown(GEP);
Dan Gohman26466c02009-05-08 20:26:55 +00002053 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002054 gep_type_iterator GTI = gep_type_begin(GEP);
2055 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2056 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002057 I != E; ++I) {
2058 Value *Index = *I;
2059 // Compute the (potentially symbolic) offset in bytes for this index.
2060 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2061 // For a struct, add the member offset.
2062 const StructLayout &SL = *TD->getStructLayout(STy);
2063 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2064 uint64_t Offset = SL.getElementOffset(FieldNo);
2065 TotalOffset = getAddExpr(TotalOffset,
2066 getIntegerSCEV(Offset, IntPtrTy));
2067 } else {
2068 // For an array, add the element offset, explicitly scaled.
2069 SCEVHandle LocalOffset = getSCEV(Index);
2070 if (!isa<PointerType>(LocalOffset->getType()))
2071 // Getelementptr indicies are signed.
2072 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2073 IntPtrTy);
2074 LocalOffset =
2075 getMulExpr(LocalOffset,
Duncan Sands777d2302009-05-09 07:06:46 +00002076 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman26466c02009-05-08 20:26:55 +00002077 IntPtrTy));
2078 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2079 }
2080 }
2081 return getAddExpr(getSCEV(Base), TotalOffset);
2082}
2083
Nick Lewycky83bb0052007-11-22 07:59:40 +00002084/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2085/// guaranteed to end in (at every loop iteration). It is, at the same time,
2086/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2087/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002088static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Dan Gohman622ed672009-05-04 22:02:23 +00002089 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002090 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002091
Dan Gohman622ed672009-05-04 22:02:23 +00002092 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002093 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
2094 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002095
Dan Gohman622ed672009-05-04 22:02:23 +00002096 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002097 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2098 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
Dan Gohman42a58752009-05-12 01:23:18 +00002099 SE.getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002100 }
2101
Dan Gohman622ed672009-05-04 22:02:23 +00002102 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002103 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2104 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
Dan Gohman42a58752009-05-12 01:23:18 +00002105 SE.getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002106 }
2107
Dan Gohman622ed672009-05-04 22:02:23 +00002108 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002109 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002110 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky83bb0052007-11-22 07:59:40 +00002111 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002112 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002113 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002114 }
2115
Dan Gohman622ed672009-05-04 22:02:23 +00002116 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002117 // The result is the sum of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002118 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
2119 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002120 for (unsigned i = 1, e = M->getNumOperands();
2121 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002122 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002123 BitWidth);
2124 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002125 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002126
Dan Gohman622ed672009-05-04 22:02:23 +00002127 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002128 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002129 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky83bb0052007-11-22 07:59:40 +00002130 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002131 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002132 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002133 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002134
Dan Gohman622ed672009-05-04 22:02:23 +00002135 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002136 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002137 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002138 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002139 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002140 return MinOpRes;
2141 }
2142
Dan Gohman622ed672009-05-04 22:02:23 +00002143 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002144 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002145 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky3e630762008-02-20 06:48:22 +00002146 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002147 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky3e630762008-02-20 06:48:22 +00002148 return MinOpRes;
2149 }
2150
Nick Lewycky789558d2009-01-13 09:18:58 +00002151 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky83bb0052007-11-22 07:59:40 +00002152 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002153}
Chris Lattner53e677a2004-04-02 20:23:17 +00002154
2155/// createSCEV - We know that there is no SCEV for the specified value.
2156/// Analyze the expression.
2157///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002158SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002159 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002160 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00002161
Dan Gohman6c459a22008-06-22 19:56:46 +00002162 unsigned Opcode = Instruction::UserOp1;
2163 if (Instruction *I = dyn_cast<Instruction>(V))
2164 Opcode = I->getOpcode();
2165 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2166 Opcode = CE->getOpcode();
2167 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002168 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00002169
Dan Gohman6c459a22008-06-22 19:56:46 +00002170 User *U = cast<User>(V);
2171 switch (Opcode) {
2172 case Instruction::Add:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002173 return getAddExpr(getSCEV(U->getOperand(0)),
2174 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002175 case Instruction::Mul:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002176 return getMulExpr(getSCEV(U->getOperand(0)),
2177 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002178 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002179 return getUDivExpr(getSCEV(U->getOperand(0)),
2180 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002181 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002182 return getMinusSCEV(getSCEV(U->getOperand(0)),
2183 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002184 case Instruction::And:
2185 // For an expression like x&255 that merely masks off the high bits,
2186 // use zext(trunc(x)) as the SCEV expression.
2187 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002188 if (CI->isNullValue())
2189 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00002190 if (CI->isAllOnesValue())
2191 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002192 const APInt &A = CI->getValue();
2193 unsigned Ones = A.countTrailingOnes();
2194 if (APIntOps::isMask(Ones, A))
2195 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002196 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
2197 IntegerType::get(Ones)),
2198 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00002199 }
2200 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00002201 case Instruction::Or:
2202 // If the RHS of the Or is a constant, we may have something like:
2203 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2204 // optimizations will transparently handle this case.
2205 //
2206 // In order for this transformation to be safe, the LHS must be of the
2207 // form X*(2^n) and the Or constant must be less than 2^n.
2208 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2209 SCEVHandle LHS = getSCEV(U->getOperand(0));
2210 const APInt &CIVal = CI->getValue();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002211 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman6c459a22008-06-22 19:56:46 +00002212 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002213 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00002214 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002215 break;
2216 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00002217 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00002218 // If the RHS of the xor is a signbit, then this is just an add.
2219 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00002220 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002221 return getAddExpr(getSCEV(U->getOperand(0)),
2222 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002223
2224 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00002225 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002226 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00002227
2228 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2229 // This is a variant of the check for xor with -1, and it handles
2230 // the case where instcombine has trimmed non-demanded bits out
2231 // of an xor with -1.
2232 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2233 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2234 if (BO->getOpcode() == Instruction::And &&
2235 LCI->getValue() == CI->getValue())
2236 if (const SCEVZeroExtendExpr *Z =
2237 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0))))
2238 return getZeroExtendExpr(getNotSCEV(Z->getOperand()),
2239 U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002240 }
2241 break;
2242
2243 case Instruction::Shl:
2244 // Turn shift left of a constant amount into a multiply.
2245 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2246 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2247 Constant *X = ConstantInt::get(
2248 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002249 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00002250 }
2251 break;
2252
Nick Lewycky01eaf802008-07-07 06:15:49 +00002253 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00002254 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00002255 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2256 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2257 Constant *X = ConstantInt::get(
2258 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002259 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002260 }
2261 break;
2262
Dan Gohman4ee29af2009-04-21 02:26:00 +00002263 case Instruction::AShr:
2264 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2265 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2266 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2267 if (L->getOpcode() == Instruction::Shl &&
2268 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002269 unsigned BitWidth = getTypeSizeInBits(U->getType());
2270 uint64_t Amt = BitWidth - CI->getZExtValue();
2271 if (Amt == BitWidth)
2272 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2273 if (Amt > BitWidth)
2274 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00002275 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002276 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002277 IntegerType::get(Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00002278 U->getType());
2279 }
2280 break;
2281
Dan Gohman6c459a22008-06-22 19:56:46 +00002282 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002283 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002284
2285 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002286 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002287
2288 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002289 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002290
2291 case Instruction::BitCast:
2292 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002293 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00002294 return getSCEV(U->getOperand(0));
2295 break;
2296
Dan Gohman2d1be872009-04-16 03:18:22 +00002297 case Instruction::IntToPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002298 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002299 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002300 TD->getIntPtrType());
Dan Gohman2d1be872009-04-16 03:18:22 +00002301
2302 case Instruction::PtrToInt:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002303 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002304 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2305 U->getType());
2306
Dan Gohman26466c02009-05-08 20:26:55 +00002307 case Instruction::GetElementPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002308 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanfb791602009-05-08 20:58:38 +00002309 return createNodeForGEP(U);
Dan Gohman2d1be872009-04-16 03:18:22 +00002310
Dan Gohman6c459a22008-06-22 19:56:46 +00002311 case Instruction::PHI:
2312 return createNodeForPHI(cast<PHINode>(U));
2313
2314 case Instruction::Select:
2315 // This could be a smax or umax that was lowered earlier.
2316 // Try to recover it.
2317 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2318 Value *LHS = ICI->getOperand(0);
2319 Value *RHS = ICI->getOperand(1);
2320 switch (ICI->getPredicate()) {
2321 case ICmpInst::ICMP_SLT:
2322 case ICmpInst::ICMP_SLE:
2323 std::swap(LHS, RHS);
2324 // fall through
2325 case ICmpInst::ICMP_SGT:
2326 case ICmpInst::ICMP_SGE:
2327 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002328 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002329 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman1fbffe02008-07-30 04:36:32 +00002330 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002331 return getNotSCEV(getSMaxExpr(
2332 getNotSCEV(getSCEV(LHS)),
2333 getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00002334 break;
2335 case ICmpInst::ICMP_ULT:
2336 case ICmpInst::ICMP_ULE:
2337 std::swap(LHS, RHS);
2338 // fall through
2339 case ICmpInst::ICMP_UGT:
2340 case ICmpInst::ICMP_UGE:
2341 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002342 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002343 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2344 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002345 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2346 getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00002347 break;
2348 default:
2349 break;
2350 }
2351 }
2352
2353 default: // We cannot analyze this expression.
2354 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002355 }
2356
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002357 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002358}
2359
2360
2361
2362//===----------------------------------------------------------------------===//
2363// Iteration Count Computation Code
2364//
2365
Dan Gohman46bdfb02009-02-24 18:55:53 +00002366/// getBackedgeTakenCount - If the specified loop has a predictable
2367/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2368/// object. The backedge-taken count is the number of times the loop header
2369/// will be branched to from within the loop. This is one less than the
2370/// trip count of the loop, since it doesn't count the first iteration,
2371/// when the header is branched to from outside the loop.
2372///
2373/// Note that it is not valid to call this method on a loop without a
2374/// loop-invariant backedge-taken count (see
2375/// hasLoopInvariantBackedgeTakenCount).
2376///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002377SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002378 return getBackedgeTakenInfo(L).Exact;
2379}
2380
2381/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2382/// return the least SCEV value that is known never to be less than the
2383/// actual backedge taken count.
2384SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2385 return getBackedgeTakenInfo(L).Max;
2386}
2387
2388const ScalarEvolution::BackedgeTakenInfo &
2389ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00002390 // Initially insert a CouldNotCompute for this loop. If the insertion
2391 // succeeds, procede to actually compute a backedge-taken count and
2392 // update the value. The temporary CouldNotCompute value tells SCEV
2393 // code elsewhere that it shouldn't attempt to request a new
2394 // backedge-taken count, which could result in infinite recursion.
Dan Gohmana1af7572009-04-30 20:47:05 +00002395 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00002396 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2397 if (Pair.second) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002398 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2399 if (ItCount.Exact != UnknownValue) {
2400 assert(ItCount.Exact->isLoopInvariant(L) &&
2401 ItCount.Max->isLoopInvariant(L) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002402 "Computed trip count isn't loop invariant for loop!");
2403 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00002404
Dan Gohman01ecca22009-04-27 20:16:15 +00002405 // Update the value in the map.
2406 Pair.first->second = ItCount;
Chris Lattner53e677a2004-04-02 20:23:17 +00002407 } else if (isa<PHINode>(L->getHeader()->begin())) {
2408 // Only count loops that have phi nodes as not being computable.
2409 ++NumTripCountsNotComputed;
2410 }
Dan Gohmana1af7572009-04-30 20:47:05 +00002411
2412 // Now that we know more about the trip count for this loop, forget any
2413 // existing SCEV values for PHI nodes in this loop since they are only
2414 // conservative estimates made without the benefit
2415 // of trip count information.
2416 if (ItCount.hasAnyInfo())
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00002417 forgetLoopPHIs(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002418 }
Dan Gohman01ecca22009-04-27 20:16:15 +00002419 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00002420}
2421
Dan Gohman46bdfb02009-02-24 18:55:53 +00002422/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohman60f8a632009-02-17 20:49:49 +00002423/// client when it has changed a loop in a way that may effect
Dan Gohman46bdfb02009-02-24 18:55:53 +00002424/// ScalarEvolution's ability to compute a trip count, or if the loop
2425/// is deleted.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002426void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00002427 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00002428 forgetLoopPHIs(L);
2429}
2430
2431/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2432/// PHI nodes in the given loop. This is used when the trip count of
2433/// the loop may have changed.
2434void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohman35738ac2009-05-04 22:30:44 +00002435 BasicBlock *Header = L->getHeader();
2436
Dan Gohmanefb9fbf2009-05-12 01:27:58 +00002437 // Push all Loop-header PHIs onto the Worklist stack, except those
2438 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2439 // a PHI either means that it has an unrecognized structure, or it's
2440 // a PHI that's in the progress of being computed by createNodeForPHI.
2441 // In the former case, additional loop trip count information isn't
2442 // going to change anything. In the later case, createNodeForPHI will
2443 // perform the necessary updates on its own when it gets to that point.
Dan Gohman35738ac2009-05-04 22:30:44 +00002444 SmallVector<Instruction *, 16> Worklist;
2445 for (BasicBlock::iterator I = Header->begin();
Dan Gohmanefb9fbf2009-05-12 01:27:58 +00002446 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2447 std::map<SCEVCallbackVH, SCEVHandle>::iterator It = Scalars.find((Value*)I);
2448 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2449 Worklist.push_back(PN);
2450 }
Dan Gohman35738ac2009-05-04 22:30:44 +00002451
2452 while (!Worklist.empty()) {
2453 Instruction *I = Worklist.pop_back_val();
2454 if (Scalars.erase(I))
2455 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2456 UI != UE; ++UI)
2457 Worklist.push_back(cast<Instruction>(UI));
2458 }
Dan Gohman60f8a632009-02-17 20:49:49 +00002459}
2460
Dan Gohman46bdfb02009-02-24 18:55:53 +00002461/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2462/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00002463ScalarEvolution::BackedgeTakenInfo
2464ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002465 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patelb7211a22007-08-21 00:31:24 +00002466 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002467 L->getExitBlocks(ExitBlocks);
2468 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002469
2470 // Okay, there is one exit block. Try to find the condition that causes the
2471 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002472 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00002473
2474 BasicBlock *ExitingBlock = 0;
2475 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2476 PI != E; ++PI)
2477 if (L->contains(*PI)) {
2478 if (ExitingBlock == 0)
2479 ExitingBlock = *PI;
2480 else
2481 return UnknownValue; // More than one block exiting!
2482 }
2483 assert(ExitingBlock && "No exits from loop, something is broken!");
2484
2485 // Okay, we've computed the exiting block. See what condition causes us to
2486 // exit.
2487 //
2488 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00002489 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2490 if (ExitBr == 0) return UnknownValue;
2491 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00002492
2493 // At this point, we know we have a conditional branch that determines whether
2494 // the loop is exited. However, we don't know if the branch is executed each
2495 // time through the loop. If not, then the execution count of the branch will
2496 // not be equal to the trip count of the loop.
2497 //
2498 // Currently we check for this by checking to see if the Exit branch goes to
2499 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00002500 // times as the loop. We also handle the case where the exit block *is* the
2501 // loop header. This is common for un-rotated loops. More extensive analysis
2502 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00002503 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00002504 ExitBr->getSuccessor(1) != L->getHeader() &&
2505 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00002506 return UnknownValue;
2507
Reid Spencere4d87aa2006-12-23 06:05:41 +00002508 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2509
Eli Friedman361e54d2009-05-09 12:32:42 +00002510 // If it's not an integer or pointer comparison then compute it the hard way.
2511 if (ExitCond == 0)
Dan Gohman46bdfb02009-02-24 18:55:53 +00002512 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Chris Lattner7980fb92004-04-17 18:36:24 +00002513 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00002514
Reid Spencere4d87aa2006-12-23 06:05:41 +00002515 // If the condition was exit on true, convert the condition to exit on false
2516 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00002517 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00002518 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002519 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00002520 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002521
2522 // Handle common loops like: for (X = "string"; *X; ++X)
2523 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2524 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2525 SCEVHandle ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00002526 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Chris Lattner673e02b2004-10-12 01:49:27 +00002527 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2528 }
2529
Chris Lattner53e677a2004-04-02 20:23:17 +00002530 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2531 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2532
2533 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00002534 LHS = getSCEVAtScope(LHS, L);
2535 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002536
Reid Spencere4d87aa2006-12-23 06:05:41 +00002537 // At this point, we would like to compute how many iterations of the
2538 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00002539 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2540 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00002541 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002542 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00002543 }
2544
Chris Lattner53e677a2004-04-02 20:23:17 +00002545 // If we have a comparison of a chrec against a constant, try to use value
2546 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00002547 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2548 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00002549 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00002550 // Form the constant range.
2551 ConstantRange CompRange(
2552 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002553
Eli Friedman361e54d2009-05-09 12:32:42 +00002554 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
2555 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00002556 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002557
Chris Lattner53e677a2004-04-02 20:23:17 +00002558 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002559 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00002560 // Convert to: while (X-Y != 0)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002561 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002562 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002563 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002564 }
2565 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00002566 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002567 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002568 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002569 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002570 }
2571 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002572 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2573 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002574 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002575 }
2576 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002577 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2578 getNotSCEV(RHS), L, true);
2579 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002580 break;
2581 }
2582 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002583 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2584 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002585 break;
2586 }
2587 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002588 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2589 getNotSCEV(RHS), L, false);
2590 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002591 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002592 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002593 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002594#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002595 errs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002596 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002597 errs() << "[unsigned] ";
2598 errs() << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00002599 << Instruction::getOpcodeName(Instruction::ICmp)
2600 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002601#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00002602 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002603 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00002604 return
2605 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2606 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00002607}
2608
Chris Lattner673e02b2004-10-12 01:49:27 +00002609static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00002610EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2611 ScalarEvolution &SE) {
2612 SCEVHandle InVal = SE.getConstant(C);
2613 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002614 assert(isa<SCEVConstant>(Val) &&
2615 "Evaluation of SCEV at constant didn't fold correctly?");
2616 return cast<SCEVConstant>(Val)->getValue();
2617}
2618
2619/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2620/// and a GEP expression (missing the pointer index) indexing into it, return
2621/// the addressed element of the initializer or null if the index expression is
2622/// invalid.
2623static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002624GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00002625 const std::vector<ConstantInt*> &Indices) {
2626 Constant *Init = GV->getInitializer();
2627 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002628 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00002629 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2630 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2631 Init = cast<Constant>(CS->getOperand(Idx));
2632 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2633 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2634 Init = cast<Constant>(CA->getOperand(Idx));
2635 } else if (isa<ConstantAggregateZero>(Init)) {
2636 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2637 assert(Idx < STy->getNumElements() && "Bad struct index!");
2638 Init = Constant::getNullValue(STy->getElementType(Idx));
2639 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2640 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2641 Init = Constant::getNullValue(ATy->getElementType());
2642 } else {
2643 assert(0 && "Unknown constant aggregate type!");
2644 }
2645 return 0;
2646 } else {
2647 return 0; // Unknown initializer type
2648 }
2649 }
2650 return Init;
2651}
2652
Dan Gohman46bdfb02009-02-24 18:55:53 +00002653/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2654/// 'icmp op load X, cst', try to see if we can compute the backedge
2655/// execution count.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002656SCEVHandle ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00002657ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2658 const Loop *L,
2659 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002660 if (LI->isVolatile()) return UnknownValue;
2661
2662 // Check to see if the loaded pointer is a getelementptr of a global.
2663 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2664 if (!GEP) return UnknownValue;
2665
2666 // Make sure that it is really a constant global we are gepping, with an
2667 // initializer, and make sure the first IDX is really 0.
2668 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2669 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2670 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2671 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2672 return UnknownValue;
2673
2674 // Okay, we allow one non-constant index into the GEP instruction.
2675 Value *VarIdx = 0;
2676 std::vector<ConstantInt*> Indexes;
2677 unsigned VarIdxNum = 0;
2678 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2679 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2680 Indexes.push_back(CI);
2681 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2682 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2683 VarIdx = GEP->getOperand(i);
2684 VarIdxNum = i-2;
2685 Indexes.push_back(0);
2686 }
2687
2688 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2689 // Check to see if X is a loop variant variable value now.
2690 SCEVHandle Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00002691 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00002692
2693 // We can only recognize very limited forms of loop index expressions, in
2694 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00002695 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00002696 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2697 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2698 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2699 return UnknownValue;
2700
2701 unsigned MaxSteps = MaxBruteForceIterations;
2702 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002703 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00002704 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002705 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00002706
2707 // Form the GEP offset.
2708 Indexes[VarIdxNum] = Val;
2709
2710 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2711 if (Result == 0) break; // Cannot compute!
2712
2713 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002714 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002715 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00002716 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002717#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002718 errs() << "\n***\n*** Computed loop count " << *ItCst
2719 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2720 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00002721#endif
2722 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002723 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00002724 }
2725 }
2726 return UnknownValue;
2727}
2728
2729
Chris Lattner3221ad02004-04-17 22:58:41 +00002730/// CanConstantFold - Return true if we can constant fold an instruction of the
2731/// specified type, assuming that all operands were constants.
2732static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00002733 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00002734 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2735 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002736
Chris Lattner3221ad02004-04-17 22:58:41 +00002737 if (const CallInst *CI = dyn_cast<CallInst>(I))
2738 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00002739 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00002740 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00002741}
2742
Chris Lattner3221ad02004-04-17 22:58:41 +00002743/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2744/// in the loop that V is derived from. We allow arbitrary operations along the
2745/// way, but the operands of an operation must either be constants or a value
2746/// derived from a constant PHI. If this expression does not fit with these
2747/// constraints, return null.
2748static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2749 // If this is not an instruction, or if this is an instruction outside of the
2750 // loop, it can't be derived from a loop PHI.
2751 Instruction *I = dyn_cast<Instruction>(V);
2752 if (I == 0 || !L->contains(I->getParent())) return 0;
2753
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002754 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002755 if (L->getHeader() == I->getParent())
2756 return PN;
2757 else
2758 // We don't currently keep track of the control flow needed to evaluate
2759 // PHIs, so we cannot handle PHIs inside of loops.
2760 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002761 }
Chris Lattner3221ad02004-04-17 22:58:41 +00002762
2763 // If we won't be able to constant fold this expression even if the operands
2764 // are constants, return early.
2765 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002766
Chris Lattner3221ad02004-04-17 22:58:41 +00002767 // Otherwise, we can evaluate this instruction if all of its operands are
2768 // constant or derived from a PHI node themselves.
2769 PHINode *PHI = 0;
2770 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2771 if (!(isa<Constant>(I->getOperand(Op)) ||
2772 isa<GlobalValue>(I->getOperand(Op)))) {
2773 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2774 if (P == 0) return 0; // Not evolving from PHI
2775 if (PHI == 0)
2776 PHI = P;
2777 else if (PHI != P)
2778 return 0; // Evolving from multiple different PHIs.
2779 }
2780
2781 // This is a expression evolving from a constant PHI!
2782 return PHI;
2783}
2784
2785/// EvaluateExpression - Given an expression that passes the
2786/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2787/// in the loop has the value PHIVal. If we can't fold this expression for some
2788/// reason, return null.
2789static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2790 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00002791 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00002792 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00002793 Instruction *I = cast<Instruction>(V);
2794
2795 std::vector<Constant*> Operands;
2796 Operands.resize(I->getNumOperands());
2797
2798 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2799 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2800 if (Operands[i] == 0) return 0;
2801 }
2802
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002803 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2804 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2805 &Operands[0], Operands.size());
2806 else
2807 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2808 &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00002809}
2810
2811/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2812/// in the header of its containing loop, we know the loop executes a
2813/// constant number of times, and the PHI node is just a recurrence
2814/// involving constants, fold it.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002815Constant *ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00002816getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00002817 std::map<PHINode*, Constant*>::iterator I =
2818 ConstantEvolutionLoopExitValue.find(PN);
2819 if (I != ConstantEvolutionLoopExitValue.end())
2820 return I->second;
2821
Dan Gohman46bdfb02009-02-24 18:55:53 +00002822 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00002823 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2824
2825 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2826
2827 // Since the loop is canonicalized, the PHI node must have two entries. One
2828 // entry must be a constant (coming in from outside of the loop), and the
2829 // second must be derived from the same PHI.
2830 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2831 Constant *StartCST =
2832 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2833 if (StartCST == 0)
2834 return RetVal = 0; // Must be a constant.
2835
2836 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2837 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2838 if (PN2 != PN)
2839 return RetVal = 0; // Not derived from same PHI.
2840
2841 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00002842 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00002843 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00002844
Dan Gohman46bdfb02009-02-24 18:55:53 +00002845 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00002846 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00002847 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2848 if (IterationNum == NumIterations)
2849 return RetVal = PHIVal; // Got exit value!
2850
2851 // Compute the value of the PHI node for the next iteration.
2852 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2853 if (NextPHI == PHIVal)
2854 return RetVal = NextPHI; // Stopped evolving!
2855 if (NextPHI == 0)
2856 return 0; // Couldn't evaluate!
2857 PHIVal = NextPHI;
2858 }
2859}
2860
Dan Gohman46bdfb02009-02-24 18:55:53 +00002861/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00002862/// constant number of times (the condition evolves only from constants),
2863/// try to evaluate a few iterations of the loop until we get the exit
2864/// condition gets a value of ExitWhen (true or false). If we cannot
2865/// evaluate the trip count of the loop, return UnknownValue.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002866SCEVHandle ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00002867ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00002868 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2869 if (PN == 0) return UnknownValue;
2870
2871 // Since the loop is canonicalized, the PHI node must have two entries. One
2872 // entry must be a constant (coming in from outside of the loop), and the
2873 // second must be derived from the same PHI.
2874 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2875 Constant *StartCST =
2876 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2877 if (StartCST == 0) return UnknownValue; // Must be a constant.
2878
2879 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2880 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2881 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2882
2883 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2884 // the loop symbolically to determine when the condition gets a value of
2885 // "ExitWhen".
2886 unsigned IterationNum = 0;
2887 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2888 for (Constant *PHIVal = StartCST;
2889 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002890 ConstantInt *CondVal =
2891 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00002892
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002893 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00002894 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002895
Reid Spencere8019bb2007-03-01 07:25:48 +00002896 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002897 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00002898 ++NumBruteForceTripCountsComputed;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002899 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00002900 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002901
Chris Lattner3221ad02004-04-17 22:58:41 +00002902 // Compute the value of the PHI node for the next iteration.
2903 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2904 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00002905 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00002906 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00002907 }
2908
2909 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00002910 return UnknownValue;
2911}
2912
Dan Gohman66a7e852009-05-08 20:38:54 +00002913/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2914/// at the specified scope in the program. The L value specifies a loop
2915/// nest to evaluate the expression at, where null is the top-level or a
2916/// specified loop is immediately inside of the loop.
2917///
2918/// This method can be used to compute the exit value for a variable defined
2919/// in a loop by querying what the value will hold in the parent loop.
2920///
Dan Gohmand594e6f2009-05-24 23:25:42 +00002921/// In the case that a relevant loop exit value cannot be computed, the
2922/// original value V is returned.
Dan Gohman35738ac2009-05-04 22:30:44 +00002923SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002924 // FIXME: this should be turned into a virtual method on SCEV!
2925
Chris Lattner3221ad02004-04-17 22:58:41 +00002926 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002927
Nick Lewycky3e630762008-02-20 06:48:22 +00002928 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00002929 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00002930 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002931 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002932 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00002933 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2934 if (PHINode *PN = dyn_cast<PHINode>(I))
2935 if (PN->getParent() == LI->getHeader()) {
2936 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00002937 // to see if the loop that contains it has a known backedge-taken
2938 // count. If so, we may be able to force computation of the exit
2939 // value.
2940 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00002941 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00002942 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002943 // Okay, we know how many times the containing loop executes. If
2944 // this is a constant evolving PHI node, get the final value at
2945 // the specified iteration number.
2946 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00002947 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00002948 LI);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002949 if (RV) return getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00002950 }
2951 }
2952
Reid Spencer09906f32006-12-04 21:33:23 +00002953 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00002954 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00002955 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00002956 // result. This is particularly useful for computing loop exit values.
2957 if (CanConstantFold(I)) {
Dan Gohman6bce6432009-05-08 20:47:27 +00002958 // Check to see if we've folded this instruction at this loop before.
2959 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
2960 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
2961 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
2962 if (!Pair.second)
2963 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
2964
Chris Lattner3221ad02004-04-17 22:58:41 +00002965 std::vector<Constant*> Operands;
2966 Operands.reserve(I->getNumOperands());
2967 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2968 Value *Op = I->getOperand(i);
2969 if (Constant *C = dyn_cast<Constant>(Op)) {
2970 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002971 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00002972 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00002973 // non-integer and non-pointer, don't even try to analyze them
2974 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00002975 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00002976 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00002977
Chris Lattner3221ad02004-04-17 22:58:41 +00002978 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohman622ed672009-05-04 22:02:23 +00002979 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00002980 Constant *C = SC->getValue();
2981 if (C->getType() != Op->getType())
2982 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2983 Op->getType(),
2984 false),
2985 C, Op->getType());
2986 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00002987 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00002988 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
2989 if (C->getType() != Op->getType())
2990 C =
2991 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2992 Op->getType(),
2993 false),
2994 C, Op->getType());
2995 Operands.push_back(C);
2996 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00002997 return V;
2998 } else {
2999 return V;
3000 }
3001 }
3002 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003003
3004 Constant *C;
3005 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3006 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3007 &Operands[0], Operands.size());
3008 else
3009 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3010 &Operands[0], Operands.size());
Dan Gohman6bce6432009-05-08 20:47:27 +00003011 Pair.first->second = C;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003012 return getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003013 }
3014 }
3015
3016 // This is some other type of SCEVUnknown, just return it.
3017 return V;
3018 }
3019
Dan Gohman622ed672009-05-04 22:02:23 +00003020 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003021 // Avoid performing the look-up in the common case where the specified
3022 // expression has no loop-variant portions.
3023 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
3024 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3025 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003026 // Okay, at least one of these operands is loop variant but might be
3027 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00003028 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00003029 NewOps.push_back(OpAtScope);
3030
3031 for (++i; i != e; ++i) {
3032 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003033 NewOps.push_back(OpAtScope);
3034 }
3035 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003036 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003037 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003038 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003039 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003040 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00003041 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003042 return getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003043 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003044 }
3045 }
3046 // If we got here, all operands are loop invariant.
3047 return Comm;
3048 }
3049
Dan Gohman622ed672009-05-04 22:02:23 +00003050 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Nick Lewycky789558d2009-01-13 09:18:58 +00003051 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00003052 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00003053 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3054 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003055 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00003056 }
3057
3058 // If this is a loop recurrence for a loop that does not contain L, then we
3059 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00003060 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003061 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3062 // To evaluate this recurrence, we need to know how many times the AddRec
3063 // loop iterates. Compute this now.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003064 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00003065 if (BackedgeTakenCount == UnknownValue) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003066
Eli Friedmanb42a6262008-08-04 23:49:06 +00003067 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003068 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003069 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00003070 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00003071 }
3072
Dan Gohman622ed672009-05-04 22:02:23 +00003073 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003074 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003075 if (Op == Cast->getOperand())
3076 return Cast; // must be loop invariant
3077 return getZeroExtendExpr(Op, Cast->getType());
3078 }
3079
Dan Gohman622ed672009-05-04 22:02:23 +00003080 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003081 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003082 if (Op == Cast->getOperand())
3083 return Cast; // must be loop invariant
3084 return getSignExtendExpr(Op, Cast->getType());
3085 }
3086
Dan Gohman622ed672009-05-04 22:02:23 +00003087 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003088 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003089 if (Op == Cast->getOperand())
3090 return Cast; // must be loop invariant
3091 return getTruncateExpr(Op, Cast->getType());
3092 }
3093
3094 assert(0 && "Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00003095 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00003096}
3097
Dan Gohman66a7e852009-05-08 20:38:54 +00003098/// getSCEVAtScope - This is a convenience function which does
3099/// getSCEVAtScope(getSCEV(V), L).
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003100SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
3101 return getSCEVAtScope(getSCEV(V), L);
3102}
3103
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003104/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3105/// following equation:
3106///
3107/// A * X = B (mod N)
3108///
3109/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3110/// A and B isn't important.
3111///
3112/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
3113static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
3114 ScalarEvolution &SE) {
3115 uint32_t BW = A.getBitWidth();
3116 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3117 assert(A != 0 && "A must be non-zero.");
3118
3119 // 1. D = gcd(A, N)
3120 //
3121 // The gcd of A and N may have only one prime factor: 2. The number of
3122 // trailing zeros in A is its multiplicity
3123 uint32_t Mult2 = A.countTrailingZeros();
3124 // D = 2^Mult2
3125
3126 // 2. Check if B is divisible by D.
3127 //
3128 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3129 // is not less than multiplicity of this prime factor for D.
3130 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003131 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003132
3133 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3134 // modulo (N / D).
3135 //
3136 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3137 // bit width during computations.
3138 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3139 APInt Mod(BW + 1, 0);
3140 Mod.set(BW - Mult2); // Mod = N / D
3141 APInt I = AD.multiplicativeInverse(Mod);
3142
3143 // 4. Compute the minimum unsigned root of the equation:
3144 // I * (B / D) mod (N / D)
3145 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3146
3147 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3148 // bits.
3149 return SE.getConstant(Result.trunc(BW));
3150}
Chris Lattner53e677a2004-04-02 20:23:17 +00003151
3152/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3153/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3154/// might be the same) or two SCEVCouldNotCompute objects.
3155///
3156static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman246b2562007-10-22 18:31:58 +00003157SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003158 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00003159 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3160 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3161 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003162
Chris Lattner53e677a2004-04-02 20:23:17 +00003163 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00003164 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00003165 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003166 return std::make_pair(CNC, CNC);
3167 }
3168
Reid Spencere8019bb2007-03-01 07:25:48 +00003169 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00003170 const APInt &L = LC->getValue()->getValue();
3171 const APInt &M = MC->getValue()->getValue();
3172 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00003173 APInt Two(BitWidth, 2);
3174 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003175
Reid Spencere8019bb2007-03-01 07:25:48 +00003176 {
3177 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00003178 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00003179 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3180 // The B coefficient is M-N/2
3181 APInt B(M);
3182 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003183
Reid Spencere8019bb2007-03-01 07:25:48 +00003184 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00003185 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00003186
Reid Spencere8019bb2007-03-01 07:25:48 +00003187 // Compute the B^2-4ac term.
3188 APInt SqrtTerm(B);
3189 SqrtTerm *= B;
3190 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00003191
Reid Spencere8019bb2007-03-01 07:25:48 +00003192 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3193 // integer value or else APInt::sqrt() will assert.
3194 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003195
Reid Spencere8019bb2007-03-01 07:25:48 +00003196 // Compute the two solutions for the quadratic formula.
3197 // The divisions must be performed as signed divisions.
3198 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00003199 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00003200 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00003201 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00003202 return std::make_pair(CNC, CNC);
3203 }
3204
Reid Spencere8019bb2007-03-01 07:25:48 +00003205 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3206 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003207
Dan Gohman246b2562007-10-22 18:31:58 +00003208 return std::make_pair(SE.getConstant(Solution1),
3209 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00003210 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00003211}
3212
3213/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman6c0866c2009-05-24 23:45:28 +00003214/// value to zero will execute. If not computable, return UnknownValue.
Dan Gohman35738ac2009-05-04 22:30:44 +00003215SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003216 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00003217 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003218 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00003219 if (C->getValue()->isZero()) return C;
Chris Lattner53e677a2004-04-02 20:23:17 +00003220 return UnknownValue; // Otherwise it will loop infinitely.
3221 }
3222
Dan Gohman35738ac2009-05-04 22:30:44 +00003223 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003224 if (!AddRec || AddRec->getLoop() != L)
3225 return UnknownValue;
3226
3227 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003228 // If this is an affine expression, the execution count of this branch is
3229 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00003230 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003231 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00003232 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003233 // equivalent to:
3234 //
3235 // Step*N = -Start (mod 2^BW)
3236 //
3237 // where BW is the common bit width of Start and Step.
3238
Chris Lattner53e677a2004-04-02 20:23:17 +00003239 // Get the initial value for the loop.
3240 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003241 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003242
Dan Gohman622ed672009-05-04 22:02:23 +00003243 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003244 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00003245
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003246 // First, handle unitary steps.
3247 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003248 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003249 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3250 return Start; // N = Start (as unsigned)
3251
3252 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00003253 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003254 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003255 -StartC->getValue()->getValue(),
3256 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003257 }
Chris Lattner42a75512007-01-15 02:27:26 +00003258 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003259 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3260 // the quadratic equation to solve it.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003261 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
3262 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00003263 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3264 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00003265 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003266#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003267 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3268 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003269#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00003270 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003271 if (ConstantInt *CB =
3272 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003273 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00003274 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00003275 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003276
Chris Lattner53e677a2004-04-02 20:23:17 +00003277 // We can only use this value if the chrec ends up with an exact zero
3278 // value at this index. When solving for "X*X != 5", for example, we
3279 // should not accept a root of 2.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003280 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00003281 if (Val->isZero())
3282 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00003283 }
3284 }
3285 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003286
Chris Lattner53e677a2004-04-02 20:23:17 +00003287 return UnknownValue;
3288}
3289
3290/// HowFarToNonZero - Return the number of times a backedge checking the
3291/// specified value for nonzero will execute. If not computable, return
3292/// UnknownValue
Dan Gohman35738ac2009-05-04 22:30:44 +00003293SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003294 // Loops that look like: while (X == 0) are very strange indeed. We don't
3295 // handle them yet except for the trivial case. This could be expanded in the
3296 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003297
Chris Lattner53e677a2004-04-02 20:23:17 +00003298 // If the value is a constant, check to see if it is known to be non-zero
3299 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00003300 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00003301 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003302 return getIntegerSCEV(0, C->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00003303 return UnknownValue; // Otherwise it will loop infinitely.
3304 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003305
Chris Lattner53e677a2004-04-02 20:23:17 +00003306 // We could implement others, but I really doubt anyone writes loops like
3307 // this, and if they did, they would already be constant folded.
3308 return UnknownValue;
3309}
3310
Dan Gohman859b4822009-05-18 15:36:09 +00003311/// getLoopPredecessor - If the given loop's header has exactly one unique
3312/// predecessor outside the loop, return it. Otherwise return null.
3313///
3314BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3315 BasicBlock *Header = L->getHeader();
3316 BasicBlock *Pred = 0;
3317 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3318 PI != E; ++PI)
3319 if (!L->contains(*PI)) {
3320 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3321 Pred = *PI;
3322 }
3323 return Pred;
3324}
3325
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003326/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3327/// (which may not be an immediate predecessor) which has exactly one
3328/// successor from which BB is reachable, or null if no such block is
3329/// found.
3330///
3331BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003332ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00003333 // If the block has a unique predecessor, then there is no path from the
3334 // predecessor to the block that does not go through the direct edge
3335 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003336 if (BasicBlock *Pred = BB->getSinglePredecessor())
3337 return Pred;
3338
3339 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00003340 // If the header has a unique predecessor outside the loop, it must be
3341 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003342 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00003343 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003344
3345 return 0;
3346}
3347
Dan Gohmanc2390b12009-02-12 22:19:27 +00003348/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman3d739fe2009-04-30 20:48:53 +00003349/// a conditional between LHS and RHS. This is used to help avoid max
3350/// expressions in loop trip counts.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003351bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman3d739fe2009-04-30 20:48:53 +00003352 ICmpInst::Predicate Pred,
Dan Gohman35738ac2009-05-04 22:30:44 +00003353 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00003354 // Interpret a null as meaning no loop, where there is obviously no guard
3355 // (interprocedural conditions notwithstanding).
3356 if (!L) return false;
3357
Dan Gohman859b4822009-05-18 15:36:09 +00003358 BasicBlock *Predecessor = getLoopPredecessor(L);
3359 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00003360
Dan Gohman859b4822009-05-18 15:36:09 +00003361 // Starting at the loop predecessor, climb up the predecessor chain, as long
3362 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003363 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00003364 for (; Predecessor;
3365 PredecessorDest = Predecessor,
3366 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00003367
3368 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00003369 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00003370 if (!LoopEntryPredicate ||
3371 LoopEntryPredicate->isUnconditional())
3372 continue;
3373
3374 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3375 if (!ICI) continue;
3376
3377 // Now that we found a conditional branch that dominates the loop, check to
3378 // see if it is the comparison we are looking for.
3379 Value *PreCondLHS = ICI->getOperand(0);
3380 Value *PreCondRHS = ICI->getOperand(1);
3381 ICmpInst::Predicate Cond;
Dan Gohman859b4822009-05-18 15:36:09 +00003382 if (LoopEntryPredicate->getSuccessor(0) == PredecessorDest)
Dan Gohman38372182008-08-12 20:17:31 +00003383 Cond = ICI->getPredicate();
3384 else
3385 Cond = ICI->getInversePredicate();
3386
Dan Gohmanc2390b12009-02-12 22:19:27 +00003387 if (Cond == Pred)
3388 ; // An exact match.
3389 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3390 ; // The actual condition is beyond sufficient.
3391 else
3392 // Check a few special cases.
3393 switch (Cond) {
3394 case ICmpInst::ICMP_UGT:
3395 if (Pred == ICmpInst::ICMP_ULT) {
3396 std::swap(PreCondLHS, PreCondRHS);
3397 Cond = ICmpInst::ICMP_ULT;
3398 break;
3399 }
3400 continue;
3401 case ICmpInst::ICMP_SGT:
3402 if (Pred == ICmpInst::ICMP_SLT) {
3403 std::swap(PreCondLHS, PreCondRHS);
3404 Cond = ICmpInst::ICMP_SLT;
3405 break;
3406 }
3407 continue;
3408 case ICmpInst::ICMP_NE:
3409 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3410 // so check for this case by checking if the NE is comparing against
3411 // a minimum or maximum constant.
3412 if (!ICmpInst::isTrueWhenEqual(Pred))
3413 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3414 const APInt &A = CI->getValue();
3415 switch (Pred) {
3416 case ICmpInst::ICMP_SLT:
3417 if (A.isMaxSignedValue()) break;
3418 continue;
3419 case ICmpInst::ICMP_SGT:
3420 if (A.isMinSignedValue()) break;
3421 continue;
3422 case ICmpInst::ICMP_ULT:
3423 if (A.isMaxValue()) break;
3424 continue;
3425 case ICmpInst::ICMP_UGT:
3426 if (A.isMinValue()) break;
3427 continue;
3428 default:
3429 continue;
3430 }
3431 Cond = ICmpInst::ICMP_NE;
3432 // NE is symmetric but the original comparison may not be. Swap
3433 // the operands if necessary so that they match below.
3434 if (isa<SCEVConstant>(LHS))
3435 std::swap(PreCondLHS, PreCondRHS);
3436 break;
3437 }
3438 continue;
3439 default:
3440 // We weren't able to reconcile the condition.
3441 continue;
3442 }
Dan Gohman38372182008-08-12 20:17:31 +00003443
3444 if (!PreCondLHS->getType()->isInteger()) continue;
3445
3446 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3447 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3448 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003449 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3450 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohman38372182008-08-12 20:17:31 +00003451 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00003452 }
3453
Dan Gohman38372182008-08-12 20:17:31 +00003454 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00003455}
3456
Chris Lattnerdb25de42005-08-15 23:33:51 +00003457/// HowManyLessThans - Return the number of times a backedge containing the
3458/// specified less-than comparison will execute. If not computable, return
3459/// UnknownValue.
Dan Gohmana1af7572009-04-30 20:47:05 +00003460ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Dan Gohman35738ac2009-05-04 22:30:44 +00003461HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3462 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00003463 // Only handle: "ADDREC < LoopInvariant".
3464 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3465
Dan Gohman35738ac2009-05-04 22:30:44 +00003466 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00003467 if (!AddRec || AddRec->getLoop() != L)
3468 return UnknownValue;
3469
3470 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00003471 // FORNOW: We only support unit strides.
Dan Gohmana1af7572009-04-30 20:47:05 +00003472 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3473 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3474 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3475
3476 // TODO: handle non-constant strides.
3477 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3478 if (!CStep || CStep->isZero())
3479 return UnknownValue;
Dan Gohman70a1fe72009-05-18 15:22:39 +00003480 if (CStep->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003481 // With unit stride, the iteration never steps past the limit value.
3482 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3483 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3484 // Test whether a positive iteration iteration can step past the limit
3485 // value and past the maximum value for its type in a single step.
3486 if (isSigned) {
3487 APInt Max = APInt::getSignedMaxValue(BitWidth);
3488 if ((Max - CStep->getValue()->getValue())
3489 .slt(CLimit->getValue()->getValue()))
3490 return UnknownValue;
3491 } else {
3492 APInt Max = APInt::getMaxValue(BitWidth);
3493 if ((Max - CStep->getValue()->getValue())
3494 .ult(CLimit->getValue()->getValue()))
3495 return UnknownValue;
3496 }
3497 } else
3498 // TODO: handle non-constant limit values below.
3499 return UnknownValue;
3500 } else
3501 // TODO: handle negative strides below.
Chris Lattnerdb25de42005-08-15 23:33:51 +00003502 return UnknownValue;
3503
Dan Gohmana1af7572009-04-30 20:47:05 +00003504 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3505 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3506 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00003507 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00003508
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00003509 // First, we get the value of the LHS in the first iteration: n
3510 SCEVHandle Start = AddRec->getOperand(0);
3511
Dan Gohmana1af7572009-04-30 20:47:05 +00003512 // Determine the minimum constant start value.
3513 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3514 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3515 APInt::getMinValue(BitWidth));
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00003516
Dan Gohmana1af7572009-04-30 20:47:05 +00003517 // If we know that the condition is true in order to enter the loop,
3518 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00003519 // only know that it will execute (max(m,n)-n)/s times. In both cases,
3520 // the division must round up.
Dan Gohmana1af7572009-04-30 20:47:05 +00003521 SCEVHandle End = RHS;
3522 if (!isLoopGuardedByCond(L,
3523 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3524 getMinusSCEV(Start, Step), RHS))
3525 End = isSigned ? getSMaxExpr(RHS, Start)
3526 : getUMaxExpr(RHS, Start);
3527
3528 // Determine the maximum constant end value.
3529 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3530 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3531 APInt::getMaxValue(BitWidth));
3532
3533 // Finally, we subtract these two values and divide, rounding up, to get
3534 // the number of times the backedge is executed.
3535 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3536 getAddExpr(Step, NegOne)),
3537 Step);
3538
3539 // The maximum backedge count is similar, except using the minimum start
3540 // value and the maximum end value.
3541 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3542 MinStart),
3543 getAddExpr(Step, NegOne)),
3544 Step);
3545
3546 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00003547 }
3548
3549 return UnknownValue;
3550}
3551
Chris Lattner53e677a2004-04-02 20:23:17 +00003552/// getNumIterationsInRange - Return the number of iterations of this loop that
3553/// produce values in the specified constant range. Another way of looking at
3554/// this is that it returns the first iteration number where the value is not in
3555/// the condition, thus computing the exit count. If the iteration count can't
3556/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman246b2562007-10-22 18:31:58 +00003557SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3558 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00003559 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003560 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003561
3562 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00003563 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00003564 if (!SC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003565 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00003566 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3567 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00003568 if (const SCEVAddRecExpr *ShiftedAddRec =
3569 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00003570 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00003571 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00003572 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003573 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003574 }
3575
3576 // The only time we can solve this is when we have all constant indices.
3577 // Otherwise, we cannot determine the overflow conditions.
3578 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3579 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003580 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003581
3582
3583 // Okay at this point we know that all elements of the chrec are constants and
3584 // that the start element is zero.
3585
3586 // First check to see if the range contains zero. If not, the first
3587 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003588 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00003589 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman246b2562007-10-22 18:31:58 +00003590 return SE.getConstant(ConstantInt::get(getType(),0));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003591
Chris Lattner53e677a2004-04-02 20:23:17 +00003592 if (isAffine()) {
3593 // If this is an affine expression then we have this situation:
3594 // Solve {0,+,A} in Range === Ax in Range
3595
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003596 // We know that zero is in the range. If A is positive then we know that
3597 // the upper value of the range must be the first possible exit value.
3598 // If A is negative then the lower of the range is the last possible loop
3599 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00003600 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003601 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3602 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00003603
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003604 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00003605 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00003606 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00003607
3608 // Evaluate at the exit value. If we really did fall out of the valid
3609 // range, then we computed our trip count, otherwise wrap around or other
3610 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00003611 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003612 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003613 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003614
3615 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00003616 assert(Range.contains(
3617 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003618 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00003619 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00003620 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00003621 } else if (isQuadratic()) {
3622 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3623 // quadratic equation to solve it. To do this, we must frame our problem in
3624 // terms of figuring out when zero is crossed, instead of when
3625 // Range.getUpper() is crossed.
3626 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00003627 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3628 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003629
3630 // Next, solve the constructed addrec
3631 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00003632 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00003633 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3634 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00003635 if (R1) {
3636 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003637 if (ConstantInt *CB =
3638 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003639 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00003640 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00003641 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003642
Chris Lattner53e677a2004-04-02 20:23:17 +00003643 // Make sure the root is not off by one. The returned iteration should
3644 // not be in the range, but the previous one should be. When solving
3645 // for "X*X < 5", for example, we should not return a root of 2.
3646 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003647 R1->getValue(),
3648 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003649 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003650 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00003651 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003652
Dan Gohman246b2562007-10-22 18:31:58 +00003653 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003654 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00003655 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003656 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003657 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003658
Chris Lattner53e677a2004-04-02 20:23:17 +00003659 // If R1 was not in the range, then it is a good return value. Make
3660 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00003661 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00003662 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003663 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00003664 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003665 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003666 }
3667 }
3668 }
3669
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003670 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003671}
3672
3673
3674
3675//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00003676// SCEVCallbackVH Class Implementation
3677//===----------------------------------------------------------------------===//
3678
Dan Gohman1959b752009-05-19 19:22:47 +00003679void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohman35738ac2009-05-04 22:30:44 +00003680 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3681 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3682 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00003683 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
3684 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00003685 SE->Scalars.erase(getValPtr());
3686 // this now dangles!
3687}
3688
Dan Gohman1959b752009-05-19 19:22:47 +00003689void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohman35738ac2009-05-04 22:30:44 +00003690 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3691
3692 // Forget all the expressions associated with users of the old value,
3693 // so that future queries will recompute the expressions using the new
3694 // value.
3695 SmallVector<User *, 16> Worklist;
3696 Value *Old = getValPtr();
3697 bool DeleteOld = false;
3698 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3699 UI != UE; ++UI)
3700 Worklist.push_back(*UI);
3701 while (!Worklist.empty()) {
3702 User *U = Worklist.pop_back_val();
3703 // Deleting the Old value will cause this to dangle. Postpone
3704 // that until everything else is done.
3705 if (U == Old) {
3706 DeleteOld = true;
3707 continue;
3708 }
3709 if (PHINode *PN = dyn_cast<PHINode>(U))
3710 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00003711 if (Instruction *I = dyn_cast<Instruction>(U))
3712 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00003713 if (SE->Scalars.erase(U))
3714 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3715 UI != UE; ++UI)
3716 Worklist.push_back(*UI);
3717 }
3718 if (DeleteOld) {
3719 if (PHINode *PN = dyn_cast<PHINode>(Old))
3720 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00003721 if (Instruction *I = dyn_cast<Instruction>(Old))
3722 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00003723 SE->Scalars.erase(Old);
3724 // this now dangles!
3725 }
3726 // this may dangle!
3727}
3728
Dan Gohman1959b752009-05-19 19:22:47 +00003729ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00003730 : CallbackVH(V), SE(se) {}
3731
3732//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00003733// ScalarEvolution Class Implementation
3734//===----------------------------------------------------------------------===//
3735
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003736ScalarEvolution::ScalarEvolution()
3737 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3738}
3739
Chris Lattner53e677a2004-04-02 20:23:17 +00003740bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003741 this->F = &F;
3742 LI = &getAnalysis<LoopInfo>();
3743 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00003744 return false;
3745}
3746
3747void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003748 Scalars.clear();
3749 BackedgeTakenCounts.clear();
3750 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00003751 ValuesAtScopes.clear();
Chris Lattner53e677a2004-04-02 20:23:17 +00003752}
3753
3754void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3755 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00003756 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +00003757}
3758
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003759bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00003760 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00003761}
3762
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003763static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00003764 const Loop *L) {
3765 // Print all inner loops first
3766 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3767 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003768
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003769 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003770
Devang Patelb7211a22007-08-21 00:31:24 +00003771 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003772 L->getExitBlocks(ExitBlocks);
3773 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003774 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003775
Dan Gohman46bdfb02009-02-24 18:55:53 +00003776 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3777 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003778 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00003779 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003780 }
3781
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003782 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00003783}
3784
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003785void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003786 // ScalarEvolution's implementaiton of the print method is to print
3787 // out SCEV values of all instructions that are interesting. Doing
3788 // this potentially causes it to create new SCEV objects though,
3789 // which technically conflicts with the const qualifier. This isn't
3790 // observable from outside the class though (the hasSCEV function
3791 // notwithstanding), so casting away the const isn't dangerous.
3792 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003793
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003794 OS << "Classifying expressions for: " << F->getName() << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00003795 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00003796 if (isSCEVable(I->getType())) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00003797 OS << *I;
Dan Gohman8dae1382008-09-14 17:21:12 +00003798 OS << " --> ";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003799 SCEVHandle SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00003800 SV->print(OS);
3801 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003802
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003803 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003804 OS << "Exits: ";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003805 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00003806 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003807 OS << "<<Unknown>>";
3808 } else {
3809 OS << *ExitValue;
3810 }
3811 }
3812
Chris Lattner53e677a2004-04-02 20:23:17 +00003813 OS << "\n";
3814 }
3815
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003816 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3817 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3818 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00003819}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003820
3821void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3822 raw_os_ostream OS(o);
3823 print(OS, M);
3824}