blob: 54f27653542155bdd76d80bde124357c286fe040 [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"
72#include "llvm/Transforms/Scalar.h"
73#include "llvm/Support/CFG.h"
Chris Lattner95255282006-06-28 23:17:24 +000074#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000075#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000076#include "llvm/Support/ConstantRange.h"
77#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"
Bill Wendling6f81b512006-11-28 22:46:12 +000080#include "llvm/Support/Streams.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000081#include "llvm/ADT/Statistic.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000082#include <ostream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000083#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000084#include <cmath>
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 {
Bill Wendlinge8156192006-12-07 01:30:32 +0000115 print(cerr);
Nick Lewyckyd1f5fab2009-01-16 17:07:22 +0000116 cerr << '\n';
Chris Lattner53e677a2004-04-02 20:23:17 +0000117}
118
Reid Spencer581b0d42007-02-28 19:57:34 +0000119uint32_t SCEV::getBitWidth() const {
120 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
121 return ITy->getBitWidth();
122 return 0;
123}
124
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000125bool SCEV::isZero() const {
126 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
127 return SC->getValue()->isZero();
128 return false;
129}
130
Chris Lattner53e677a2004-04-02 20:23:17 +0000131
132SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
133
134bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
135 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000136 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000137}
138
139const Type *SCEVCouldNotCompute::getType() const {
140 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000141 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000142}
143
144bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
145 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
146 return false;
147}
148
Chris Lattner4dc534c2005-02-13 04:37:18 +0000149SCEVHandle SCEVCouldNotCompute::
150replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000151 const SCEVHandle &Conc,
152 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000153 return this;
154}
155
Chris Lattner53e677a2004-04-02 20:23:17 +0000156void SCEVCouldNotCompute::print(std::ostream &OS) const {
157 OS << "***COULDNOTCOMPUTE***";
158}
159
160bool SCEVCouldNotCompute::classof(const SCEV *S) {
161 return S->getSCEVType() == scCouldNotCompute;
162}
163
164
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000165// SCEVConstants - Only allow the creation of one SCEVConstant for any
166// particular value. Don't use a SCEVHandle here, or else the object will
167// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000168static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000169
Chris Lattner53e677a2004-04-02 20:23:17 +0000170
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000171SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000172 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000173}
Chris Lattner53e677a2004-04-02 20:23:17 +0000174
Dan Gohman246b2562007-10-22 18:31:58 +0000175SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Chris Lattnerb3364092006-10-04 21:49:37 +0000176 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000177 if (R == 0) R = new SCEVConstant(V);
178 return R;
179}
Chris Lattner53e677a2004-04-02 20:23:17 +0000180
Dan Gohman246b2562007-10-22 18:31:58 +0000181SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
182 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000183}
184
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000185const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000186
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000187void SCEVConstant::print(std::ostream &OS) const {
188 WriteAsOperand(OS, V, false);
189}
Chris Lattner53e677a2004-04-02 20:23:17 +0000190
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000191// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
192// particular input. Don't use a SCEVHandle here, or else the object will
193// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000194static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
195 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000196
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000197SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
198 : SCEV(scTruncate), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000199 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000200 "Cannot truncate non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000201 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
202 && "This is not a truncating conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000203}
Chris Lattner53e677a2004-04-02 20:23:17 +0000204
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000205SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000206 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000207}
Chris Lattner53e677a2004-04-02 20:23:17 +0000208
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000209bool SCEVTruncateExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
210 return Op->dominates(BB, DT);
211}
212
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000213void SCEVTruncateExpr::print(std::ostream &OS) const {
214 OS << "(truncate " << *Op << " to " << *Ty << ")";
215}
216
217// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
218// particular input. Don't use a SCEVHandle here, or else the object will never
219// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000220static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
221 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000222
223SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000224 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000225 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000226 "Cannot zero extend non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000227 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
228 && "This is not an extending conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000229}
230
231SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000232 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000233}
234
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000235bool SCEVZeroExtendExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
236 return Op->dominates(BB, DT);
237}
238
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000239void SCEVZeroExtendExpr::print(std::ostream &OS) const {
240 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
241}
242
Dan Gohmand19534a2007-06-15 14:38:12 +0000243// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
244// particular input. Don't use a SCEVHandle here, or else the object will never
245// be deleted!
246static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
247 SCEVSignExtendExpr*> > SCEVSignExtends;
248
249SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
250 : SCEV(scSignExtend), Op(op), Ty(ty) {
251 assert(Op->getType()->isInteger() && Ty->isInteger() &&
252 "Cannot sign extend non-integer value!");
253 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
254 && "This is not an extending conversion!");
255}
256
257SCEVSignExtendExpr::~SCEVSignExtendExpr() {
258 SCEVSignExtends->erase(std::make_pair(Op, Ty));
259}
260
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000261bool SCEVSignExtendExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
262 return Op->dominates(BB, DT);
263}
264
Dan Gohmand19534a2007-06-15 14:38:12 +0000265void SCEVSignExtendExpr::print(std::ostream &OS) const {
266 OS << "(signextend " << *Op << " to " << *Ty << ")";
267}
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!
Chris Lattnerb3364092006-10-04 21:49:37 +0000272static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
273 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000274
275SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000276 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
277 std::vector<SCEV*>(Operands.begin(),
278 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000279}
280
281void SCEVCommutativeExpr::print(std::ostream &OS) const {
282 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
283 const char *OpStr = getOperationStr();
284 OS << "(" << *Operands[0];
285 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
286 OS << OpStr << *Operands[i];
287 OS << ")";
288}
289
Chris Lattner4dc534c2005-02-13 04:37:18 +0000290SCEVHandle SCEVCommutativeExpr::
291replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000292 const SCEVHandle &Conc,
293 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000294 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000295 SCEVHandle H =
296 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000297 if (H != getOperand(i)) {
298 std::vector<SCEVHandle> NewOps;
299 NewOps.reserve(getNumOperands());
300 for (unsigned j = 0; j != i; ++j)
301 NewOps.push_back(getOperand(j));
302 NewOps.push_back(H);
303 for (++i; i != e; ++i)
304 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000305 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000306
307 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000308 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000309 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000310 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000311 else if (isa<SCEVSMaxExpr>(this))
312 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000313 else if (isa<SCEVUMaxExpr>(this))
314 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000315 else
316 assert(0 && "Unknown commutative expr!");
317 }
318 }
319 return this;
320}
321
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000322bool SCEVCommutativeExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
323 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
324 if (!getOperand(i)->dominates(BB, DT))
325 return false;
326 }
327 return true;
328}
329
Chris Lattner4dc534c2005-02-13 04:37:18 +0000330
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000331// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000332// input. Don't use a SCEVHandle here, or else the object will never be
333// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000334static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000335 SCEVUDivExpr*> > SCEVUDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000336
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000337SCEVUDivExpr::~SCEVUDivExpr() {
338 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000339}
340
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000341bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
342 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
343}
344
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000345void SCEVUDivExpr::print(std::ostream &OS) const {
346 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000347}
348
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000349const Type *SCEVUDivExpr::getType() const {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000350 return LHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000351}
352
353// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
354// particular input. Don't use a SCEVHandle here, or else the object will never
355// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000356static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
357 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000358
359SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000360 SCEVAddRecExprs->erase(std::make_pair(L,
361 std::vector<SCEV*>(Operands.begin(),
362 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000363}
364
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000365bool SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
366 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
367 if (!getOperand(i)->dominates(BB, DT))
368 return false;
369 }
370 return true;
371}
372
373
Chris Lattner4dc534c2005-02-13 04:37:18 +0000374SCEVHandle SCEVAddRecExpr::
375replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000376 const SCEVHandle &Conc,
377 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000378 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000379 SCEVHandle H =
380 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000381 if (H != getOperand(i)) {
382 std::vector<SCEVHandle> NewOps;
383 NewOps.reserve(getNumOperands());
384 for (unsigned j = 0; j != i; ++j)
385 NewOps.push_back(getOperand(j));
386 NewOps.push_back(H);
387 for (++i; i != e; ++i)
388 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000389 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000390
Dan Gohman246b2562007-10-22 18:31:58 +0000391 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000392 }
393 }
394 return this;
395}
396
397
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000398bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
399 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000400 // contain L and if the start is invariant.
401 return !QueryLoop->contains(L->getHeader()) &&
402 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000403}
404
405
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000406void SCEVAddRecExpr::print(std::ostream &OS) const {
407 OS << "{" << *Operands[0];
408 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
409 OS << ",+," << *Operands[i];
410 OS << "}<" << L->getHeader()->getName() + ">";
411}
Chris Lattner53e677a2004-04-02 20:23:17 +0000412
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000413// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
414// value. Don't use a SCEVHandle here, or else the object will never be
415// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000416static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000417
Chris Lattnerb3364092006-10-04 21:49:37 +0000418SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000419
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000420bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
421 // All non-instruction values are loop invariant. All instructions are loop
422 // invariant if they are not contained in the specified loop.
423 if (Instruction *I = dyn_cast<Instruction>(V))
424 return !L->contains(I->getParent());
425 return true;
426}
Chris Lattner53e677a2004-04-02 20:23:17 +0000427
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000428bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
429 if (Instruction *I = dyn_cast<Instruction>(getValue()))
430 return DT->dominates(I->getParent(), BB);
431 return true;
432}
433
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000434const Type *SCEVUnknown::getType() const {
435 return V->getType();
436}
Chris Lattner53e677a2004-04-02 20:23:17 +0000437
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000438void SCEVUnknown::print(std::ostream &OS) const {
439 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000440}
441
Chris Lattner8d741b82004-06-20 06:23:15 +0000442//===----------------------------------------------------------------------===//
443// SCEV Utilities
444//===----------------------------------------------------------------------===//
445
446namespace {
447 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
448 /// than the complexity of the RHS. This comparator is used to canonicalize
449 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000450 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000451 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Chris Lattner8d741b82004-06-20 06:23:15 +0000452 return LHS->getSCEVType() < RHS->getSCEVType();
453 }
454 };
455}
456
457/// GroupByComplexity - Given a list of SCEV objects, order them by their
458/// complexity, and group objects of the same complexity together by value.
459/// When this routine is finished, we know that any duplicates in the vector are
460/// consecutive and that complexity is monotonically increasing.
461///
462/// Note that we go take special precautions to ensure that we get determinstic
463/// results from this routine. In other words, we don't want the results of
464/// this to depend on where the addresses of various SCEV objects happened to
465/// land in memory.
466///
467static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
468 if (Ops.size() < 2) return; // Noop
469 if (Ops.size() == 2) {
470 // This is the common case, which also happens to be trivially simple.
471 // Special case it.
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000472 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000473 std::swap(Ops[0], Ops[1]);
474 return;
475 }
476
477 // Do the rough sort by complexity.
478 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
479
480 // Now that we are sorted by complexity, group elements of the same
481 // complexity. Note that this is, at worst, N^2, but the vector is likely to
482 // be extremely short in practice. Note that we take this approach because we
483 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000484 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000485 SCEV *S = Ops[i];
486 unsigned Complexity = S->getSCEVType();
487
488 // If there are any objects of the same complexity and same value as this
489 // one, group them.
490 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
491 if (Ops[j] == S) { // Found a duplicate.
492 // Move it to immediately after i'th element.
493 std::swap(Ops[i+1], Ops[j]);
494 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000495 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000496 }
497 }
498 }
499}
500
Chris Lattner53e677a2004-04-02 20:23:17 +0000501
Chris Lattner53e677a2004-04-02 20:23:17 +0000502
503//===----------------------------------------------------------------------===//
504// Simple SCEV method implementations
505//===----------------------------------------------------------------------===//
506
507/// getIntegerSCEV - Given an integer or FP type, create a constant for the
508/// specified signed integer value and return a SCEV for the constant.
Dan Gohman246b2562007-10-22 18:31:58 +0000509SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000510 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000511 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000512 C = Constant::getNullValue(Ty);
513 else if (Ty->isFloatingPoint())
Chris Lattner02a260a2008-04-20 00:41:09 +0000514 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
515 APFloat::IEEEdouble, Val));
Reid Spencere4d87aa2006-12-23 06:05:41 +0000516 else
Reid Spencerb83eb642006-10-20 07:07:24 +0000517 C = ConstantInt::get(Ty, Val);
Dan Gohman246b2562007-10-22 18:31:58 +0000518 return getUnknown(C);
Chris Lattner53e677a2004-04-02 20:23:17 +0000519}
520
Chris Lattner53e677a2004-04-02 20:23:17 +0000521/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
522///
Dan Gohman246b2562007-10-22 18:31:58 +0000523SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000524 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman246b2562007-10-22 18:31:58 +0000525 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000526
Nick Lewycky178f20a2008-02-20 06:58:55 +0000527 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
Nick Lewycky3e630762008-02-20 06:48:22 +0000528}
529
530/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
531SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
532 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
533 return getUnknown(ConstantExpr::getNot(VC->getValue()));
534
Nick Lewycky178f20a2008-02-20 06:58:55 +0000535 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
Nick Lewycky3e630762008-02-20 06:48:22 +0000536 return getMinusSCEV(AllOnes, V);
Chris Lattner53e677a2004-04-02 20:23:17 +0000537}
538
539/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
540///
Dan Gohman246b2562007-10-22 18:31:58 +0000541SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
542 const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000543 // X - Y --> X + -Y
Dan Gohman246b2562007-10-22 18:31:58 +0000544 return getAddExpr(LHS, getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000545}
546
547
Eli Friedmanb42a6262008-08-04 23:49:06 +0000548/// BinomialCoefficient - Compute BC(It, K). The result has width W.
549// Assume, K > 0.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000550static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedmanb42a6262008-08-04 23:49:06 +0000551 ScalarEvolution &SE,
552 const IntegerType* ResultTy) {
553 // Handle the simplest case efficiently.
554 if (K == 1)
555 return SE.getTruncateOrZeroExtend(It, ResultTy);
556
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000557 // We are using the following formula for BC(It, K):
558 //
559 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
560 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000561 // Suppose, W is the bitwidth of the return value. We must be prepared for
562 // overflow. Hence, we must assure that the result of our computation is
563 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
564 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000565 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000566 // However, this code doesn't use exactly that formula; the formula it uses
567 // is something like the following, where T is the number of factors of 2 in
568 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
569 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000570 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000571 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000572 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000573 // This formula is trivially equivalent to the previous formula. However,
574 // this formula can be implemented much more efficiently. The trick is that
575 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
576 // arithmetic. To do exact division in modular arithmetic, all we have
577 // to do is multiply by the inverse. Therefore, this step can be done at
578 // width W.
579 //
580 // The next issue is how to safely do the division by 2^T. The way this
581 // is done is by doing the multiplication step at a width of at least W + T
582 // bits. This way, the bottom W+T bits of the product are accurate. Then,
583 // when we perform the division by 2^T (which is equivalent to a right shift
584 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
585 // truncated out after the division by 2^T.
586 //
587 // In comparison to just directly using the first formula, this technique
588 // is much more efficient; using the first formula requires W * K bits,
589 // but this formula less than W + K bits. Also, the first formula requires
590 // a division step, whereas this formula only requires multiplies and shifts.
591 //
592 // It doesn't matter whether the subtraction step is done in the calculation
593 // width or the input iteration count's width; if the subtraction overflows,
594 // the result must be zero anyway. We prefer here to do it in the width of
595 // the induction variable because it helps a lot for certain cases; CodeGen
596 // isn't smart enough to ignore the overflow, which leads to much less
597 // efficient code if the width of the subtraction is wider than the native
598 // register width.
599 //
600 // (It's possible to not widen at all by pulling out factors of 2 before
601 // the multiplication; for example, K=2 can be calculated as
602 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
603 // extra arithmetic, so it's not an obvious win, and it gets
604 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000605
Eli Friedmanb42a6262008-08-04 23:49:06 +0000606 // Protection from insane SCEVs; this bound is conservative,
607 // but it probably doesn't matter.
608 if (K > 1000)
609 return new SCEVCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000610
Eli Friedmanb42a6262008-08-04 23:49:06 +0000611 unsigned W = ResultTy->getBitWidth();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000612
Eli Friedmanb42a6262008-08-04 23:49:06 +0000613 // Calculate K! / 2^T and T; we divide out the factors of two before
614 // multiplying for calculating K! / 2^T to avoid overflow.
615 // Other overflow doesn't matter because we only care about the bottom
616 // W bits of the result.
617 APInt OddFactorial(W, 1);
618 unsigned T = 1;
619 for (unsigned i = 3; i <= K; ++i) {
620 APInt Mult(W, i);
621 unsigned TwoFactors = Mult.countTrailingZeros();
622 T += TwoFactors;
623 Mult = Mult.lshr(TwoFactors);
624 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000625 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000626
Eli Friedmanb42a6262008-08-04 23:49:06 +0000627 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000628 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000629
630 // Calcuate 2^T, at width T+W.
631 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
632
633 // Calculate the multiplicative inverse of K! / 2^T;
634 // this multiplication factor will perform the exact division by
635 // K! / 2^T.
636 APInt Mod = APInt::getSignedMinValue(W+1);
637 APInt MultiplyFactor = OddFactorial.zext(W+1);
638 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
639 MultiplyFactor = MultiplyFactor.trunc(W);
640
641 // Calculate the product, at width T+W
642 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
643 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
644 for (unsigned i = 1; i != K; ++i) {
645 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
646 Dividend = SE.getMulExpr(Dividend,
647 SE.getTruncateOrZeroExtend(S, CalculationTy));
648 }
649
650 // Divide by 2^T
651 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
652
653 // Truncate the result, and divide by K! / 2^T.
654
655 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
656 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000657}
658
Chris Lattner53e677a2004-04-02 20:23:17 +0000659/// evaluateAtIteration - Return the value of this chain of recurrences at
660/// the specified iteration number. We can evaluate this recurrence by
661/// multiplying each element in the chain by the binomial coefficient
662/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
663///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000664/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000665///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000666/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000667///
Dan Gohman246b2562007-10-22 18:31:58 +0000668SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
669 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000670 SCEVHandle Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000671 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000672 // The computation is correct in the face of overflow provided that the
673 // multiplication is performed _after_ the evaluation of the binomial
674 // coefficient.
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000675 SCEVHandle Coeff = BinomialCoefficient(It, i, SE,
676 cast<IntegerType>(getType()));
677 if (isa<SCEVCouldNotCompute>(Coeff))
678 return Coeff;
679
680 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000681 }
682 return Result;
683}
684
Chris Lattner53e677a2004-04-02 20:23:17 +0000685//===----------------------------------------------------------------------===//
686// SCEV Expression folder implementations
687//===----------------------------------------------------------------------===//
688
Dan Gohman246b2562007-10-22 18:31:58 +0000689SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000690 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000691 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000692 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000693
694 // If the input value is a chrec scev made out of constants, truncate
695 // all of the constants.
696 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
697 std::vector<SCEVHandle> Operands;
698 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
699 // FIXME: This should allow truncation of other expression types!
700 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman246b2562007-10-22 18:31:58 +0000701 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000702 else
703 break;
704 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman246b2562007-10-22 18:31:58 +0000705 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000706 }
707
Chris Lattnerb3364092006-10-04 21:49:37 +0000708 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000709 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
710 return Result;
711}
712
Dan Gohman246b2562007-10-22 18:31:58 +0000713SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000714 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000715 return getUnknown(
Reid Spencerd977d862006-12-12 23:36:14 +0000716 ConstantExpr::getZExt(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000717
718 // FIXME: If the input value is a chrec scev, and we can prove that the value
719 // did not overflow the old, smaller, value, we can zero extend all of the
720 // operands (often constants). This would allow analysis of something like
721 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
722
Chris Lattnerb3364092006-10-04 21:49:37 +0000723 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000724 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
725 return Result;
726}
727
Dan Gohman246b2562007-10-22 18:31:58 +0000728SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmand19534a2007-06-15 14:38:12 +0000729 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000730 return getUnknown(
Dan Gohmand19534a2007-06-15 14:38:12 +0000731 ConstantExpr::getSExt(SC->getValue(), Ty));
732
733 // FIXME: If the input value is a chrec scev, and we can prove that the value
734 // did not overflow the old, smaller, value, we can sign extend all of the
735 // operands (often constants). This would allow analysis of something like
736 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
737
738 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
739 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
740 return Result;
741}
742
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000743/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
744/// of the input value to the specified type. If the type must be
745/// extended, it is zero extended.
746SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
747 const Type *Ty) {
748 const Type *SrcTy = V->getType();
749 assert(SrcTy->isInteger() && Ty->isInteger() &&
750 "Cannot truncate or zero extend with non-integer arguments!");
751 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
752 return V; // No conversion
753 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
754 return getTruncateExpr(V, Ty);
755 return getZeroExtendExpr(V, Ty);
756}
757
Chris Lattner53e677a2004-04-02 20:23:17 +0000758// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman246b2562007-10-22 18:31:58 +0000759SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000760 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000761 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000762
763 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000764 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000765
766 // If there are any constants, fold them together.
767 unsigned Idx = 0;
768 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
769 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000770 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000771 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
772 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000773 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
774 RHSC->getValue()->getValue());
775 Ops[0] = getConstant(Fold);
776 Ops.erase(Ops.begin()+1); // Erase the folded element
777 if (Ops.size() == 1) return Ops[0];
778 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000779 }
780
781 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +0000782 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000783 Ops.erase(Ops.begin());
784 --Idx;
785 }
786 }
787
Chris Lattner627018b2004-04-07 16:16:11 +0000788 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000789
Chris Lattner53e677a2004-04-02 20:23:17 +0000790 // Okay, check to see if the same value occurs in the operand list twice. If
791 // so, merge them together into an multiply expression. Since we sorted the
792 // list, these values are required to be adjacent.
793 const Type *Ty = Ops[0]->getType();
794 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
795 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
796 // Found a match, merge the two values into a multiply, and add any
797 // remaining values to the result.
Dan Gohman246b2562007-10-22 18:31:58 +0000798 SCEVHandle Two = getIntegerSCEV(2, Ty);
799 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +0000800 if (Ops.size() == 2)
801 return Mul;
802 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
803 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +0000804 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000805 }
806
Dan Gohmanf50cd742007-06-18 19:30:09 +0000807 // Now we know the first non-constant operand. Skip past any cast SCEVs.
808 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
809 ++Idx;
810
811 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +0000812 if (Idx < Ops.size()) {
813 bool DeletedAdd = false;
814 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
815 // If we have an add, expand the add operands onto the end of the operands
816 // list.
817 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
818 Ops.erase(Ops.begin()+Idx);
819 DeletedAdd = true;
820 }
821
822 // If we deleted at least one add, we added operands to the end of the list,
823 // and they are not necessarily sorted. Recurse to resort and resimplify
824 // any operands we just aquired.
825 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +0000826 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000827 }
828
829 // Skip over the add expression until we get to a multiply.
830 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
831 ++Idx;
832
833 // If we are adding something to a multiply expression, make sure the
834 // something is not already an operand of the multiply. If so, merge it into
835 // the multiply.
836 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
837 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
838 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
839 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
840 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000841 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000842 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
843 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
844 if (Mul->getNumOperands() != 2) {
845 // If the multiply has more than two operands, we must get the
846 // Y*Z term.
847 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
848 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000849 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000850 }
Dan Gohman246b2562007-10-22 18:31:58 +0000851 SCEVHandle One = getIntegerSCEV(1, Ty);
852 SCEVHandle AddOne = getAddExpr(InnerMul, One);
853 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000854 if (Ops.size() == 2) return OuterMul;
855 if (AddOp < Idx) {
856 Ops.erase(Ops.begin()+AddOp);
857 Ops.erase(Ops.begin()+Idx-1);
858 } else {
859 Ops.erase(Ops.begin()+Idx);
860 Ops.erase(Ops.begin()+AddOp-1);
861 }
862 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000863 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000864 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000865
Chris Lattner53e677a2004-04-02 20:23:17 +0000866 // Check this multiply against other multiplies being added together.
867 for (unsigned OtherMulIdx = Idx+1;
868 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
869 ++OtherMulIdx) {
870 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
871 // If MulOp occurs in OtherMul, we can fold the two multiplies
872 // together.
873 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
874 OMulOp != e; ++OMulOp)
875 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
876 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
877 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
878 if (Mul->getNumOperands() != 2) {
879 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
880 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000881 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000882 }
883 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
884 if (OtherMul->getNumOperands() != 2) {
885 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
886 OtherMul->op_end());
887 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000888 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000889 }
Dan Gohman246b2562007-10-22 18:31:58 +0000890 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
891 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +0000892 if (Ops.size() == 2) return OuterMul;
893 Ops.erase(Ops.begin()+Idx);
894 Ops.erase(Ops.begin()+OtherMulIdx-1);
895 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000896 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000897 }
898 }
899 }
900 }
901
902 // If there are any add recurrences in the operands list, see if any other
903 // added values are loop invariant. If so, we can fold them into the
904 // recurrence.
905 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
906 ++Idx;
907
908 // Scan over all recurrences, trying to fold loop invariants into them.
909 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
910 // Scan all of the other operands to this add and add them to the vector if
911 // they are loop invariant w.r.t. the recurrence.
912 std::vector<SCEVHandle> LIOps;
913 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
914 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
915 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
916 LIOps.push_back(Ops[i]);
917 Ops.erase(Ops.begin()+i);
918 --i; --e;
919 }
920
921 // If we found some loop invariants, fold them into the recurrence.
922 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +0000923 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +0000924 LIOps.push_back(AddRec->getStart());
925
926 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +0000927 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000928
Dan Gohman246b2562007-10-22 18:31:58 +0000929 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000930 // If all of the other operands were loop invariant, we are done.
931 if (Ops.size() == 1) return NewRec;
932
933 // Otherwise, add the folded AddRec by the non-liv parts.
934 for (unsigned i = 0;; ++i)
935 if (Ops[i] == AddRec) {
936 Ops[i] = NewRec;
937 break;
938 }
Dan Gohman246b2562007-10-22 18:31:58 +0000939 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000940 }
941
942 // Okay, if there weren't any loop invariants to be folded, check to see if
943 // there are multiple AddRec's with the same loop induction variable being
944 // added together. If so, we can fold them.
945 for (unsigned OtherIdx = Idx+1;
946 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
947 if (OtherIdx != Idx) {
948 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
949 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
950 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
951 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
952 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
953 if (i >= NewOps.size()) {
954 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
955 OtherAddRec->op_end());
956 break;
957 }
Dan Gohman246b2562007-10-22 18:31:58 +0000958 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +0000959 }
Dan Gohman246b2562007-10-22 18:31:58 +0000960 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000961
962 if (Ops.size() == 2) return NewAddRec;
963
964 Ops.erase(Ops.begin()+Idx);
965 Ops.erase(Ops.begin()+OtherIdx-1);
966 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +0000967 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000968 }
969 }
970
971 // Otherwise couldn't fold anything into this recurrence. Move onto the
972 // next one.
973 }
974
975 // Okay, it looks like we really DO need an add expr. Check to see if we
976 // already have one, otherwise create a new one.
977 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000978 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
979 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000980 if (Result == 0) Result = new SCEVAddExpr(Ops);
981 return Result;
982}
983
984
Dan Gohman246b2562007-10-22 18:31:58 +0000985SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000986 assert(!Ops.empty() && "Cannot get empty mul!");
987
988 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000989 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000990
991 // If there are any constants, fold them together.
992 unsigned Idx = 0;
993 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
994
995 // C1*(C2+V) -> C1*C2 + C1*V
996 if (Ops.size() == 2)
997 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
998 if (Add->getNumOperands() == 2 &&
999 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001000 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1001 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001002
1003
1004 ++Idx;
1005 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1006 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001007 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1008 RHSC->getValue()->getValue());
1009 Ops[0] = getConstant(Fold);
1010 Ops.erase(Ops.begin()+1); // Erase the folded element
1011 if (Ops.size() == 1) return Ops[0];
1012 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001013 }
1014
1015 // If we are left with a constant one being multiplied, strip it off.
1016 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1017 Ops.erase(Ops.begin());
1018 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001019 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001020 // If we have a multiply of zero, it will always be zero.
1021 return Ops[0];
1022 }
1023 }
1024
1025 // Skip over the add expression until we get to a multiply.
1026 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1027 ++Idx;
1028
1029 if (Ops.size() == 1)
1030 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001031
Chris Lattner53e677a2004-04-02 20:23:17 +00001032 // If there are mul operands inline them all into this expression.
1033 if (Idx < Ops.size()) {
1034 bool DeletedMul = false;
1035 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1036 // If we have an mul, expand the mul operands onto the end of the operands
1037 // list.
1038 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1039 Ops.erase(Ops.begin()+Idx);
1040 DeletedMul = true;
1041 }
1042
1043 // If we deleted at least one mul, we added operands to the end of the list,
1044 // and they are not necessarily sorted. Recurse to resort and resimplify
1045 // any operands we just aquired.
1046 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001047 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001048 }
1049
1050 // If there are any add recurrences in the operands list, see if any other
1051 // added values are loop invariant. If so, we can fold them into the
1052 // recurrence.
1053 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1054 ++Idx;
1055
1056 // Scan over all recurrences, trying to fold loop invariants into them.
1057 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1058 // Scan all of the other operands to this mul and add them to the vector if
1059 // they are loop invariant w.r.t. the recurrence.
1060 std::vector<SCEVHandle> LIOps;
1061 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1062 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1063 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1064 LIOps.push_back(Ops[i]);
1065 Ops.erase(Ops.begin()+i);
1066 --i; --e;
1067 }
1068
1069 // If we found some loop invariants, fold them into the recurrence.
1070 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001071 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001072 std::vector<SCEVHandle> NewOps;
1073 NewOps.reserve(AddRec->getNumOperands());
1074 if (LIOps.size() == 1) {
1075 SCEV *Scale = LIOps[0];
1076 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001077 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001078 } else {
1079 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1080 std::vector<SCEVHandle> MulOps(LIOps);
1081 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001082 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001083 }
1084 }
1085
Dan Gohman246b2562007-10-22 18:31:58 +00001086 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001087
1088 // If all of the other operands were loop invariant, we are done.
1089 if (Ops.size() == 1) return NewRec;
1090
1091 // Otherwise, multiply the folded AddRec by the non-liv parts.
1092 for (unsigned i = 0;; ++i)
1093 if (Ops[i] == AddRec) {
1094 Ops[i] = NewRec;
1095 break;
1096 }
Dan Gohman246b2562007-10-22 18:31:58 +00001097 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001098 }
1099
1100 // Okay, if there weren't any loop invariants to be folded, check to see if
1101 // there are multiple AddRec's with the same loop induction variable being
1102 // multiplied together. If so, we can fold them.
1103 for (unsigned OtherIdx = Idx+1;
1104 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1105 if (OtherIdx != Idx) {
1106 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1107 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1108 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1109 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman246b2562007-10-22 18:31:58 +00001110 SCEVHandle NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001111 G->getStart());
Dan Gohman246b2562007-10-22 18:31:58 +00001112 SCEVHandle B = F->getStepRecurrence(*this);
1113 SCEVHandle D = G->getStepRecurrence(*this);
1114 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1115 getMulExpr(G, B),
1116 getMulExpr(B, D));
1117 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1118 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001119 if (Ops.size() == 2) return NewAddRec;
1120
1121 Ops.erase(Ops.begin()+Idx);
1122 Ops.erase(Ops.begin()+OtherIdx-1);
1123 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001124 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001125 }
1126 }
1127
1128 // Otherwise couldn't fold anything into this recurrence. Move onto the
1129 // next one.
1130 }
1131
1132 // Okay, it looks like we really DO need an mul expr. Check to see if we
1133 // already have one, otherwise create a new one.
1134 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001135 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1136 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001137 if (Result == 0)
1138 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001139 return Result;
1140}
1141
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001142SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001143 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1144 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky789558d2009-01-13 09:18:58 +00001145 return LHS; // X udiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +00001146
1147 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1148 Constant *LHSCV = LHSC->getValue();
1149 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001150 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001151 }
1152 }
1153
Nick Lewycky789558d2009-01-13 09:18:58 +00001154 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1155
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001156 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1157 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001158 return Result;
1159}
1160
1161
1162/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1163/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001164SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Chris Lattner53e677a2004-04-02 20:23:17 +00001165 const SCEVHandle &Step, const Loop *L) {
1166 std::vector<SCEVHandle> Operands;
1167 Operands.push_back(Start);
1168 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1169 if (StepChrec->getLoop() == L) {
1170 Operands.insert(Operands.end(), StepChrec->op_begin(),
1171 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001172 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001173 }
1174
1175 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001176 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001177}
1178
1179/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1180/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001181SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Chris Lattner53e677a2004-04-02 20:23:17 +00001182 const Loop *L) {
1183 if (Operands.size() == 1) return Operands[0];
1184
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001185 if (Operands.back()->isZero()) {
1186 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001187 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001188 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001189
Dan Gohmand9cc7492008-08-08 18:33:12 +00001190 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1191 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1192 const Loop* NestedLoop = NestedAR->getLoop();
1193 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1194 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1195 NestedAR->op_end());
1196 SCEVHandle NestedARHandle(NestedAR);
1197 Operands[0] = NestedAR->getStart();
1198 NestedOperands[0] = getAddRecExpr(Operands, L);
1199 return getAddRecExpr(NestedOperands, NestedLoop);
1200 }
1201 }
1202
Chris Lattner53e677a2004-04-02 20:23:17 +00001203 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001204 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1205 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001206 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1207 return Result;
1208}
1209
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001210SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1211 const SCEVHandle &RHS) {
1212 std::vector<SCEVHandle> Ops;
1213 Ops.push_back(LHS);
1214 Ops.push_back(RHS);
1215 return getSMaxExpr(Ops);
1216}
1217
1218SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1219 assert(!Ops.empty() && "Cannot get empty smax!");
1220 if (Ops.size() == 1) return Ops[0];
1221
1222 // Sort by complexity, this groups all similar expression types together.
1223 GroupByComplexity(Ops);
1224
1225 // If there are any constants, fold them together.
1226 unsigned Idx = 0;
1227 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1228 ++Idx;
1229 assert(Idx < Ops.size());
1230 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1231 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001232 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001233 APIntOps::smax(LHSC->getValue()->getValue(),
1234 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001235 Ops[0] = getConstant(Fold);
1236 Ops.erase(Ops.begin()+1); // Erase the folded element
1237 if (Ops.size() == 1) return Ops[0];
1238 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001239 }
1240
1241 // If we are left with a constant -inf, strip it off.
1242 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1243 Ops.erase(Ops.begin());
1244 --Idx;
1245 }
1246 }
1247
1248 if (Ops.size() == 1) return Ops[0];
1249
1250 // Find the first SMax
1251 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1252 ++Idx;
1253
1254 // Check to see if one of the operands is an SMax. If so, expand its operands
1255 // onto our operand list, and recurse to simplify.
1256 if (Idx < Ops.size()) {
1257 bool DeletedSMax = false;
1258 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1259 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1260 Ops.erase(Ops.begin()+Idx);
1261 DeletedSMax = true;
1262 }
1263
1264 if (DeletedSMax)
1265 return getSMaxExpr(Ops);
1266 }
1267
1268 // Okay, check to see if the same value occurs in the operand list twice. If
1269 // so, delete one. Since we sorted the list, these values are required to
1270 // be adjacent.
1271 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1272 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1273 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1274 --i; --e;
1275 }
1276
1277 if (Ops.size() == 1) return Ops[0];
1278
1279 assert(!Ops.empty() && "Reduced smax down to nothing!");
1280
Nick Lewycky3e630762008-02-20 06:48:22 +00001281 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001282 // already have one, otherwise create a new one.
1283 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1284 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1285 SCEVOps)];
1286 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1287 return Result;
1288}
1289
Nick Lewycky3e630762008-02-20 06:48:22 +00001290SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1291 const SCEVHandle &RHS) {
1292 std::vector<SCEVHandle> Ops;
1293 Ops.push_back(LHS);
1294 Ops.push_back(RHS);
1295 return getUMaxExpr(Ops);
1296}
1297
1298SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1299 assert(!Ops.empty() && "Cannot get empty umax!");
1300 if (Ops.size() == 1) return Ops[0];
1301
1302 // Sort by complexity, this groups all similar expression types together.
1303 GroupByComplexity(Ops);
1304
1305 // If there are any constants, fold them together.
1306 unsigned Idx = 0;
1307 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1308 ++Idx;
1309 assert(Idx < Ops.size());
1310 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1311 // We found two constants, fold them together!
1312 ConstantInt *Fold = ConstantInt::get(
1313 APIntOps::umax(LHSC->getValue()->getValue(),
1314 RHSC->getValue()->getValue()));
1315 Ops[0] = getConstant(Fold);
1316 Ops.erase(Ops.begin()+1); // Erase the folded element
1317 if (Ops.size() == 1) return Ops[0];
1318 LHSC = cast<SCEVConstant>(Ops[0]);
1319 }
1320
1321 // If we are left with a constant zero, strip it off.
1322 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1323 Ops.erase(Ops.begin());
1324 --Idx;
1325 }
1326 }
1327
1328 if (Ops.size() == 1) return Ops[0];
1329
1330 // Find the first UMax
1331 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1332 ++Idx;
1333
1334 // Check to see if one of the operands is a UMax. If so, expand its operands
1335 // onto our operand list, and recurse to simplify.
1336 if (Idx < Ops.size()) {
1337 bool DeletedUMax = false;
1338 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1339 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1340 Ops.erase(Ops.begin()+Idx);
1341 DeletedUMax = true;
1342 }
1343
1344 if (DeletedUMax)
1345 return getUMaxExpr(Ops);
1346 }
1347
1348 // Okay, check to see if the same value occurs in the operand list twice. If
1349 // so, delete one. Since we sorted the list, these values are required to
1350 // be adjacent.
1351 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1352 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1353 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1354 --i; --e;
1355 }
1356
1357 if (Ops.size() == 1) return Ops[0];
1358
1359 assert(!Ops.empty() && "Reduced umax down to nothing!");
1360
1361 // Okay, it looks like we really DO need a umax expr. Check to see if we
1362 // already have one, otherwise create a new one.
1363 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1364 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1365 SCEVOps)];
1366 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1367 return Result;
1368}
1369
Dan Gohman246b2562007-10-22 18:31:58 +00001370SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001371 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001372 return getConstant(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001373 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001374 if (Result == 0) Result = new SCEVUnknown(V);
1375 return Result;
1376}
1377
Chris Lattner53e677a2004-04-02 20:23:17 +00001378
1379//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001380// ScalarEvolutionsImpl Definition and Implementation
1381//===----------------------------------------------------------------------===//
1382//
1383/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1384/// evolution code.
1385///
1386namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001387 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohman246b2562007-10-22 18:31:58 +00001388 /// SE - A reference to the public ScalarEvolution object.
1389 ScalarEvolution &SE;
1390
Chris Lattner53e677a2004-04-02 20:23:17 +00001391 /// F - The function we are analyzing.
1392 ///
1393 Function &F;
1394
1395 /// LI - The loop information for the function we are currently analyzing.
1396 ///
1397 LoopInfo &LI;
1398
1399 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1400 /// things.
1401 SCEVHandle UnknownValue;
1402
1403 /// Scalars - This is a cache of the scalars we have analyzed so far.
1404 ///
1405 std::map<Value*, SCEVHandle> Scalars;
1406
1407 /// IterationCounts - Cache the iteration count of the loops for this
1408 /// function as they are computed.
1409 std::map<const Loop*, SCEVHandle> IterationCounts;
1410
Chris Lattner3221ad02004-04-17 22:58:41 +00001411 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1412 /// the PHI instructions that we attempt to compute constant evolutions for.
1413 /// This allows us to avoid potentially expensive recomputation of these
1414 /// properties. An instruction maps to null if we are unable to compute its
1415 /// exit value.
1416 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001417
Chris Lattner53e677a2004-04-02 20:23:17 +00001418 public:
Dan Gohman246b2562007-10-22 18:31:58 +00001419 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1420 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
Chris Lattner53e677a2004-04-02 20:23:17 +00001421
1422 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1423 /// expression and create a new one.
1424 SCEVHandle getSCEV(Value *V);
1425
Chris Lattnera0740fb2005-08-09 23:36:33 +00001426 /// hasSCEV - Return true if the SCEV for this value has already been
1427 /// computed.
1428 bool hasSCEV(Value *V) const {
1429 return Scalars.count(V);
1430 }
1431
1432 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1433 /// the specified value.
1434 void setSCEV(Value *V, const SCEVHandle &H) {
1435 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1436 assert(isNew && "This entry already existed!");
Devang Patel89d0a4d2008-11-11 19:17:41 +00001437 isNew = false;
Chris Lattnera0740fb2005-08-09 23:36:33 +00001438 }
1439
1440
Chris Lattner53e677a2004-04-02 20:23:17 +00001441 /// getSCEVAtScope - Compute the value of the specified expression within
1442 /// the indicated loop (which may be null to indicate in no loop). If the
1443 /// expression cannot be evaluated, return UnknownValue itself.
1444 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1445
1446
Dan Gohmanc2390b12009-02-12 22:19:27 +00001447 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
1448 /// a conditional between LHS and RHS.
1449 bool isLoopGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
1450 SCEV *LHS, SCEV *RHS);
1451
Chris Lattner53e677a2004-04-02 20:23:17 +00001452 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1453 /// an analyzable loop-invariant iteration count.
1454 bool hasLoopInvariantIterationCount(const Loop *L);
1455
Dan Gohman60f8a632009-02-17 20:49:49 +00001456 /// forgetLoopIterationCount - This method should be called by the
1457 /// client when it has changed a loop in a way that may effect
1458 /// ScalarEvolution's ability to compute a trip count.
1459 void forgetLoopIterationCount(const Loop *L);
1460
Chris Lattner53e677a2004-04-02 20:23:17 +00001461 /// getIterationCount - If the specified loop has a predictable iteration
1462 /// count, return it. Note that it is not valid to call this method on a
1463 /// loop without a loop-invariant iteration count.
1464 SCEVHandle getIterationCount(const Loop *L);
1465
Dan Gohman5cec4db2007-06-19 14:28:31 +00001466 /// deleteValueFromRecords - This method should be called by the
1467 /// client before it removes a value from the program, to make sure
Chris Lattner53e677a2004-04-02 20:23:17 +00001468 /// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001469 void deleteValueFromRecords(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001470
1471 private:
1472 /// createSCEV - We know that there is no SCEV for the specified value.
1473 /// Analyze the expression.
1474 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001475
1476 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1477 /// SCEVs.
1478 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001479
1480 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1481 /// for the specified instruction and replaces any references to the
1482 /// symbolic value SymName with the specified value. This is used during
1483 /// PHI resolution.
1484 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1485 const SCEVHandle &SymName,
1486 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001487
1488 /// ComputeIterationCount - Compute the number of times the specified loop
1489 /// will iterate.
1490 SCEVHandle ComputeIterationCount(const Loop *L);
1491
Chris Lattner673e02b2004-10-12 01:49:27 +00001492 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001493 /// 'icmp op load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00001494 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1495 Constant *RHS,
1496 const Loop *L,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001497 ICmpInst::Predicate p);
Chris Lattner673e02b2004-10-12 01:49:27 +00001498
Chris Lattner7980fb92004-04-17 18:36:24 +00001499 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1500 /// constant number of times (the condition evolves only from constants),
1501 /// try to evaluate a few iterations of the loop until we get the exit
1502 /// condition gets a value of ExitWhen (true or false). If we cannot
1503 /// evaluate the trip count of the loop, return UnknownValue.
1504 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1505 bool ExitWhen);
1506
Chris Lattner53e677a2004-04-02 20:23:17 +00001507 /// HowFarToZero - Return the number of times a backedge comparing the
1508 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001509 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001510 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1511
1512 /// HowFarToNonZero - Return the number of times a backedge checking the
1513 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001514 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001515 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001516
Chris Lattnerdb25de42005-08-15 23:33:51 +00001517 /// HowManyLessThans - Return the number of times a backedge containing the
1518 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001519 /// UnknownValue. isSigned specifies whether the less-than is signed.
1520 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
Nick Lewycky789558d2009-01-13 09:18:58 +00001521 bool isSigned);
Chris Lattnerdb25de42005-08-15 23:33:51 +00001522
Dan Gohmanfd6edef2008-09-15 22:18:04 +00001523 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
1524 /// (which may not be an immediate predecessor) which has exactly one
1525 /// successor from which BB is reachable, or null if no such block is
1526 /// found.
1527 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1528
Chris Lattner3221ad02004-04-17 22:58:41 +00001529 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1530 /// in the header of its containing loop, we know the loop executes a
1531 /// constant number of times, and the PHI node is just a recurrence
1532 /// involving constants, fold it.
Reid Spencere8019bb2007-03-01 07:25:48 +00001533 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
Chris Lattner3221ad02004-04-17 22:58:41 +00001534 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001535 };
1536}
1537
1538//===----------------------------------------------------------------------===//
1539// Basic SCEV Analysis and PHI Idiom Recognition Code
1540//
1541
Dan Gohman5cec4db2007-06-19 14:28:31 +00001542/// deleteValueFromRecords - This method should be called by the
Chris Lattner53e677a2004-04-02 20:23:17 +00001543/// client before it removes an instruction from the program, to make sure
1544/// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001545void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1546 SmallVector<Value *, 16> Worklist;
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001547
Dan Gohman5cec4db2007-06-19 14:28:31 +00001548 if (Scalars.erase(V)) {
1549 if (PHINode *PN = dyn_cast<PHINode>(V))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001550 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman5cec4db2007-06-19 14:28:31 +00001551 Worklist.push_back(V);
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001552 }
1553
1554 while (!Worklist.empty()) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001555 Value *VV = Worklist.back();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001556 Worklist.pop_back();
1557
Dan Gohman5cec4db2007-06-19 14:28:31 +00001558 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001559 UI != UE; ++UI) {
Nick Lewycky51e844b2007-06-06 11:26:20 +00001560 Instruction *Inst = cast<Instruction>(*UI);
1561 if (Scalars.erase(Inst)) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001562 if (PHINode *PN = dyn_cast<PHINode>(VV))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001563 ConstantEvolutionLoopExitValue.erase(PN);
1564 Worklist.push_back(Inst);
1565 }
1566 }
1567 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001568}
1569
1570
1571/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1572/// expression and create a new one.
1573SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1574 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1575
1576 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1577 if (I != Scalars.end()) return I->second;
1578 SCEVHandle S = createSCEV(V);
1579 Scalars.insert(std::make_pair(V, S));
1580 return S;
1581}
1582
Chris Lattner4dc534c2005-02-13 04:37:18 +00001583/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1584/// the specified instruction and replaces any references to the symbolic value
1585/// SymName with the specified value. This is used during PHI resolution.
1586void ScalarEvolutionsImpl::
1587ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1588 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001589 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001590 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001591
Chris Lattner4dc534c2005-02-13 04:37:18 +00001592 SCEVHandle NV =
Dan Gohman246b2562007-10-22 18:31:58 +00001593 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001594 if (NV == SI->second) return; // No change.
1595
1596 SI->second = NV; // Update the scalars map!
1597
1598 // Any instruction values that use this instruction might also need to be
1599 // updated!
1600 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1601 UI != E; ++UI)
1602 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1603}
Chris Lattner53e677a2004-04-02 20:23:17 +00001604
1605/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1606/// a loop header, making it a potential recurrence, or it doesn't.
1607///
1608SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1609 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1610 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1611 if (L->getHeader() == PN->getParent()) {
1612 // If it lives in the loop header, it has two incoming values, one
1613 // from outside the loop, and one from inside.
1614 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1615 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001616
Chris Lattner53e677a2004-04-02 20:23:17 +00001617 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman246b2562007-10-22 18:31:58 +00001618 SCEVHandle SymbolicName = SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001619 assert(Scalars.find(PN) == Scalars.end() &&
1620 "PHI node already processed?");
1621 Scalars.insert(std::make_pair(PN, SymbolicName));
1622
1623 // Using this symbolic name for the PHI, analyze the value coming around
1624 // the back-edge.
1625 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1626
1627 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1628 // has a special value for the first iteration of the loop.
1629
1630 // If the value coming around the backedge is an add with the symbolic
1631 // value we just inserted, then we found a simple induction variable!
1632 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1633 // If there is a single occurrence of the symbolic value, replace it
1634 // with a recurrence.
1635 unsigned FoundIndex = Add->getNumOperands();
1636 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1637 if (Add->getOperand(i) == SymbolicName)
1638 if (FoundIndex == e) {
1639 FoundIndex = i;
1640 break;
1641 }
1642
1643 if (FoundIndex != Add->getNumOperands()) {
1644 // Create an add with everything but the specified operand.
1645 std::vector<SCEVHandle> Ops;
1646 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1647 if (i != FoundIndex)
1648 Ops.push_back(Add->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001649 SCEVHandle Accum = SE.getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001650
1651 // This is not a valid addrec if the step amount is varying each
1652 // loop iteration, but is not itself an addrec in this loop.
1653 if (Accum->isLoopInvariant(L) ||
1654 (isa<SCEVAddRecExpr>(Accum) &&
1655 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1656 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman246b2562007-10-22 18:31:58 +00001657 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001658
1659 // Okay, for the entire analysis of this edge we assumed the PHI
1660 // to be symbolic. We now need to go back and update all of the
1661 // entries for the scalars that use the PHI (except for the PHI
1662 // itself) to use the new analyzed value instead of the "symbolic"
1663 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001664 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001665 return PHISCEV;
1666 }
1667 }
Chris Lattner97156e72006-04-26 18:34:07 +00001668 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1669 // Otherwise, this could be a loop like this:
1670 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1671 // In this case, j = {1,+,1} and BEValue is j.
1672 // Because the other in-value of i (0) fits the evolution of BEValue
1673 // i really is an addrec evolution.
1674 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1675 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1676
1677 // If StartVal = j.start - j.stride, we can use StartVal as the
1678 // initial step of the addrec evolution.
Dan Gohman246b2562007-10-22 18:31:58 +00001679 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1680 AddRec->getOperand(1))) {
Chris Lattner97156e72006-04-26 18:34:07 +00001681 SCEVHandle PHISCEV =
Dan Gohman246b2562007-10-22 18:31:58 +00001682 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00001683
1684 // Okay, for the entire analysis of this edge we assumed the PHI
1685 // to be symbolic. We now need to go back and update all of the
1686 // entries for the scalars that use the PHI (except for the PHI
1687 // itself) to use the new analyzed value instead of the "symbolic"
1688 // value.
1689 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1690 return PHISCEV;
1691 }
1692 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001693 }
1694
1695 return SymbolicName;
1696 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001697
Chris Lattner53e677a2004-04-02 20:23:17 +00001698 // If it's not a loop phi, we can't handle it yet.
Dan Gohman246b2562007-10-22 18:31:58 +00001699 return SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001700}
1701
Nick Lewycky83bb0052007-11-22 07:59:40 +00001702/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1703/// guaranteed to end in (at every loop iteration). It is, at the same time,
1704/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1705/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1706static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1707 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00001708 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00001709
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001710 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Nick Lewycky83bb0052007-11-22 07:59:40 +00001711 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1712
1713 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1714 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1715 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1716 }
1717
1718 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1719 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1720 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1721 }
1722
Chris Lattnera17f0392006-12-12 02:26:09 +00001723 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001724 // The result is the min of all operands results.
1725 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1726 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1727 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1728 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001729 }
1730
1731 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001732 // The result is the sum of all operands results.
1733 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1734 uint32_t BitWidth = M->getBitWidth();
1735 for (unsigned i = 1, e = M->getNumOperands();
1736 SumOpRes != BitWidth && i != e; ++i)
1737 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1738 BitWidth);
1739 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001740 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001741
Chris Lattnera17f0392006-12-12 02:26:09 +00001742 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001743 // The result is the min of all operands results.
1744 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1745 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1746 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1747 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001748 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001749
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001750 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1751 // The result is the min of all operands results.
1752 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1753 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1754 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1755 return MinOpRes;
1756 }
1757
Nick Lewycky3e630762008-02-20 06:48:22 +00001758 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1759 // The result is the min of all operands results.
1760 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1761 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1762 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1763 return MinOpRes;
1764 }
1765
Nick Lewycky789558d2009-01-13 09:18:58 +00001766 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky83bb0052007-11-22 07:59:40 +00001767 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00001768}
Chris Lattner53e677a2004-04-02 20:23:17 +00001769
1770/// createSCEV - We know that there is no SCEV for the specified value.
1771/// Analyze the expression.
1772///
1773SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
Chris Lattner42b5e082007-11-23 08:46:22 +00001774 if (!isa<IntegerType>(V->getType()))
1775 return SE.getUnknown(V);
1776
Dan Gohman6c459a22008-06-22 19:56:46 +00001777 unsigned Opcode = Instruction::UserOp1;
1778 if (Instruction *I = dyn_cast<Instruction>(V))
1779 Opcode = I->getOpcode();
1780 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1781 Opcode = CE->getOpcode();
1782 else
1783 return SE.getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00001784
Dan Gohman6c459a22008-06-22 19:56:46 +00001785 User *U = cast<User>(V);
1786 switch (Opcode) {
1787 case Instruction::Add:
1788 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1789 getSCEV(U->getOperand(1)));
1790 case Instruction::Mul:
1791 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1792 getSCEV(U->getOperand(1)));
1793 case Instruction::UDiv:
1794 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1795 getSCEV(U->getOperand(1)));
1796 case Instruction::Sub:
1797 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1798 getSCEV(U->getOperand(1)));
1799 case Instruction::Or:
1800 // If the RHS of the Or is a constant, we may have something like:
1801 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1802 // optimizations will transparently handle this case.
1803 //
1804 // In order for this transformation to be safe, the LHS must be of the
1805 // form X*(2^n) and the Or constant must be less than 2^n.
1806 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1807 SCEVHandle LHS = getSCEV(U->getOperand(0));
1808 const APInt &CIVal = CI->getValue();
1809 if (GetMinTrailingZeros(LHS) >=
1810 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1811 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001812 }
Dan Gohman6c459a22008-06-22 19:56:46 +00001813 break;
1814 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00001815 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00001816 // If the RHS of the xor is a signbit, then this is just an add.
1817 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00001818 if (CI->getValue().isSignBit())
1819 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1820 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00001821
1822 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman6c459a22008-06-22 19:56:46 +00001823 else if (CI->isAllOnesValue())
1824 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1825 }
1826 break;
1827
1828 case Instruction::Shl:
1829 // Turn shift left of a constant amount into a multiply.
1830 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1831 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1832 Constant *X = ConstantInt::get(
1833 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1834 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1835 }
1836 break;
1837
Nick Lewycky01eaf802008-07-07 06:15:49 +00001838 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00001839 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00001840 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1841 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1842 Constant *X = ConstantInt::get(
1843 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1844 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1845 }
1846 break;
1847
Dan Gohman6c459a22008-06-22 19:56:46 +00001848 case Instruction::Trunc:
1849 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1850
1851 case Instruction::ZExt:
1852 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1853
1854 case Instruction::SExt:
1855 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1856
1857 case Instruction::BitCast:
1858 // BitCasts are no-op casts so we just eliminate the cast.
1859 if (U->getType()->isInteger() &&
1860 U->getOperand(0)->getType()->isInteger())
1861 return getSCEV(U->getOperand(0));
1862 break;
1863
1864 case Instruction::PHI:
1865 return createNodeForPHI(cast<PHINode>(U));
1866
1867 case Instruction::Select:
1868 // This could be a smax or umax that was lowered earlier.
1869 // Try to recover it.
1870 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1871 Value *LHS = ICI->getOperand(0);
1872 Value *RHS = ICI->getOperand(1);
1873 switch (ICI->getPredicate()) {
1874 case ICmpInst::ICMP_SLT:
1875 case ICmpInst::ICMP_SLE:
1876 std::swap(LHS, RHS);
1877 // fall through
1878 case ICmpInst::ICMP_SGT:
1879 case ICmpInst::ICMP_SGE:
1880 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1881 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1882 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman1fbffe02008-07-30 04:36:32 +00001883 // ~smax(~x, ~y) == smin(x, y).
1884 return SE.getNotSCEV(SE.getSMaxExpr(
1885 SE.getNotSCEV(getSCEV(LHS)),
1886 SE.getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00001887 break;
1888 case ICmpInst::ICMP_ULT:
1889 case ICmpInst::ICMP_ULE:
1890 std::swap(LHS, RHS);
1891 // fall through
1892 case ICmpInst::ICMP_UGT:
1893 case ICmpInst::ICMP_UGE:
1894 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1895 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1896 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1897 // ~umax(~x, ~y) == umin(x, y)
1898 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
1899 SE.getNotSCEV(getSCEV(RHS))));
1900 break;
1901 default:
1902 break;
1903 }
1904 }
1905
1906 default: // We cannot analyze this expression.
1907 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001908 }
1909
Dan Gohman246b2562007-10-22 18:31:58 +00001910 return SE.getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001911}
1912
1913
1914
1915//===----------------------------------------------------------------------===//
1916// Iteration Count Computation Code
1917//
1918
1919/// getIterationCount - If the specified loop has a predictable iteration
1920/// count, return it. Note that it is not valid to call this method on a
1921/// loop without a loop-invariant iteration count.
1922SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1923 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1924 if (I == IterationCounts.end()) {
1925 SCEVHandle ItCount = ComputeIterationCount(L);
1926 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1927 if (ItCount != UnknownValue) {
1928 assert(ItCount->isLoopInvariant(L) &&
1929 "Computed trip count isn't loop invariant for loop!");
1930 ++NumTripCountsComputed;
1931 } else if (isa<PHINode>(L->getHeader()->begin())) {
1932 // Only count loops that have phi nodes as not being computable.
1933 ++NumTripCountsNotComputed;
1934 }
1935 }
1936 return I->second;
1937}
1938
Dan Gohman60f8a632009-02-17 20:49:49 +00001939/// forgetLoopIterationCount - This method should be called by the
1940/// client when it has changed a loop in a way that may effect
1941/// ScalarEvolution's ability to compute a trip count.
1942void ScalarEvolutionsImpl::forgetLoopIterationCount(const Loop *L) {
1943 IterationCounts.erase(L);
1944}
1945
Chris Lattner53e677a2004-04-02 20:23:17 +00001946/// ComputeIterationCount - Compute the number of times the specified loop
1947/// will iterate.
1948SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1949 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patelb7211a22007-08-21 00:31:24 +00001950 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001951 L->getExitBlocks(ExitBlocks);
1952 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001953
1954 // Okay, there is one exit block. Try to find the condition that causes the
1955 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001956 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001957
1958 BasicBlock *ExitingBlock = 0;
1959 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1960 PI != E; ++PI)
1961 if (L->contains(*PI)) {
1962 if (ExitingBlock == 0)
1963 ExitingBlock = *PI;
1964 else
1965 return UnknownValue; // More than one block exiting!
1966 }
1967 assert(ExitingBlock && "No exits from loop, something is broken!");
1968
1969 // Okay, we've computed the exiting block. See what condition causes us to
1970 // exit.
1971 //
1972 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00001973 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1974 if (ExitBr == 0) return UnknownValue;
1975 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00001976
1977 // At this point, we know we have a conditional branch that determines whether
1978 // the loop is exited. However, we don't know if the branch is executed each
1979 // time through the loop. If not, then the execution count of the branch will
1980 // not be equal to the trip count of the loop.
1981 //
1982 // Currently we check for this by checking to see if the Exit branch goes to
1983 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00001984 // times as the loop. We also handle the case where the exit block *is* the
1985 // loop header. This is common for un-rotated loops. More extensive analysis
1986 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001987 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00001988 ExitBr->getSuccessor(1) != L->getHeader() &&
1989 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00001990 return UnknownValue;
1991
Reid Spencere4d87aa2006-12-23 06:05:41 +00001992 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1993
Nick Lewycky3b711652008-02-21 08:34:02 +00001994 // If it's not an integer comparison then compute it the hard way.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001995 // Note that ICmpInst deals with pointer comparisons too so we must check
1996 // the type of the operand.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001997 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Chris Lattner7980fb92004-04-17 18:36:24 +00001998 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1999 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00002000
Reid Spencere4d87aa2006-12-23 06:05:41 +00002001 // If the condition was exit on true, convert the condition to exit on false
2002 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00002003 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00002004 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002005 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00002006 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002007
2008 // Handle common loops like: for (X = "string"; *X; ++X)
2009 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2010 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2011 SCEVHandle ItCnt =
2012 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
2013 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2014 }
2015
Chris Lattner53e677a2004-04-02 20:23:17 +00002016 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2017 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2018
2019 // Try to evaluate any dependencies out of the loop.
2020 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2021 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2022 Tmp = getSCEVAtScope(RHS, L);
2023 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2024
Reid Spencere4d87aa2006-12-23 06:05:41 +00002025 // At this point, we would like to compute how many iterations of the
2026 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00002027 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2028 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00002029 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002030 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00002031 }
2032
2033 // FIXME: think about handling pointer comparisons! i.e.:
2034 // while (P != P+100) ++P;
2035
2036 // If we have a comparison of a chrec against a constant, try to use value
2037 // ranges to answer this query.
2038 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2039 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2040 if (AddRec->getLoop() == L) {
2041 // Form the comparison range using the constant of the correct type so
2042 // that the ConstantRange class knows to do a signed or unsigned
2043 // comparison.
2044 ConstantInt *CompVal = RHSC->getValue();
2045 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00002046 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00002047 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00002048 if (CompVal) {
2049 // Form the constant range.
Reid Spencerc6aedf72007-02-28 22:03:51 +00002050 ConstantRange CompRange(
2051 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002052
Dan Gohman246b2562007-10-22 18:31:58 +00002053 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002054 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2055 }
2056 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002057
Chris Lattner53e677a2004-04-02 20:23:17 +00002058 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002059 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00002060 // Convert to: while (X-Y != 0)
Dan Gohman246b2562007-10-22 18:31:58 +00002061 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002062 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002063 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002064 }
2065 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00002066 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman246b2562007-10-22 18:31:58 +00002067 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002068 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002069 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002070 }
2071 case ICmpInst::ICMP_SLT: {
Nick Lewycky789558d2009-01-13 09:18:58 +00002072 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002073 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002074 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002075 }
2076 case ICmpInst::ICMP_SGT: {
Eli Friedman068acc32008-07-30 00:04:08 +00002077 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky789558d2009-01-13 09:18:58 +00002078 SE.getNotSCEV(RHS), L, true);
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002079 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2080 break;
2081 }
2082 case ICmpInst::ICMP_ULT: {
Nick Lewycky789558d2009-01-13 09:18:58 +00002083 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002084 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2085 break;
2086 }
2087 case ICmpInst::ICMP_UGT: {
Dale Johannesena0c8fc62008-04-20 16:58:57 +00002088 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky789558d2009-01-13 09:18:58 +00002089 SE.getNotSCEV(RHS), L, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002090 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002091 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002092 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002093 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002094#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002095 cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002096 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendlinge8156192006-12-07 01:30:32 +00002097 cerr << "[unsigned] ";
2098 cerr << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00002099 << Instruction::getOpcodeName(Instruction::ICmp)
2100 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002101#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00002102 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002103 }
Chris Lattner7980fb92004-04-17 18:36:24 +00002104 return ComputeIterationCountExhaustively(L, ExitCond,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002105 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00002106}
2107
Chris Lattner673e02b2004-10-12 01:49:27 +00002108static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00002109EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2110 ScalarEvolution &SE) {
2111 SCEVHandle InVal = SE.getConstant(C);
2112 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002113 assert(isa<SCEVConstant>(Val) &&
2114 "Evaluation of SCEV at constant didn't fold correctly?");
2115 return cast<SCEVConstant>(Val)->getValue();
2116}
2117
2118/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2119/// and a GEP expression (missing the pointer index) indexing into it, return
2120/// the addressed element of the initializer or null if the index expression is
2121/// invalid.
2122static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002123GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00002124 const std::vector<ConstantInt*> &Indices) {
2125 Constant *Init = GV->getInitializer();
2126 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002127 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00002128 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2129 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2130 Init = cast<Constant>(CS->getOperand(Idx));
2131 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2132 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2133 Init = cast<Constant>(CA->getOperand(Idx));
2134 } else if (isa<ConstantAggregateZero>(Init)) {
2135 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2136 assert(Idx < STy->getNumElements() && "Bad struct index!");
2137 Init = Constant::getNullValue(STy->getElementType(Idx));
2138 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2139 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2140 Init = Constant::getNullValue(ATy->getElementType());
2141 } else {
2142 assert(0 && "Unknown constant aggregate type!");
2143 }
2144 return 0;
2145 } else {
2146 return 0; // Unknown initializer type
2147 }
2148 }
2149 return Init;
2150}
2151
2152/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky08de6132008-05-06 04:03:18 +00002153/// 'icmp op load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00002154SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002155ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002156 const Loop *L,
2157 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002158 if (LI->isVolatile()) return UnknownValue;
2159
2160 // Check to see if the loaded pointer is a getelementptr of a global.
2161 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2162 if (!GEP) return UnknownValue;
2163
2164 // Make sure that it is really a constant global we are gepping, with an
2165 // initializer, and make sure the first IDX is really 0.
2166 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2167 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2168 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2169 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2170 return UnknownValue;
2171
2172 // Okay, we allow one non-constant index into the GEP instruction.
2173 Value *VarIdx = 0;
2174 std::vector<ConstantInt*> Indexes;
2175 unsigned VarIdxNum = 0;
2176 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2177 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2178 Indexes.push_back(CI);
2179 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2180 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2181 VarIdx = GEP->getOperand(i);
2182 VarIdxNum = i-2;
2183 Indexes.push_back(0);
2184 }
2185
2186 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2187 // Check to see if X is a loop variant variable value now.
2188 SCEVHandle Idx = getSCEV(VarIdx);
2189 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2190 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2191
2192 // We can only recognize very limited forms of loop index expressions, in
2193 // particular, only affine AddRec's like {C1,+,C2}.
2194 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2195 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2196 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2197 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2198 return UnknownValue;
2199
2200 unsigned MaxSteps = MaxBruteForceIterations;
2201 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002202 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00002203 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohman246b2562007-10-22 18:31:58 +00002204 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002205
2206 // Form the GEP offset.
2207 Indexes[VarIdxNum] = Val;
2208
2209 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2210 if (Result == 0) break; // Cannot compute!
2211
2212 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002213 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002214 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00002215 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002216#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002217 cerr << "\n***\n*** Computed loop count " << *ItCst
2218 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2219 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00002220#endif
2221 ++NumArrayLenItCounts;
Dan Gohman246b2562007-10-22 18:31:58 +00002222 return SE.getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00002223 }
2224 }
2225 return UnknownValue;
2226}
2227
2228
Chris Lattner3221ad02004-04-17 22:58:41 +00002229/// CanConstantFold - Return true if we can constant fold an instruction of the
2230/// specified type, assuming that all operands were constants.
2231static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00002232 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00002233 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2234 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002235
Chris Lattner3221ad02004-04-17 22:58:41 +00002236 if (const CallInst *CI = dyn_cast<CallInst>(I))
2237 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00002238 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00002239 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00002240}
2241
Chris Lattner3221ad02004-04-17 22:58:41 +00002242/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2243/// in the loop that V is derived from. We allow arbitrary operations along the
2244/// way, but the operands of an operation must either be constants or a value
2245/// derived from a constant PHI. If this expression does not fit with these
2246/// constraints, return null.
2247static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2248 // If this is not an instruction, or if this is an instruction outside of the
2249 // loop, it can't be derived from a loop PHI.
2250 Instruction *I = dyn_cast<Instruction>(V);
2251 if (I == 0 || !L->contains(I->getParent())) return 0;
2252
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002253 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002254 if (L->getHeader() == I->getParent())
2255 return PN;
2256 else
2257 // We don't currently keep track of the control flow needed to evaluate
2258 // PHIs, so we cannot handle PHIs inside of loops.
2259 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002260 }
Chris Lattner3221ad02004-04-17 22:58:41 +00002261
2262 // If we won't be able to constant fold this expression even if the operands
2263 // are constants, return early.
2264 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002265
Chris Lattner3221ad02004-04-17 22:58:41 +00002266 // Otherwise, we can evaluate this instruction if all of its operands are
2267 // constant or derived from a PHI node themselves.
2268 PHINode *PHI = 0;
2269 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2270 if (!(isa<Constant>(I->getOperand(Op)) ||
2271 isa<GlobalValue>(I->getOperand(Op)))) {
2272 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2273 if (P == 0) return 0; // Not evolving from PHI
2274 if (PHI == 0)
2275 PHI = P;
2276 else if (PHI != P)
2277 return 0; // Evolving from multiple different PHIs.
2278 }
2279
2280 // This is a expression evolving from a constant PHI!
2281 return PHI;
2282}
2283
2284/// EvaluateExpression - Given an expression that passes the
2285/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2286/// in the loop has the value PHIVal. If we can't fold this expression for some
2287/// reason, return null.
2288static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2289 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00002290 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00002291 Instruction *I = cast<Instruction>(V);
2292
2293 std::vector<Constant*> Operands;
2294 Operands.resize(I->getNumOperands());
2295
2296 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2297 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2298 if (Operands[i] == 0) return 0;
2299 }
2300
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002301 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2302 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2303 &Operands[0], Operands.size());
2304 else
2305 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2306 &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00002307}
2308
2309/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2310/// in the header of its containing loop, we know the loop executes a
2311/// constant number of times, and the PHI node is just a recurrence
2312/// involving constants, fold it.
2313Constant *ScalarEvolutionsImpl::
Reid Spencere8019bb2007-03-01 07:25:48 +00002314getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00002315 std::map<PHINode*, Constant*>::iterator I =
2316 ConstantEvolutionLoopExitValue.find(PN);
2317 if (I != ConstantEvolutionLoopExitValue.end())
2318 return I->second;
2319
Reid Spencere8019bb2007-03-01 07:25:48 +00002320 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00002321 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2322
2323 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2324
2325 // Since the loop is canonicalized, the PHI node must have two entries. One
2326 // entry must be a constant (coming in from outside of the loop), and the
2327 // second must be derived from the same PHI.
2328 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2329 Constant *StartCST =
2330 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2331 if (StartCST == 0)
2332 return RetVal = 0; // Must be a constant.
2333
2334 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2335 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2336 if (PN2 != PN)
2337 return RetVal = 0; // Not derived from same PHI.
2338
2339 // Execute the loop symbolically to determine the exit value.
Reid Spencere8019bb2007-03-01 07:25:48 +00002340 if (Its.getActiveBits() >= 32)
2341 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00002342
Reid Spencere8019bb2007-03-01 07:25:48 +00002343 unsigned NumIterations = Its.getZExtValue(); // must be in range
2344 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00002345 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2346 if (IterationNum == NumIterations)
2347 return RetVal = PHIVal; // Got exit value!
2348
2349 // Compute the value of the PHI node for the next iteration.
2350 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2351 if (NextPHI == PHIVal)
2352 return RetVal = NextPHI; // Stopped evolving!
2353 if (NextPHI == 0)
2354 return 0; // Couldn't evaluate!
2355 PHIVal = NextPHI;
2356 }
2357}
2358
Chris Lattner7980fb92004-04-17 18:36:24 +00002359/// ComputeIterationCountExhaustively - If the trip is known to execute a
2360/// constant number of times (the condition evolves only from constants),
2361/// try to evaluate a few iterations of the loop until we get the exit
2362/// condition gets a value of ExitWhen (true or false). If we cannot
2363/// evaluate the trip count of the loop, return UnknownValue.
2364SCEVHandle ScalarEvolutionsImpl::
2365ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2366 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2367 if (PN == 0) return UnknownValue;
2368
2369 // Since the loop is canonicalized, the PHI node must have two entries. One
2370 // entry must be a constant (coming in from outside of the loop), and the
2371 // second must be derived from the same PHI.
2372 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2373 Constant *StartCST =
2374 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2375 if (StartCST == 0) return UnknownValue; // Must be a constant.
2376
2377 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2378 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2379 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2380
2381 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2382 // the loop symbolically to determine when the condition gets a value of
2383 // "ExitWhen".
2384 unsigned IterationNum = 0;
2385 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2386 for (Constant *PHIVal = StartCST;
2387 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002388 ConstantInt *CondVal =
2389 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00002390
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002391 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00002392 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002393
Reid Spencere8019bb2007-03-01 07:25:48 +00002394 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002395 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00002396 ++NumBruteForceTripCountsComputed;
Dan Gohman246b2562007-10-22 18:31:58 +00002397 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00002398 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002399
Chris Lattner3221ad02004-04-17 22:58:41 +00002400 // Compute the value of the PHI node for the next iteration.
2401 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2402 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00002403 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00002404 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00002405 }
2406
2407 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00002408 return UnknownValue;
2409}
2410
2411/// getSCEVAtScope - Compute the value of the specified expression within the
2412/// indicated loop (which may be null to indicate in no loop). If the
2413/// expression cannot be evaluated, return UnknownValue.
2414SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2415 // FIXME: this should be turned into a virtual method on SCEV!
2416
Chris Lattner3221ad02004-04-17 22:58:41 +00002417 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002418
Nick Lewycky3e630762008-02-20 06:48:22 +00002419 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00002420 // exit value from the loop without using SCEVs.
2421 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2422 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2423 const Loop *LI = this->LI[I->getParent()];
2424 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2425 if (PHINode *PN = dyn_cast<PHINode>(I))
2426 if (PN->getParent() == LI->getHeader()) {
2427 // Okay, there is no closed form solution for the PHI node. Check
2428 // to see if the loop that contains it has a known iteration count.
2429 // If so, we may be able to force computation of the exit value.
2430 SCEVHandle IterationCount = getIterationCount(LI);
2431 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2432 // Okay, we know how many times the containing loop executes. If
2433 // this is a constant evolving PHI node, get the final value at
2434 // the specified iteration number.
2435 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencere8019bb2007-03-01 07:25:48 +00002436 ICC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00002437 LI);
Dan Gohman246b2562007-10-22 18:31:58 +00002438 if (RV) return SE.getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00002439 }
2440 }
2441
Reid Spencer09906f32006-12-04 21:33:23 +00002442 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00002443 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00002444 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00002445 // result. This is particularly useful for computing loop exit values.
2446 if (CanConstantFold(I)) {
2447 std::vector<Constant*> Operands;
2448 Operands.reserve(I->getNumOperands());
2449 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2450 Value *Op = I->getOperand(i);
2451 if (Constant *C = dyn_cast<Constant>(Op)) {
2452 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002453 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00002454 // If any of the operands is non-constant and if they are
2455 // non-integer, don't even try to analyze them with scev techniques.
2456 if (!isa<IntegerType>(Op->getType()))
2457 return V;
2458
Chris Lattner3221ad02004-04-17 22:58:41 +00002459 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2460 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
Reid Spencerd977d862006-12-12 23:36:14 +00002461 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2462 Op->getType(),
2463 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002464 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2465 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
Reid Spencerd977d862006-12-12 23:36:14 +00002466 Operands.push_back(ConstantExpr::getIntegerCast(C,
2467 Op->getType(),
2468 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002469 else
2470 return V;
2471 } else {
2472 return V;
2473 }
2474 }
2475 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002476
2477 Constant *C;
2478 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2479 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2480 &Operands[0], Operands.size());
2481 else
2482 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2483 &Operands[0], Operands.size());
Dan Gohman246b2562007-10-22 18:31:58 +00002484 return SE.getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002485 }
2486 }
2487
2488 // This is some other type of SCEVUnknown, just return it.
2489 return V;
2490 }
2491
Chris Lattner53e677a2004-04-02 20:23:17 +00002492 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2493 // Avoid performing the look-up in the common case where the specified
2494 // expression has no loop-variant portions.
2495 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2496 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2497 if (OpAtScope != Comm->getOperand(i)) {
2498 if (OpAtScope == UnknownValue) return UnknownValue;
2499 // Okay, at least one of these operands is loop variant but might be
2500 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002501 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002502 NewOps.push_back(OpAtScope);
2503
2504 for (++i; i != e; ++i) {
2505 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2506 if (OpAtScope == UnknownValue) return UnknownValue;
2507 NewOps.push_back(OpAtScope);
2508 }
2509 if (isa<SCEVAddExpr>(Comm))
Dan Gohman246b2562007-10-22 18:31:58 +00002510 return SE.getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002511 if (isa<SCEVMulExpr>(Comm))
2512 return SE.getMulExpr(NewOps);
2513 if (isa<SCEVSMaxExpr>(Comm))
2514 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00002515 if (isa<SCEVUMaxExpr>(Comm))
2516 return SE.getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002517 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002518 }
2519 }
2520 // If we got here, all operands are loop invariant.
2521 return Comm;
2522 }
2523
Nick Lewycky789558d2009-01-13 09:18:58 +00002524 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2525 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002526 if (LHS == UnknownValue) return LHS;
Nick Lewycky789558d2009-01-13 09:18:58 +00002527 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002528 if (RHS == UnknownValue) return RHS;
Nick Lewycky789558d2009-01-13 09:18:58 +00002529 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2530 return Div; // must be loop invariant
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00002531 return SE.getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002532 }
2533
2534 // If this is a loop recurrence for a loop that does not contain L, then we
2535 // are dealing with the final value computed by the loop.
2536 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2537 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2538 // To evaluate this recurrence, we need to know how many times the AddRec
2539 // loop iterates. Compute this now.
2540 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2541 if (IterationCount == UnknownValue) return UnknownValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002542
Eli Friedmanb42a6262008-08-04 23:49:06 +00002543 // Then, evaluate the AddRec.
Dan Gohman246b2562007-10-22 18:31:58 +00002544 return AddRec->evaluateAtIteration(IterationCount, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002545 }
2546 return UnknownValue;
2547 }
2548
2549 //assert(0 && "Unknown SCEV type!");
2550 return UnknownValue;
2551}
2552
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002553/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2554/// following equation:
2555///
2556/// A * X = B (mod N)
2557///
2558/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2559/// A and B isn't important.
2560///
2561/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2562static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2563 ScalarEvolution &SE) {
2564 uint32_t BW = A.getBitWidth();
2565 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2566 assert(A != 0 && "A must be non-zero.");
2567
2568 // 1. D = gcd(A, N)
2569 //
2570 // The gcd of A and N may have only one prime factor: 2. The number of
2571 // trailing zeros in A is its multiplicity
2572 uint32_t Mult2 = A.countTrailingZeros();
2573 // D = 2^Mult2
2574
2575 // 2. Check if B is divisible by D.
2576 //
2577 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2578 // is not less than multiplicity of this prime factor for D.
2579 if (B.countTrailingZeros() < Mult2)
2580 return new SCEVCouldNotCompute();
2581
2582 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2583 // modulo (N / D).
2584 //
2585 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2586 // bit width during computations.
2587 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2588 APInt Mod(BW + 1, 0);
2589 Mod.set(BW - Mult2); // Mod = N / D
2590 APInt I = AD.multiplicativeInverse(Mod);
2591
2592 // 4. Compute the minimum unsigned root of the equation:
2593 // I * (B / D) mod (N / D)
2594 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2595
2596 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2597 // bits.
2598 return SE.getConstant(Result.trunc(BW));
2599}
Chris Lattner53e677a2004-04-02 20:23:17 +00002600
2601/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2602/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2603/// might be the same) or two SCEVCouldNotCompute objects.
2604///
2605static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman246b2562007-10-22 18:31:58 +00002606SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002607 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Reid Spencere8019bb2007-03-01 07:25:48 +00002608 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2609 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2610 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002611
Chris Lattner53e677a2004-04-02 20:23:17 +00002612 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00002613 if (!LC || !MC || !NC) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002614 SCEV *CNC = new SCEVCouldNotCompute();
2615 return std::make_pair(CNC, CNC);
2616 }
2617
Reid Spencere8019bb2007-03-01 07:25:48 +00002618 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00002619 const APInt &L = LC->getValue()->getValue();
2620 const APInt &M = MC->getValue()->getValue();
2621 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00002622 APInt Two(BitWidth, 2);
2623 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002624
Reid Spencere8019bb2007-03-01 07:25:48 +00002625 {
2626 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00002627 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00002628 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2629 // The B coefficient is M-N/2
2630 APInt B(M);
2631 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002632
Reid Spencere8019bb2007-03-01 07:25:48 +00002633 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00002634 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00002635
Reid Spencere8019bb2007-03-01 07:25:48 +00002636 // Compute the B^2-4ac term.
2637 APInt SqrtTerm(B);
2638 SqrtTerm *= B;
2639 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00002640
Reid Spencere8019bb2007-03-01 07:25:48 +00002641 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2642 // integer value or else APInt::sqrt() will assert.
2643 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002644
Reid Spencere8019bb2007-03-01 07:25:48 +00002645 // Compute the two solutions for the quadratic formula.
2646 // The divisions must be performed as signed divisions.
2647 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00002648 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00002649 if (TwoA.isMinValue()) {
2650 SCEV *CNC = new SCEVCouldNotCompute();
2651 return std::make_pair(CNC, CNC);
2652 }
2653
Reid Spencere8019bb2007-03-01 07:25:48 +00002654 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2655 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002656
Dan Gohman246b2562007-10-22 18:31:58 +00002657 return std::make_pair(SE.getConstant(Solution1),
2658 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00002659 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00002660}
2661
2662/// HowFarToZero - Return the number of times a backedge comparing the specified
2663/// value to zero will execute. If not computable, return UnknownValue
2664SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2665 // If the value is a constant
2666 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2667 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00002668 if (C->getValue()->isZero()) return C;
Chris Lattner53e677a2004-04-02 20:23:17 +00002669 return UnknownValue; // Otherwise it will loop infinitely.
2670 }
2671
2672 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2673 if (!AddRec || AddRec->getLoop() != L)
2674 return UnknownValue;
2675
2676 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002677 // If this is an affine expression, the execution count of this branch is
2678 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00002679 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002680 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00002681 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002682 // equivalent to:
2683 //
2684 // Step*N = -Start (mod 2^BW)
2685 //
2686 // where BW is the common bit width of Start and Step.
2687
Chris Lattner53e677a2004-04-02 20:23:17 +00002688 // Get the initial value for the loop.
2689 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002690 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002691
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002692 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002693
Chris Lattner53e677a2004-04-02 20:23:17 +00002694 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002695 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00002696
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002697 // First, handle unitary steps.
2698 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2699 return SE.getNegativeSCEV(Start); // N = -Start (as unsigned)
2700 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2701 return Start; // N = Start (as unsigned)
2702
2703 // Then, try to solve the above equation provided that Start is constant.
2704 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2705 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2706 -StartC->getValue()->getValue(),SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002707 }
Chris Lattner42a75512007-01-15 02:27:26 +00002708 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002709 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2710 // the quadratic equation to solve it.
Dan Gohman246b2562007-10-22 18:31:58 +00002711 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002712 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2713 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2714 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002715#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002716 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2717 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002718#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002719 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002720 if (ConstantInt *CB =
2721 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002722 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002723 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002724 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002725
Chris Lattner53e677a2004-04-02 20:23:17 +00002726 // We can only use this value if the chrec ends up with an exact zero
2727 // value at this index. When solving for "X*X != 5", for example, we
2728 // should not accept a root of 2.
Dan Gohman246b2562007-10-22 18:31:58 +00002729 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002730 if (Val->isZero())
2731 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00002732 }
2733 }
2734 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002735
Chris Lattner53e677a2004-04-02 20:23:17 +00002736 return UnknownValue;
2737}
2738
2739/// HowFarToNonZero - Return the number of times a backedge checking the
2740/// specified value for nonzero will execute. If not computable, return
2741/// UnknownValue
2742SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2743 // Loops that look like: while (X == 0) are very strange indeed. We don't
2744 // handle them yet except for the trivial case. This could be expanded in the
2745 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002746
Chris Lattner53e677a2004-04-02 20:23:17 +00002747 // If the value is a constant, check to see if it is known to be non-zero
2748 // already. If so, the backedge will execute zero times.
2749 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00002750 if (!C->getValue()->isNullValue())
2751 return SE.getIntegerSCEV(0, C->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002752 return UnknownValue; // Otherwise it will loop infinitely.
2753 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002754
Chris Lattner53e677a2004-04-02 20:23:17 +00002755 // We could implement others, but I really doubt anyone writes loops like
2756 // this, and if they did, they would already be constant folded.
2757 return UnknownValue;
2758}
2759
Dan Gohmanfd6edef2008-09-15 22:18:04 +00002760/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2761/// (which may not be an immediate predecessor) which has exactly one
2762/// successor from which BB is reachable, or null if no such block is
2763/// found.
2764///
2765BasicBlock *
2766ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2767 // If the block has a unique predecessor, the predecessor must have
2768 // no other successors from which BB is reachable.
2769 if (BasicBlock *Pred = BB->getSinglePredecessor())
2770 return Pred;
2771
2772 // A loop's header is defined to be a block that dominates the loop.
2773 // If the loop has a preheader, it must be a block that has exactly
2774 // one successor that can reach BB. This is slightly more strict
2775 // than necessary, but works if critical edges are split.
2776 if (Loop *L = LI.getLoopFor(BB))
2777 return L->getLoopPreheader();
2778
2779 return 0;
2780}
2781
Dan Gohmanc2390b12009-02-12 22:19:27 +00002782/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Nick Lewycky59cff122008-07-12 07:41:32 +00002783/// a conditional between LHS and RHS.
Dan Gohmanc2390b12009-02-12 22:19:27 +00002784bool ScalarEvolutionsImpl::isLoopGuardedByCond(const Loop *L,
2785 ICmpInst::Predicate Pred,
Nick Lewycky59cff122008-07-12 07:41:32 +00002786 SCEV *LHS, SCEV *RHS) {
2787 BasicBlock *Preheader = L->getLoopPreheader();
2788 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00002789
Dan Gohman38372182008-08-12 20:17:31 +00002790 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohmanfd6edef2008-09-15 22:18:04 +00002791 // there are predecessors that can be found that have unique successors
2792 // leading to the original header.
2793 for (; Preheader;
2794 PreheaderDest = Preheader,
2795 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohman38372182008-08-12 20:17:31 +00002796
2797 BranchInst *LoopEntryPredicate =
Nick Lewycky59cff122008-07-12 07:41:32 +00002798 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00002799 if (!LoopEntryPredicate ||
2800 LoopEntryPredicate->isUnconditional())
2801 continue;
2802
2803 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2804 if (!ICI) continue;
2805
2806 // Now that we found a conditional branch that dominates the loop, check to
2807 // see if it is the comparison we are looking for.
2808 Value *PreCondLHS = ICI->getOperand(0);
2809 Value *PreCondRHS = ICI->getOperand(1);
2810 ICmpInst::Predicate Cond;
2811 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2812 Cond = ICI->getPredicate();
2813 else
2814 Cond = ICI->getInversePredicate();
2815
Dan Gohmanc2390b12009-02-12 22:19:27 +00002816 if (Cond == Pred)
2817 ; // An exact match.
2818 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
2819 ; // The actual condition is beyond sufficient.
2820 else
2821 // Check a few special cases.
2822 switch (Cond) {
2823 case ICmpInst::ICMP_UGT:
2824 if (Pred == ICmpInst::ICMP_ULT) {
2825 std::swap(PreCondLHS, PreCondRHS);
2826 Cond = ICmpInst::ICMP_ULT;
2827 break;
2828 }
2829 continue;
2830 case ICmpInst::ICMP_SGT:
2831 if (Pred == ICmpInst::ICMP_SLT) {
2832 std::swap(PreCondLHS, PreCondRHS);
2833 Cond = ICmpInst::ICMP_SLT;
2834 break;
2835 }
2836 continue;
2837 case ICmpInst::ICMP_NE:
2838 // Expressions like (x >u 0) are often canonicalized to (x != 0),
2839 // so check for this case by checking if the NE is comparing against
2840 // a minimum or maximum constant.
2841 if (!ICmpInst::isTrueWhenEqual(Pred))
2842 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
2843 const APInt &A = CI->getValue();
2844 switch (Pred) {
2845 case ICmpInst::ICMP_SLT:
2846 if (A.isMaxSignedValue()) break;
2847 continue;
2848 case ICmpInst::ICMP_SGT:
2849 if (A.isMinSignedValue()) break;
2850 continue;
2851 case ICmpInst::ICMP_ULT:
2852 if (A.isMaxValue()) break;
2853 continue;
2854 case ICmpInst::ICMP_UGT:
2855 if (A.isMinValue()) break;
2856 continue;
2857 default:
2858 continue;
2859 }
2860 Cond = ICmpInst::ICMP_NE;
2861 // NE is symmetric but the original comparison may not be. Swap
2862 // the operands if necessary so that they match below.
2863 if (isa<SCEVConstant>(LHS))
2864 std::swap(PreCondLHS, PreCondRHS);
2865 break;
2866 }
2867 continue;
2868 default:
2869 // We weren't able to reconcile the condition.
2870 continue;
2871 }
Dan Gohman38372182008-08-12 20:17:31 +00002872
2873 if (!PreCondLHS->getType()->isInteger()) continue;
2874
2875 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
2876 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
2877 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
2878 (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
2879 RHS == SE.getNotSCEV(PreCondLHSSCEV)))
2880 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00002881 }
2882
Dan Gohman38372182008-08-12 20:17:31 +00002883 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00002884}
2885
Chris Lattnerdb25de42005-08-15 23:33:51 +00002886/// HowManyLessThans - Return the number of times a backedge containing the
2887/// specified less-than comparison will execute. If not computable, return
2888/// UnknownValue.
2889SCEVHandle ScalarEvolutionsImpl::
Nick Lewycky789558d2009-01-13 09:18:58 +00002890HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00002891 // Only handle: "ADDREC < LoopInvariant".
2892 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2893
2894 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2895 if (!AddRec || AddRec->getLoop() != L)
2896 return UnknownValue;
2897
2898 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00002899 // FORNOW: We only support unit strides.
2900 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
2901 if (AddRec->getOperand(1) != One)
Chris Lattnerdb25de42005-08-15 23:33:51 +00002902 return UnknownValue;
2903
Nick Lewycky789558d2009-01-13 09:18:58 +00002904 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
2905 // m. So, we count the number of iterations in which {n,+,1} < m is true.
2906 // Note that we cannot simply return max(m-n,0) because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00002907 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00002908
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002909 // First, we get the value of the LHS in the first iteration: n
2910 SCEVHandle Start = AddRec->getOperand(0);
2911
Dan Gohmanc2390b12009-02-12 22:19:27 +00002912 if (isLoopGuardedByCond(L,
2913 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Nick Lewycky789558d2009-01-13 09:18:58 +00002914 SE.getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
2915 // Since we know that the condition is true in order to enter the loop,
2916 // we know that it will run exactly m-n times.
2917 return SE.getMinusSCEV(RHS, Start);
2918 } else {
2919 // Then, we get the value of the LHS in the first iteration in which the
2920 // above condition doesn't hold. This equals to max(m,n).
2921 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
2922 : SE.getUMaxExpr(RHS, Start);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002923
Nick Lewycky789558d2009-01-13 09:18:58 +00002924 // Finally, we subtract these two values to get the number of times the
2925 // backedge is executed: max(m,n)-n.
2926 return SE.getMinusSCEV(End, Start);
Nick Lewycky1447f5c2008-12-16 08:30:01 +00002927 }
Chris Lattnerdb25de42005-08-15 23:33:51 +00002928 }
2929
2930 return UnknownValue;
2931}
2932
Chris Lattner53e677a2004-04-02 20:23:17 +00002933/// getNumIterationsInRange - Return the number of iterations of this loop that
2934/// produce values in the specified constant range. Another way of looking at
2935/// this is that it returns the first iteration number where the value is not in
2936/// the condition, thus computing the exit count. If the iteration count can't
2937/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman246b2562007-10-22 18:31:58 +00002938SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2939 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002940 if (Range.isFullSet()) // Infinite loop.
2941 return new SCEVCouldNotCompute();
2942
2943 // If the start is a non-zero constant, shift the range to simplify things.
2944 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00002945 if (!SC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002946 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00002947 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2948 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002949 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2950 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00002951 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002952 // This is strange and shouldn't happen.
2953 return new SCEVCouldNotCompute();
2954 }
2955
2956 // The only time we can solve this is when we have all constant indices.
2957 // Otherwise, we cannot determine the overflow conditions.
2958 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2959 if (!isa<SCEVConstant>(getOperand(i)))
2960 return new SCEVCouldNotCompute();
2961
2962
2963 // Okay at this point we know that all elements of the chrec are constants and
2964 // that the start element is zero.
2965
2966 // First check to see if the range contains zero. If not, the first
2967 // iteration exits.
Reid Spencera6e8a952007-03-01 07:54:15 +00002968 if (!Range.contains(APInt(getBitWidth(),0)))
Dan Gohman246b2562007-10-22 18:31:58 +00002969 return SE.getConstant(ConstantInt::get(getType(),0));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002970
Chris Lattner53e677a2004-04-02 20:23:17 +00002971 if (isAffine()) {
2972 // If this is an affine expression then we have this situation:
2973 // Solve {0,+,A} in Range === Ax in Range
2974
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002975 // We know that zero is in the range. If A is positive then we know that
2976 // the upper value of the range must be the first possible exit value.
2977 // If A is negative then the lower of the range is the last possible loop
2978 // value. Also note that we already checked for a full range.
Reid Spencer581b0d42007-02-28 19:57:34 +00002979 APInt One(getBitWidth(),1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002980 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2981 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00002982
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002983 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00002984 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00002985 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002986
2987 // Evaluate at the exit value. If we really did fall out of the valid
2988 // range, then we computed our trip count, otherwise wrap around or other
2989 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00002990 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002991 if (Range.contains(Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002992 return new SCEVCouldNotCompute(); // Something strange happened
2993
2994 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00002995 assert(Range.contains(
2996 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00002997 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002998 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00002999 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00003000 } else if (isQuadratic()) {
3001 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3002 // quadratic equation to solve it. To do this, we must frame our problem in
3003 // terms of figuring out when zero is crossed, instead of when
3004 // Range.getUpper() is crossed.
3005 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00003006 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3007 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003008
3009 // Next, solve the constructed addrec
3010 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00003011 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00003012 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3013 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3014 if (R1) {
3015 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003016 if (ConstantInt *CB =
3017 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003018 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00003019 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00003020 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003021
Chris Lattner53e677a2004-04-02 20:23:17 +00003022 // Make sure the root is not off by one. The returned iteration should
3023 // not be in the range, but the previous one should be. When solving
3024 // for "X*X < 5", for example, we should not return a root of 2.
3025 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003026 R1->getValue(),
3027 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003028 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003029 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00003030 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003031
Dan Gohman246b2562007-10-22 18:31:58 +00003032 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003033 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00003034 return SE.getConstant(NextVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00003035 return new SCEVCouldNotCompute(); // Something strange happened
3036 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003037
Chris Lattner53e677a2004-04-02 20:23:17 +00003038 // If R1 was not in the range, then it is a good return value. Make
3039 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00003040 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00003041 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003042 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00003043 return R1;
3044 return new SCEVCouldNotCompute(); // Something strange happened
3045 }
3046 }
3047 }
3048
Chris Lattner53e677a2004-04-02 20:23:17 +00003049 return new SCEVCouldNotCompute();
3050}
3051
3052
3053
3054//===----------------------------------------------------------------------===//
3055// ScalarEvolution Class Implementation
3056//===----------------------------------------------------------------------===//
3057
3058bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohman246b2562007-10-22 18:31:58 +00003059 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
Chris Lattner53e677a2004-04-02 20:23:17 +00003060 return false;
3061}
3062
3063void ScalarEvolution::releaseMemory() {
3064 delete (ScalarEvolutionsImpl*)Impl;
3065 Impl = 0;
3066}
3067
3068void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3069 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00003070 AU.addRequiredTransitive<LoopInfo>();
3071}
3072
3073SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
3074 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
3075}
3076
Chris Lattnera0740fb2005-08-09 23:36:33 +00003077/// hasSCEV - Return true if the SCEV for this value has already been
3078/// computed.
3079bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00003080 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00003081}
3082
3083
3084/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
3085/// the specified value.
3086void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
3087 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
3088}
3089
3090
Dan Gohmanc2390b12009-02-12 22:19:27 +00003091bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
3092 ICmpInst::Predicate Pred,
3093 SCEV *LHS, SCEV *RHS) {
3094 return ((ScalarEvolutionsImpl*)Impl)->isLoopGuardedByCond(L, Pred,
3095 LHS, RHS);
3096}
3097
Chris Lattner53e677a2004-04-02 20:23:17 +00003098SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
3099 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
3100}
3101
3102bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
3103 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
3104}
3105
Dan Gohman60f8a632009-02-17 20:49:49 +00003106void ScalarEvolution::forgetLoopIterationCount(const Loop *L) {
3107 return ((ScalarEvolutionsImpl*)Impl)->forgetLoopIterationCount(L);
3108}
3109
Chris Lattner53e677a2004-04-02 20:23:17 +00003110SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3111 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3112}
3113
Dan Gohman5cec4db2007-06-19 14:28:31 +00003114void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3115 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003116}
3117
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003118static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00003119 const Loop *L) {
3120 // Print all inner loops first
3121 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3122 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003123
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003124 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003125
Devang Patelb7211a22007-08-21 00:31:24 +00003126 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003127 L->getExitBlocks(ExitBlocks);
3128 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003129 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003130
3131 if (SE->hasLoopInvariantIterationCount(L)) {
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003132 OS << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003133 } else {
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003134 OS << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003135 }
3136
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003137 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00003138}
3139
Reid Spencerce9653c2004-12-07 04:03:45 +00003140void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00003141 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3142 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3143
3144 OS << "Classifying expressions for: " << F.getName() << "\n";
3145 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner42a75512007-01-15 02:27:26 +00003146 if (I->getType()->isInteger()) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00003147 OS << *I;
Dan Gohman8dae1382008-09-14 17:21:12 +00003148 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00003149 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00003150 SV->print(OS);
3151 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003152
Chris Lattner6ffe5512004-04-27 15:13:33 +00003153 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003154 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00003155 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003156 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3157 OS << "<<Unknown>>";
3158 } else {
3159 OS << *ExitValue;
3160 }
3161 }
3162
3163
3164 OS << "\n";
3165 }
3166
3167 OS << "Determining loop execution counts for: " << F.getName() << "\n";
3168 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3169 PrintLoopInfo(OS, this, *I);
3170}