blob: e00d1d9f80650b6b746886655dff3d31cdb5cc42 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
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.
31//
32// 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//
36// 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
62#define DEBUG_TYPE "scalar-evolution"
63#include "llvm/Analysis/ScalarEvolutionExpressions.h"
64#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
66#include "llvm/GlobalVariable.h"
67#include "llvm/Instructions.h"
68#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng98c073b2009-02-17 00:13:06 +000069#include "llvm/Analysis/Dominators.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070#include "llvm/Analysis/LoopInfo.h"
71#include "llvm/Assembly/Writer.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000072#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000073#include "llvm/Transforms/Scalar.h"
74#include "llvm/Support/CFG.h"
75#include "llvm/Support/CommandLine.h"
76#include "llvm/Support/Compiler.h"
77#include "llvm/Support/ConstantRange.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000078#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079#include "llvm/Support/InstIterator.h"
80#include "llvm/Support/ManagedStatic.h"
81#include "llvm/Support/MathExtras.h"
Dan Gohman13058cc2009-04-21 00:47:46 +000082#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083#include "llvm/ADT/Statistic.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000084#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085#include <ostream>
86#include <algorithm>
87#include <cmath>
88using namespace llvm;
89
Dan Gohmanf17a25c2007-07-18 16:29:46 +000090STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
98
Dan Gohman089efff2008-05-13 00:00:25 +000099static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000100MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
102 "symbolically execute a constant derived loop"),
103 cl::init(100));
104
Dan Gohman089efff2008-05-13 00:00:25 +0000105static RegisterPass<ScalarEvolution>
106R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107char ScalarEvolution::ID = 0;
108
109//===----------------------------------------------------------------------===//
110// SCEV class definitions
111//===----------------------------------------------------------------------===//
112
113//===----------------------------------------------------------------------===//
114// Implementation of the SCEV class.
115//
116SCEV::~SCEV() {}
117void SCEV::dump() const {
Dan Gohman13058cc2009-04-21 00:47:46 +0000118 print(errs());
119 errs() << '\n';
120}
121
122void SCEV::print(std::ostream &o) const {
123 raw_os_ostream OS(o);
124 print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125}
126
Dan Gohman7b560c42008-06-18 16:23:07 +0000127bool SCEV::isZero() const {
128 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
129 return SC->getValue()->isZero();
130 return false;
131}
132
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133
134SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
Dan Gohmanffd36ba2009-04-21 23:15:49 +0000135SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136
137bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
138 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
139 return false;
140}
141
142const Type *SCEVCouldNotCompute::getType() const {
143 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
144 return 0;
145}
146
147bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
148 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
149 return false;
150}
151
152SCEVHandle SCEVCouldNotCompute::
153replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000154 const SCEVHandle &Conc,
155 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156 return this;
157}
158
Dan Gohman13058cc2009-04-21 00:47:46 +0000159void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000160 OS << "***COULDNOTCOMPUTE***";
161}
162
163bool SCEVCouldNotCompute::classof(const SCEV *S) {
164 return S->getSCEVType() == scCouldNotCompute;
165}
166
167
168// SCEVConstants - Only allow the creation of one SCEVConstant for any
169// particular value. Don't use a SCEVHandle here, or else the object will
170// never be deleted!
171static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
172
173
174SCEVConstant::~SCEVConstant() {
175 SCEVConstants->erase(V);
176}
177
Dan Gohman89f85052007-10-22 18:31:58 +0000178SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 SCEVConstant *&R = (*SCEVConstants)[V];
180 if (R == 0) R = new SCEVConstant(V);
181 return R;
182}
183
Dan Gohman89f85052007-10-22 18:31:58 +0000184SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
185 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000186}
187
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188const Type *SCEVConstant::getType() const { return V->getType(); }
189
Dan Gohman13058cc2009-04-21 00:47:46 +0000190void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191 WriteAsOperand(OS, V, false);
192}
193
Dan Gohman2a381532009-04-21 01:25:57 +0000194SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
195 const SCEVHandle &op, const Type *ty)
196 : SCEV(SCEVTy), Op(op), Ty(ty) {}
197
198SCEVCastExpr::~SCEVCastExpr() {}
199
200bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
201 return Op->dominates(BB, DT);
202}
203
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
205// particular input. Don't use a SCEVHandle here, or else the object will
206// never be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000207static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000208 SCEVTruncateExpr*> > SCEVTruncates;
209
210SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000211 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000212 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
213 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215}
216
217SCEVTruncateExpr::~SCEVTruncateExpr() {
218 SCEVTruncates->erase(std::make_pair(Op, Ty));
219}
220
Dan Gohman13058cc2009-04-21 00:47:46 +0000221void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000222 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000223}
224
225// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
226// particular input. Don't use a SCEVHandle here, or else the object will never
227// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000228static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000229 SCEVZeroExtendExpr*> > SCEVZeroExtends;
230
231SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000232 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000233 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
234 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000235 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236}
237
238SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
239 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
240}
241
Dan Gohman13058cc2009-04-21 00:47:46 +0000242void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000243 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000244}
245
246// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
247// particular input. Don't use a SCEVHandle here, or else the object will never
248// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000249static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000250 SCEVSignExtendExpr*> > SCEVSignExtends;
251
252SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000253 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000254 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
255 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000256 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257}
258
259SCEVSignExtendExpr::~SCEVSignExtendExpr() {
260 SCEVSignExtends->erase(std::make_pair(Op, Ty));
261}
262
Dan Gohman13058cc2009-04-21 00:47:46 +0000263void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000264 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000265}
266
267// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
268// particular input. Don't use a SCEVHandle here, or else the object will never
269// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000270static ManagedStatic<std::map<std::pair<unsigned, std::vector<const SCEV*> >,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000271 SCEVCommutativeExpr*> > SCEVCommExprs;
272
273SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000274 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
275 SCEVCommExprs->erase(std::make_pair(getSCEVType(), SCEVOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276}
277
Dan Gohman13058cc2009-04-21 00:47:46 +0000278void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000279 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
280 const char *OpStr = getOperationStr();
281 OS << "(" << *Operands[0];
282 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
283 OS << OpStr << *Operands[i];
284 OS << ")";
285}
286
287SCEVHandle SCEVCommutativeExpr::
288replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000289 const SCEVHandle &Conc,
290 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000291 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000292 SCEVHandle H =
293 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294 if (H != getOperand(i)) {
295 std::vector<SCEVHandle> NewOps;
296 NewOps.reserve(getNumOperands());
297 for (unsigned j = 0; j != i; ++j)
298 NewOps.push_back(getOperand(j));
299 NewOps.push_back(H);
300 for (++i; i != e; ++i)
301 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000302 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000303
304 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000305 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000306 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000307 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000308 else if (isa<SCEVSMaxExpr>(this))
309 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000310 else if (isa<SCEVUMaxExpr>(this))
311 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312 else
313 assert(0 && "Unknown commutative expr!");
314 }
315 }
316 return this;
317}
318
Dan Gohman72a8a022009-05-07 14:00:19 +0000319bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng98c073b2009-02-17 00:13:06 +0000320 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
321 if (!getOperand(i)->dominates(BB, DT))
322 return false;
323 }
324 return true;
325}
326
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000327
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000328// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000329// input. Don't use a SCEVHandle here, or else the object will never be
330// deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000331static ManagedStatic<std::map<std::pair<const SCEV*, const SCEV*>,
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000332 SCEVUDivExpr*> > SCEVUDivs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000333
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000334SCEVUDivExpr::~SCEVUDivExpr() {
335 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336}
337
Evan Cheng98c073b2009-02-17 00:13:06 +0000338bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
339 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
340}
341
Dan Gohman13058cc2009-04-21 00:47:46 +0000342void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000343 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344}
345
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000346const Type *SCEVUDivExpr::getType() const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347 return LHS->getType();
348}
349
350// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
351// particular input. Don't use a SCEVHandle here, or else the object will never
352// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000353static ManagedStatic<std::map<std::pair<const Loop *,
354 std::vector<const SCEV*> >,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000355 SCEVAddRecExpr*> > SCEVAddRecExprs;
356
357SCEVAddRecExpr::~SCEVAddRecExpr() {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000358 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
359 SCEVAddRecExprs->erase(std::make_pair(L, SCEVOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000360}
361
362SCEVHandle SCEVAddRecExpr::
363replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000364 const SCEVHandle &Conc,
365 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000366 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000367 SCEVHandle H =
368 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000369 if (H != getOperand(i)) {
370 std::vector<SCEVHandle> NewOps;
371 NewOps.reserve(getNumOperands());
372 for (unsigned j = 0; j != i; ++j)
373 NewOps.push_back(getOperand(j));
374 NewOps.push_back(H);
375 for (++i; i != e; ++i)
376 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000377 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378
Dan Gohman89f85052007-10-22 18:31:58 +0000379 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000380 }
381 }
382 return this;
383}
384
385
386bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
387 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
388 // contain L and if the start is invariant.
389 return !QueryLoop->contains(L->getHeader()) &&
390 getOperand(0)->isLoopInvariant(QueryLoop);
391}
392
393
Dan Gohman13058cc2009-04-21 00:47:46 +0000394void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000395 OS << "{" << *Operands[0];
396 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
397 OS << ",+," << *Operands[i];
398 OS << "}<" << L->getHeader()->getName() + ">";
399}
400
401// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
402// value. Don't use a SCEVHandle here, or else the object will never be
403// deleted!
404static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
405
406SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
407
408bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
409 // All non-instruction values are loop invariant. All instructions are loop
410 // invariant if they are not contained in the specified loop.
411 if (Instruction *I = dyn_cast<Instruction>(V))
412 return !L->contains(I->getParent());
413 return true;
414}
415
Evan Cheng98c073b2009-02-17 00:13:06 +0000416bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
417 if (Instruction *I = dyn_cast<Instruction>(getValue()))
418 return DT->dominates(I->getParent(), BB);
419 return true;
420}
421
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000422const Type *SCEVUnknown::getType() const {
423 return V->getType();
424}
425
Dan Gohman13058cc2009-04-21 00:47:46 +0000426void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000427 WriteAsOperand(OS, V, false);
428}
429
430//===----------------------------------------------------------------------===//
431// SCEV Utilities
432//===----------------------------------------------------------------------===//
433
434namespace {
435 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
436 /// than the complexity of the RHS. This comparator is used to canonicalize
437 /// expressions.
438 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000439 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000440 return LHS->getSCEVType() < RHS->getSCEVType();
441 }
442 };
443}
444
445/// GroupByComplexity - Given a list of SCEV objects, order them by their
446/// complexity, and group objects of the same complexity together by value.
447/// When this routine is finished, we know that any duplicates in the vector are
448/// consecutive and that complexity is monotonically increasing.
449///
450/// Note that we go take special precautions to ensure that we get determinstic
451/// results from this routine. In other words, we don't want the results of
452/// this to depend on where the addresses of various SCEV objects happened to
453/// land in memory.
454///
455static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
456 if (Ops.size() < 2) return; // Noop
457 if (Ops.size() == 2) {
458 // This is the common case, which also happens to be trivially simple.
459 // Special case it.
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000460 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000461 std::swap(Ops[0], Ops[1]);
462 return;
463 }
464
465 // Do the rough sort by complexity.
Dan Gohman991acef2009-05-06 22:54:33 +0000466 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000467
468 // Now that we are sorted by complexity, group elements of the same
469 // complexity. Note that this is, at worst, N^2, but the vector is likely to
470 // be extremely short in practice. Note that we take this approach because we
471 // do not want to depend on the addresses of the objects we are grouping.
472 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000473 const SCEV *S = Ops[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000474 unsigned Complexity = S->getSCEVType();
475
476 // If there are any objects of the same complexity and same value as this
477 // one, group them.
478 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
479 if (Ops[j] == S) { // Found a duplicate.
480 // Move it to immediately after i'th element.
481 std::swap(Ops[i+1], Ops[j]);
482 ++i; // no need to rescan it.
483 if (i == e-2) return; // Done!
484 }
485 }
486 }
487}
488
489
490
491//===----------------------------------------------------------------------===//
492// Simple SCEV method implementations
493//===----------------------------------------------------------------------===//
494
Eli Friedman7489ec92008-08-04 23:49:06 +0000495/// BinomialCoefficient - Compute BC(It, K). The result has width W.
496// Assume, K > 0.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000497static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000498 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000499 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000500 // Handle the simplest case efficiently.
501 if (K == 1)
502 return SE.getTruncateOrZeroExtend(It, ResultTy);
503
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000504 // We are using the following formula for BC(It, K):
505 //
506 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
507 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000508 // Suppose, W is the bitwidth of the return value. We must be prepared for
509 // overflow. Hence, we must assure that the result of our computation is
510 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
511 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000512 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000513 // However, this code doesn't use exactly that formula; the formula it uses
514 // is something like the following, where T is the number of factors of 2 in
515 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
516 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000517 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000518 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000519 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000520 // This formula is trivially equivalent to the previous formula. However,
521 // this formula can be implemented much more efficiently. The trick is that
522 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
523 // arithmetic. To do exact division in modular arithmetic, all we have
524 // to do is multiply by the inverse. Therefore, this step can be done at
525 // width W.
526 //
527 // The next issue is how to safely do the division by 2^T. The way this
528 // is done is by doing the multiplication step at a width of at least W + T
529 // bits. This way, the bottom W+T bits of the product are accurate. Then,
530 // when we perform the division by 2^T (which is equivalent to a right shift
531 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
532 // truncated out after the division by 2^T.
533 //
534 // In comparison to just directly using the first formula, this technique
535 // is much more efficient; using the first formula requires W * K bits,
536 // but this formula less than W + K bits. Also, the first formula requires
537 // a division step, whereas this formula only requires multiplies and shifts.
538 //
539 // It doesn't matter whether the subtraction step is done in the calculation
540 // width or the input iteration count's width; if the subtraction overflows,
541 // the result must be zero anyway. We prefer here to do it in the width of
542 // the induction variable because it helps a lot for certain cases; CodeGen
543 // isn't smart enough to ignore the overflow, which leads to much less
544 // efficient code if the width of the subtraction is wider than the native
545 // register width.
546 //
547 // (It's possible to not widen at all by pulling out factors of 2 before
548 // the multiplication; for example, K=2 can be calculated as
549 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
550 // extra arithmetic, so it's not an obvious win, and it gets
551 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000552
Eli Friedman7489ec92008-08-04 23:49:06 +0000553 // Protection from insane SCEVs; this bound is conservative,
554 // but it probably doesn't matter.
555 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000556 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000557
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000558 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000559
Eli Friedman7489ec92008-08-04 23:49:06 +0000560 // Calculate K! / 2^T and T; we divide out the factors of two before
561 // multiplying for calculating K! / 2^T to avoid overflow.
562 // Other overflow doesn't matter because we only care about the bottom
563 // W bits of the result.
564 APInt OddFactorial(W, 1);
565 unsigned T = 1;
566 for (unsigned i = 3; i <= K; ++i) {
567 APInt Mult(W, i);
568 unsigned TwoFactors = Mult.countTrailingZeros();
569 T += TwoFactors;
570 Mult = Mult.lshr(TwoFactors);
571 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000572 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000573
Eli Friedman7489ec92008-08-04 23:49:06 +0000574 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000575 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000576
577 // Calcuate 2^T, at width T+W.
578 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
579
580 // Calculate the multiplicative inverse of K! / 2^T;
581 // this multiplication factor will perform the exact division by
582 // K! / 2^T.
583 APInt Mod = APInt::getSignedMinValue(W+1);
584 APInt MultiplyFactor = OddFactorial.zext(W+1);
585 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
586 MultiplyFactor = MultiplyFactor.trunc(W);
587
588 // Calculate the product, at width T+W
589 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
590 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
591 for (unsigned i = 1; i != K; ++i) {
592 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
593 Dividend = SE.getMulExpr(Dividend,
594 SE.getTruncateOrZeroExtend(S, CalculationTy));
595 }
596
597 // Divide by 2^T
598 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
599
600 // Truncate the result, and divide by K! / 2^T.
601
602 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
603 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000604}
605
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606/// evaluateAtIteration - Return the value of this chain of recurrences at
607/// the specified iteration number. We can evaluate this recurrence by
608/// multiplying each element in the chain by the binomial coefficient
609/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
610///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000611/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000612///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000613/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000614///
Dan Gohman89f85052007-10-22 18:31:58 +0000615SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
616 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000617 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000618 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000619 // The computation is correct in the face of overflow provided that the
620 // multiplication is performed _after_ the evaluation of the binomial
621 // coefficient.
Dan Gohman01c2ee72009-04-16 03:18:22 +0000622 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000623 if (isa<SCEVCouldNotCompute>(Coeff))
624 return Coeff;
625
626 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000627 }
628 return Result;
629}
630
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000631//===----------------------------------------------------------------------===//
632// SCEV Expression folder implementations
633//===----------------------------------------------------------------------===//
634
Dan Gohman9c8abcc2009-05-01 16:44:56 +0000635SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
636 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000637 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000638 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000639 assert(isSCEVable(Ty) &&
640 "This is not a conversion to a SCEVable type!");
641 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000642
Dan Gohmanc76b5452009-05-04 22:02:23 +0000643 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000644 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000645 ConstantExpr::getTrunc(SC->getValue(), Ty));
646
Dan Gohman1a5c4992009-04-22 16:20:48 +0000647 // trunc(trunc(x)) --> trunc(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000648 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000649 return getTruncateExpr(ST->getOperand(), Ty);
650
Nick Lewycky37d04642009-04-23 05:15:08 +0000651 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000652 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000653 return getTruncateOrSignExtend(SS->getOperand(), Ty);
654
655 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000656 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000657 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
658
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000659 // If the input value is a chrec scev made out of constants, truncate
660 // all of the constants.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000661 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000662 std::vector<SCEVHandle> Operands;
663 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
664 // FIXME: This should allow truncation of other expression types!
665 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman89f85052007-10-22 18:31:58 +0000666 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000667 else
668 break;
669 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman89f85052007-10-22 18:31:58 +0000670 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000671 }
672
673 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
674 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
675 return Result;
676}
677
Dan Gohman36d40922009-04-16 19:25:55 +0000678SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
679 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000680 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000681 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000682 assert(isSCEVable(Ty) &&
683 "This is not a conversion to a SCEVable type!");
684 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000685
Dan Gohmanc76b5452009-05-04 22:02:23 +0000686 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000687 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000688 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
689 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
690 return getUnknown(C);
691 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000692
Dan Gohman1a5c4992009-04-22 16:20:48 +0000693 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000694 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000695 return getZeroExtendExpr(SZ->getOperand(), Ty);
696
Dan Gohmana9dba962009-04-27 20:16:15 +0000697 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000698 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000699 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000700 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000701 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000702 if (AR->isAffine()) {
703 // Check whether the backedge-taken count is SCEVCouldNotCompute.
704 // Note that this serves two purposes: It filters out loops that are
705 // simply not analyzable, and it covers the case where this code is
706 // being called from within backedge-taken count analysis, such that
707 // attempting to ask for the backedge-taken count would likely result
708 // in infinite recursion. In the later case, the analysis code will
709 // cope with a conservative value, and it will take care to purge
710 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000711 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
712 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000713 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000714 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000715 SCEVHandle Start = AR->getStart();
716 SCEVHandle Step = AR->getStepRecurrence(*this);
717
718 // Check whether the backedge-taken count can be losslessly casted to
719 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000720 SCEVHandle CastedMaxBECount =
721 getTruncateOrZeroExtend(MaxBECount, Start->getType());
722 if (MaxBECount ==
723 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000724 const Type *WideTy =
725 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000726 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000727 SCEVHandle ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000728 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000729 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000730 SCEVHandle Add = getAddExpr(Start, ZMul);
731 if (getZeroExtendExpr(Add, WideTy) ==
732 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000733 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000734 getZeroExtendExpr(Step, WideTy))))
735 // Return the expression with the addrec on the outside.
736 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
737 getZeroExtendExpr(Step, Ty),
738 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000739
740 // Similar to above, only this time treat the step value as signed.
741 // This covers loops that count down.
742 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000743 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000744 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000745 Add = getAddExpr(Start, SMul);
746 if (getZeroExtendExpr(Add, WideTy) ==
747 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000748 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000749 getSignExtendExpr(Step, WideTy))))
750 // Return the expression with the addrec on the outside.
751 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
752 getSignExtendExpr(Step, Ty),
753 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000754 }
755 }
756 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000757
758 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
759 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
760 return Result;
761}
762
Dan Gohmana9dba962009-04-27 20:16:15 +0000763SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
764 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000765 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000766 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000767 assert(isSCEVable(Ty) &&
768 "This is not a conversion to a SCEVable type!");
769 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000770
Dan Gohmanc76b5452009-05-04 22:02:23 +0000771 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000772 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000773 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
774 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
775 return getUnknown(C);
776 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000777
Dan Gohman1a5c4992009-04-22 16:20:48 +0000778 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000779 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000780 return getSignExtendExpr(SS->getOperand(), Ty);
781
Dan Gohmana9dba962009-04-27 20:16:15 +0000782 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000783 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000784 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000786 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000787 if (AR->isAffine()) {
788 // Check whether the backedge-taken count is SCEVCouldNotCompute.
789 // Note that this serves two purposes: It filters out loops that are
790 // simply not analyzable, and it covers the case where this code is
791 // being called from within backedge-taken count analysis, such that
792 // attempting to ask for the backedge-taken count would likely result
793 // in infinite recursion. In the later case, the analysis code will
794 // cope with a conservative value, and it will take care to purge
795 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000796 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
797 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000798 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000799 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000800 SCEVHandle Start = AR->getStart();
801 SCEVHandle Step = AR->getStepRecurrence(*this);
802
803 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000804 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000805 SCEVHandle CastedMaxBECount =
806 getTruncateOrZeroExtend(MaxBECount, Start->getType());
807 if (MaxBECount ==
808 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000809 const Type *WideTy =
810 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000811 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000812 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000813 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000814 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000815 SCEVHandle Add = getAddExpr(Start, SMul);
816 if (getSignExtendExpr(Add, WideTy) ==
817 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000818 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000819 getSignExtendExpr(Step, WideTy))))
820 // Return the expression with the addrec on the outside.
821 return getAddRecExpr(getSignExtendExpr(Start, Ty),
822 getSignExtendExpr(Step, Ty),
823 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000824 }
825 }
826 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000827
828 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
829 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
830 return Result;
831}
832
833// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000834SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000835 assert(!Ops.empty() && "Cannot get empty add!");
836 if (Ops.size() == 1) return Ops[0];
837
838 // Sort by complexity, this groups all similar expression types together.
839 GroupByComplexity(Ops);
840
841 // If there are any constants, fold them together.
842 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +0000843 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000844 ++Idx;
845 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +0000846 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000847 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000848 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
849 RHSC->getValue()->getValue());
850 Ops[0] = getConstant(Fold);
851 Ops.erase(Ops.begin()+1); // Erase the folded element
852 if (Ops.size() == 1) return Ops[0];
853 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000854 }
855
856 // If we are left with a constant zero being added, strip it off.
857 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
858 Ops.erase(Ops.begin());
859 --Idx;
860 }
861 }
862
863 if (Ops.size() == 1) return Ops[0];
864
865 // Okay, check to see if the same value occurs in the operand list twice. If
866 // so, merge them together into an multiply expression. Since we sorted the
867 // list, these values are required to be adjacent.
868 const Type *Ty = Ops[0]->getType();
869 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
870 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
871 // Found a match, merge the two values into a multiply, and add any
872 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000873 SCEVHandle Two = getIntegerSCEV(2, Ty);
874 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000875 if (Ops.size() == 2)
876 return Mul;
877 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
878 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000879 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000880 }
881
882 // Now we know the first non-constant operand. Skip past any cast SCEVs.
883 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
884 ++Idx;
885
886 // If there are add operands they would be next.
887 if (Idx < Ops.size()) {
888 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +0000889 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000890 // If we have an add, expand the add operands onto the end of the operands
891 // list.
892 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
893 Ops.erase(Ops.begin()+Idx);
894 DeletedAdd = true;
895 }
896
897 // If we deleted at least one add, we added operands to the end of the list,
898 // and they are not necessarily sorted. Recurse to resort and resimplify
899 // any operands we just aquired.
900 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +0000901 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000902 }
903
904 // Skip over the add expression until we get to a multiply.
905 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
906 ++Idx;
907
908 // If we are adding something to a multiply expression, make sure the
909 // something is not already an operand of the multiply. If so, merge it into
910 // the multiply.
911 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000912 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000913 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000914 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000915 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
916 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
917 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
918 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
919 if (Mul->getNumOperands() != 2) {
920 // If the multiply has more than two operands, we must get the
921 // Y*Z term.
922 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
923 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000924 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000925 }
Dan Gohman89f85052007-10-22 18:31:58 +0000926 SCEVHandle One = getIntegerSCEV(1, Ty);
927 SCEVHandle AddOne = getAddExpr(InnerMul, One);
928 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000929 if (Ops.size() == 2) return OuterMul;
930 if (AddOp < Idx) {
931 Ops.erase(Ops.begin()+AddOp);
932 Ops.erase(Ops.begin()+Idx-1);
933 } else {
934 Ops.erase(Ops.begin()+Idx);
935 Ops.erase(Ops.begin()+AddOp-1);
936 }
937 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000938 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000939 }
940
941 // Check this multiply against other multiplies being added together.
942 for (unsigned OtherMulIdx = Idx+1;
943 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
944 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000945 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000946 // If MulOp occurs in OtherMul, we can fold the two multiplies
947 // together.
948 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
949 OMulOp != e; ++OMulOp)
950 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
951 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
952 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
953 if (Mul->getNumOperands() != 2) {
954 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
955 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000956 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000957 }
958 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
959 if (OtherMul->getNumOperands() != 2) {
960 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
961 OtherMul->op_end());
962 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000963 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000964 }
Dan Gohman89f85052007-10-22 18:31:58 +0000965 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
966 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000967 if (Ops.size() == 2) return OuterMul;
968 Ops.erase(Ops.begin()+Idx);
969 Ops.erase(Ops.begin()+OtherMulIdx-1);
970 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000971 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000972 }
973 }
974 }
975 }
976
977 // If there are any add recurrences in the operands list, see if any other
978 // added values are loop invariant. If so, we can fold them into the
979 // recurrence.
980 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
981 ++Idx;
982
983 // Scan over all recurrences, trying to fold loop invariants into them.
984 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
985 // Scan all of the other operands to this add and add them to the vector if
986 // they are loop invariant w.r.t. the recurrence.
987 std::vector<SCEVHandle> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +0000988 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000989 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
990 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
991 LIOps.push_back(Ops[i]);
992 Ops.erase(Ops.begin()+i);
993 --i; --e;
994 }
995
996 // If we found some loop invariants, fold them into the recurrence.
997 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +0000998 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000999 LIOps.push_back(AddRec->getStart());
1000
1001 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001002 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001003
Dan Gohman89f85052007-10-22 18:31:58 +00001004 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001005 // If all of the other operands were loop invariant, we are done.
1006 if (Ops.size() == 1) return NewRec;
1007
1008 // Otherwise, add the folded AddRec by the non-liv parts.
1009 for (unsigned i = 0;; ++i)
1010 if (Ops[i] == AddRec) {
1011 Ops[i] = NewRec;
1012 break;
1013 }
Dan Gohman89f85052007-10-22 18:31:58 +00001014 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001015 }
1016
1017 // Okay, if there weren't any loop invariants to be folded, check to see if
1018 // there are multiple AddRec's with the same loop induction variable being
1019 // added together. If so, we can fold them.
1020 for (unsigned OtherIdx = Idx+1;
1021 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1022 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001023 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001024 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1025 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1026 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1027 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1028 if (i >= NewOps.size()) {
1029 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1030 OtherAddRec->op_end());
1031 break;
1032 }
Dan Gohman89f85052007-10-22 18:31:58 +00001033 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001034 }
Dan Gohman89f85052007-10-22 18:31:58 +00001035 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001036
1037 if (Ops.size() == 2) return NewAddRec;
1038
1039 Ops.erase(Ops.begin()+Idx);
1040 Ops.erase(Ops.begin()+OtherIdx-1);
1041 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001042 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043 }
1044 }
1045
1046 // Otherwise couldn't fold anything into this recurrence. Move onto the
1047 // next one.
1048 }
1049
1050 // Okay, it looks like we really DO need an add expr. Check to see if we
1051 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001052 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1054 SCEVOps)];
1055 if (Result == 0) Result = new SCEVAddExpr(Ops);
1056 return Result;
1057}
1058
1059
Dan Gohman89f85052007-10-22 18:31:58 +00001060SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001061 assert(!Ops.empty() && "Cannot get empty mul!");
1062
1063 // Sort by complexity, this groups all similar expression types together.
1064 GroupByComplexity(Ops);
1065
1066 // If there are any constants, fold them together.
1067 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001068 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001069
1070 // C1*(C2+V) -> C1*C2 + C1*V
1071 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001072 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001073 if (Add->getNumOperands() == 2 &&
1074 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001075 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1076 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001077
1078
1079 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001080 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001081 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001082 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1083 RHSC->getValue()->getValue());
1084 Ops[0] = getConstant(Fold);
1085 Ops.erase(Ops.begin()+1); // Erase the folded element
1086 if (Ops.size() == 1) return Ops[0];
1087 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001088 }
1089
1090 // If we are left with a constant one being multiplied, strip it off.
1091 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1092 Ops.erase(Ops.begin());
1093 --Idx;
1094 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1095 // If we have a multiply of zero, it will always be zero.
1096 return Ops[0];
1097 }
1098 }
1099
1100 // Skip over the add expression until we get to a multiply.
1101 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1102 ++Idx;
1103
1104 if (Ops.size() == 1)
1105 return Ops[0];
1106
1107 // If there are mul operands inline them all into this expression.
1108 if (Idx < Ops.size()) {
1109 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001110 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001111 // If we have an mul, expand the mul operands onto the end of the operands
1112 // list.
1113 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1114 Ops.erase(Ops.begin()+Idx);
1115 DeletedMul = true;
1116 }
1117
1118 // If we deleted at least one mul, we added operands to the end of the list,
1119 // and they are not necessarily sorted. Recurse to resort and resimplify
1120 // any operands we just aquired.
1121 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001122 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001123 }
1124
1125 // If there are any add recurrences in the operands list, see if any other
1126 // added values are loop invariant. If so, we can fold them into the
1127 // recurrence.
1128 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1129 ++Idx;
1130
1131 // Scan over all recurrences, trying to fold loop invariants into them.
1132 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1133 // Scan all of the other operands to this mul and add them to the vector if
1134 // they are loop invariant w.r.t. the recurrence.
1135 std::vector<SCEVHandle> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001136 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001137 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1138 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1139 LIOps.push_back(Ops[i]);
1140 Ops.erase(Ops.begin()+i);
1141 --i; --e;
1142 }
1143
1144 // If we found some loop invariants, fold them into the recurrence.
1145 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001146 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001147 std::vector<SCEVHandle> NewOps;
1148 NewOps.reserve(AddRec->getNumOperands());
1149 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001150 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001151 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001152 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001153 } else {
1154 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1155 std::vector<SCEVHandle> MulOps(LIOps);
1156 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001157 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001158 }
1159 }
1160
Dan Gohman89f85052007-10-22 18:31:58 +00001161 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001162
1163 // If all of the other operands were loop invariant, we are done.
1164 if (Ops.size() == 1) return NewRec;
1165
1166 // Otherwise, multiply the folded AddRec by the non-liv parts.
1167 for (unsigned i = 0;; ++i)
1168 if (Ops[i] == AddRec) {
1169 Ops[i] = NewRec;
1170 break;
1171 }
Dan Gohman89f85052007-10-22 18:31:58 +00001172 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001173 }
1174
1175 // Okay, if there weren't any loop invariants to be folded, check to see if
1176 // there are multiple AddRec's with the same loop induction variable being
1177 // multiplied together. If so, we can fold them.
1178 for (unsigned OtherIdx = Idx+1;
1179 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1180 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001181 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001182 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1183 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001184 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001185 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001186 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001187 SCEVHandle B = F->getStepRecurrence(*this);
1188 SCEVHandle D = G->getStepRecurrence(*this);
1189 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1190 getMulExpr(G, B),
1191 getMulExpr(B, D));
1192 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1193 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001194 if (Ops.size() == 2) return NewAddRec;
1195
1196 Ops.erase(Ops.begin()+Idx);
1197 Ops.erase(Ops.begin()+OtherIdx-1);
1198 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001199 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001200 }
1201 }
1202
1203 // Otherwise couldn't fold anything into this recurrence. Move onto the
1204 // next one.
1205 }
1206
1207 // Okay, it looks like we really DO need an mul expr. Check to see if we
1208 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001209 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001210 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1211 SCEVOps)];
1212 if (Result == 0)
1213 Result = new SCEVMulExpr(Ops);
1214 return Result;
1215}
1216
Dan Gohman77841cd2009-05-04 22:23:18 +00001217SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1218 const SCEVHandle &RHS) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001219 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001220 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001221 return LHS; // X udiv 1 --> x
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001222
Dan Gohmanc76b5452009-05-04 22:02:23 +00001223 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001224 Constant *LHSCV = LHSC->getValue();
1225 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001226 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001227 }
1228 }
1229
Nick Lewycky35b56022009-01-13 09:18:58 +00001230 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1231
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001232 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1233 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001234 return Result;
1235}
1236
1237
1238/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1239/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001240SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001241 const SCEVHandle &Step, const Loop *L) {
1242 std::vector<SCEVHandle> Operands;
1243 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001244 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001245 if (StepChrec->getLoop() == L) {
1246 Operands.insert(Operands.end(), StepChrec->op_begin(),
1247 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001248 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001249 }
1250
1251 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001252 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001253}
1254
1255/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1256/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001257SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Nick Lewycky37d04642009-04-23 05:15:08 +00001258 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001259 if (Operands.size() == 1) return Operands[0];
1260
Dan Gohman7b560c42008-06-18 16:23:07 +00001261 if (Operands.back()->isZero()) {
1262 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001263 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001264 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001265
Dan Gohman42936882008-08-08 18:33:12 +00001266 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001267 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001268 const Loop* NestedLoop = NestedAR->getLoop();
1269 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1270 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1271 NestedAR->op_end());
1272 SCEVHandle NestedARHandle(NestedAR);
1273 Operands[0] = NestedAR->getStart();
1274 NestedOperands[0] = getAddRecExpr(Operands, L);
1275 return getAddRecExpr(NestedOperands, NestedLoop);
1276 }
1277 }
1278
Dan Gohmanbff6b582009-05-04 22:30:44 +00001279 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1280 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001281 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1282 return Result;
1283}
1284
Nick Lewycky711640a2007-11-25 22:41:31 +00001285SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1286 const SCEVHandle &RHS) {
1287 std::vector<SCEVHandle> Ops;
1288 Ops.push_back(LHS);
1289 Ops.push_back(RHS);
1290 return getSMaxExpr(Ops);
1291}
1292
1293SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1294 assert(!Ops.empty() && "Cannot get empty smax!");
1295 if (Ops.size() == 1) return Ops[0];
1296
1297 // Sort by complexity, this groups all similar expression types together.
1298 GroupByComplexity(Ops);
1299
1300 // If there are any constants, fold them together.
1301 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001302 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001303 ++Idx;
1304 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001305 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001306 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001307 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001308 APIntOps::smax(LHSC->getValue()->getValue(),
1309 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001310 Ops[0] = getConstant(Fold);
1311 Ops.erase(Ops.begin()+1); // Erase the folded element
1312 if (Ops.size() == 1) return Ops[0];
1313 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001314 }
1315
1316 // If we are left with a constant -inf, strip it off.
1317 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1318 Ops.erase(Ops.begin());
1319 --Idx;
1320 }
1321 }
1322
1323 if (Ops.size() == 1) return Ops[0];
1324
1325 // Find the first SMax
1326 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1327 ++Idx;
1328
1329 // Check to see if one of the operands is an SMax. If so, expand its operands
1330 // onto our operand list, and recurse to simplify.
1331 if (Idx < Ops.size()) {
1332 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001333 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001334 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1335 Ops.erase(Ops.begin()+Idx);
1336 DeletedSMax = true;
1337 }
1338
1339 if (DeletedSMax)
1340 return getSMaxExpr(Ops);
1341 }
1342
1343 // Okay, check to see if the same value occurs in the operand list twice. If
1344 // so, delete one. Since we sorted the list, these values are required to
1345 // be adjacent.
1346 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1347 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1348 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1349 --i; --e;
1350 }
1351
1352 if (Ops.size() == 1) return Ops[0];
1353
1354 assert(!Ops.empty() && "Reduced smax down to nothing!");
1355
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001356 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001357 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001358 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewycky711640a2007-11-25 22:41:31 +00001359 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1360 SCEVOps)];
1361 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1362 return Result;
1363}
1364
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001365SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1366 const SCEVHandle &RHS) {
1367 std::vector<SCEVHandle> Ops;
1368 Ops.push_back(LHS);
1369 Ops.push_back(RHS);
1370 return getUMaxExpr(Ops);
1371}
1372
1373SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1374 assert(!Ops.empty() && "Cannot get empty umax!");
1375 if (Ops.size() == 1) return Ops[0];
1376
1377 // Sort by complexity, this groups all similar expression types together.
1378 GroupByComplexity(Ops);
1379
1380 // If there are any constants, fold them together.
1381 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001382 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001383 ++Idx;
1384 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001385 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001386 // We found two constants, fold them together!
1387 ConstantInt *Fold = ConstantInt::get(
1388 APIntOps::umax(LHSC->getValue()->getValue(),
1389 RHSC->getValue()->getValue()));
1390 Ops[0] = getConstant(Fold);
1391 Ops.erase(Ops.begin()+1); // Erase the folded element
1392 if (Ops.size() == 1) return Ops[0];
1393 LHSC = cast<SCEVConstant>(Ops[0]);
1394 }
1395
1396 // If we are left with a constant zero, strip it off.
1397 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1398 Ops.erase(Ops.begin());
1399 --Idx;
1400 }
1401 }
1402
1403 if (Ops.size() == 1) return Ops[0];
1404
1405 // Find the first UMax
1406 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1407 ++Idx;
1408
1409 // Check to see if one of the operands is a UMax. If so, expand its operands
1410 // onto our operand list, and recurse to simplify.
1411 if (Idx < Ops.size()) {
1412 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001413 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001414 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1415 Ops.erase(Ops.begin()+Idx);
1416 DeletedUMax = true;
1417 }
1418
1419 if (DeletedUMax)
1420 return getUMaxExpr(Ops);
1421 }
1422
1423 // Okay, check to see if the same value occurs in the operand list twice. If
1424 // so, delete one. Since we sorted the list, these values are required to
1425 // be adjacent.
1426 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1427 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1428 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1429 --i; --e;
1430 }
1431
1432 if (Ops.size() == 1) return Ops[0];
1433
1434 assert(!Ops.empty() && "Reduced umax down to nothing!");
1435
1436 // Okay, it looks like we really DO need a umax expr. Check to see if we
1437 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001438 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001439 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1440 SCEVOps)];
1441 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1442 return Result;
1443}
1444
Dan Gohman89f85052007-10-22 18:31:58 +00001445SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001446 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001447 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001448 if (isa<ConstantPointerNull>(V))
1449 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001450 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1451 if (Result == 0) Result = new SCEVUnknown(V);
1452 return Result;
1453}
1454
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001455//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001456// Basic SCEV Analysis and PHI Idiom Recognition Code
1457//
1458
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001459/// isSCEVable - Test if values of the given type are analyzable within
1460/// the SCEV framework. This primarily includes integer types, and it
1461/// can optionally include pointer types if the ScalarEvolution class
1462/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001463bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001464 // Integers are always SCEVable.
1465 if (Ty->isInteger())
1466 return true;
1467
1468 // Pointers are SCEVable if TargetData information is available
1469 // to provide pointer size information.
1470 if (isa<PointerType>(Ty))
1471 return TD != NULL;
1472
1473 // Otherwise it's not SCEVable.
1474 return false;
1475}
1476
1477/// getTypeSizeInBits - Return the size in bits of the specified type,
1478/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001479uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001480 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1481
1482 // If we have a TargetData, use it!
1483 if (TD)
1484 return TD->getTypeSizeInBits(Ty);
1485
1486 // Otherwise, we support only integer types.
1487 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1488 return Ty->getPrimitiveSizeInBits();
1489}
1490
1491/// getEffectiveSCEVType - Return a type with the same bitwidth as
1492/// the given type and which represents how SCEV will treat the given
1493/// type, for which isSCEVable must return true. For pointer types,
1494/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001495const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001496 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1497
1498 if (Ty->isInteger())
1499 return Ty;
1500
1501 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1502 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001503}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001504
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001505SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman0ad08b02009-04-18 17:58:19 +00001506 return UnknownValue;
1507}
1508
Dan Gohmand83d4af2009-05-04 22:20:30 +00001509/// hasSCEV - Return true if the SCEV for this value has already been
Edwin Török0e828d62009-05-01 08:33:47 +00001510/// computed.
1511bool ScalarEvolution::hasSCEV(Value *V) const {
1512 return Scalars.count(V);
1513}
1514
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001515/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1516/// expression and create a new one.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001517SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001518 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001519
Dan Gohmanbff6b582009-05-04 22:30:44 +00001520 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001521 if (I != Scalars.end()) return I->second;
1522 SCEVHandle S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00001523 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001524 return S;
1525}
1526
Dan Gohman01c2ee72009-04-16 03:18:22 +00001527/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1528/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001529SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1530 Ty = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001531 Constant *C;
1532 if (Val == 0)
1533 C = Constant::getNullValue(Ty);
1534 else if (Ty->isFloatingPoint())
1535 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1536 APFloat::IEEEdouble, Val));
1537 else
1538 C = ConstantInt::get(Ty, Val);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001539 return getUnknown(C);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001540}
1541
1542/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1543///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001544SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001545 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001546 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001547
1548 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001549 Ty = getEffectiveSCEVType(Ty);
1550 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001551}
1552
1553/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001554SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001555 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001556 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001557
1558 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001559 Ty = getEffectiveSCEVType(Ty);
1560 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001561 return getMinusSCEV(AllOnes, V);
1562}
1563
1564/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1565///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001566SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky37d04642009-04-23 05:15:08 +00001567 const SCEVHandle &RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001568 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001569 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001570}
1571
1572/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1573/// input value to the specified type. If the type must be extended, it is zero
1574/// extended.
1575SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001576ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001577 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001578 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001579 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1580 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001581 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001582 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001583 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001584 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001585 return getTruncateExpr(V, Ty);
1586 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001587}
1588
1589/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1590/// input value to the specified type. If the type must be extended, it is sign
1591/// extended.
1592SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001593ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001594 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001595 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001596 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1597 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001598 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001599 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001600 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001601 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001602 return getTruncateExpr(V, Ty);
1603 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001604}
1605
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001606/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1607/// the specified instruction and replaces any references to the symbolic value
1608/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001609void ScalarEvolution::
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001610ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1611 const SCEVHandle &NewVal) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001612 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
1613 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001614 if (SI == Scalars.end()) return;
1615
1616 SCEVHandle NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001617 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001618 if (NV == SI->second) return; // No change.
1619
1620 SI->second = NV; // Update the scalars map!
1621
1622 // Any instruction values that use this instruction might also need to be
1623 // updated!
1624 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1625 UI != E; ++UI)
1626 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1627}
1628
1629/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1630/// a loop header, making it a potential recurrence, or it doesn't.
1631///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001632SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001633 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001634 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001635 if (L->getHeader() == PN->getParent()) {
1636 // If it lives in the loop header, it has two incoming values, one
1637 // from outside the loop, and one from inside.
1638 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1639 unsigned BackEdge = IncomingEdge^1;
1640
1641 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001642 SCEVHandle SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001643 assert(Scalars.find(PN) == Scalars.end() &&
1644 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00001645 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001646
1647 // Using this symbolic name for the PHI, analyze the value coming around
1648 // the back-edge.
1649 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1650
1651 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1652 // has a special value for the first iteration of the loop.
1653
1654 // If the value coming around the backedge is an add with the symbolic
1655 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00001656 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001657 // If there is a single occurrence of the symbolic value, replace it
1658 // with a recurrence.
1659 unsigned FoundIndex = Add->getNumOperands();
1660 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1661 if (Add->getOperand(i) == SymbolicName)
1662 if (FoundIndex == e) {
1663 FoundIndex = i;
1664 break;
1665 }
1666
1667 if (FoundIndex != Add->getNumOperands()) {
1668 // Create an add with everything but the specified operand.
1669 std::vector<SCEVHandle> Ops;
1670 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1671 if (i != FoundIndex)
1672 Ops.push_back(Add->getOperand(i));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001673 SCEVHandle Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001674
1675 // This is not a valid addrec if the step amount is varying each
1676 // loop iteration, but is not itself an addrec in this loop.
1677 if (Accum->isLoopInvariant(L) ||
1678 (isa<SCEVAddRecExpr>(Accum) &&
1679 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1680 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001681 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001682
1683 // Okay, for the entire analysis of this edge we assumed the PHI
1684 // to be symbolic. We now need to go back and update all of the
1685 // entries for the scalars that use the PHI (except for the PHI
1686 // itself) to use the new analyzed value instead of the "symbolic"
1687 // value.
1688 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1689 return PHISCEV;
1690 }
1691 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00001692 } else if (const SCEVAddRecExpr *AddRec =
1693 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001694 // Otherwise, this could be a loop like this:
1695 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1696 // In this case, j = {1,+,1} and BEValue is j.
1697 // Because the other in-value of i (0) fits the evolution of BEValue
1698 // i really is an addrec evolution.
1699 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1700 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1701
1702 // If StartVal = j.start - j.stride, we can use StartVal as the
1703 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001704 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00001705 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001706 SCEVHandle PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001707 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001708
1709 // Okay, for the entire analysis of this edge we assumed the PHI
1710 // to be symbolic. We now need to go back and update all of the
1711 // entries for the scalars that use the PHI (except for the PHI
1712 // itself) to use the new analyzed value instead of the "symbolic"
1713 // value.
1714 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1715 return PHISCEV;
1716 }
1717 }
1718 }
1719
1720 return SymbolicName;
1721 }
1722
1723 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001724 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001725}
1726
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001727/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1728/// guaranteed to end in (at every loop iteration). It is, at the same time,
1729/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1730/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001731static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001732 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001733 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001734
Dan Gohmanc76b5452009-05-04 22:02:23 +00001735 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001736 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1737 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001738
Dan Gohmanc76b5452009-05-04 22:02:23 +00001739 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001740 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1741 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1742 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001743 }
1744
Dan Gohmanc76b5452009-05-04 22:02:23 +00001745 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001746 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1747 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1748 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001749 }
1750
Dan Gohmanc76b5452009-05-04 22:02:23 +00001751 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001752 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001753 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001754 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001755 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001756 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001757 }
1758
Dan Gohmanc76b5452009-05-04 22:02:23 +00001759 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001760 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001761 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1762 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001763 for (unsigned i = 1, e = M->getNumOperands();
1764 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001765 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001766 BitWidth);
1767 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001768 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001769
Dan Gohmanc76b5452009-05-04 22:02:23 +00001770 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001771 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001772 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001773 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001774 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001775 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001776 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001777
Dan Gohmanc76b5452009-05-04 22:02:23 +00001778 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001779 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001780 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00001781 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001782 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00001783 return MinOpRes;
1784 }
1785
Dan Gohmanc76b5452009-05-04 22:02:23 +00001786 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001787 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001788 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001789 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001790 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001791 return MinOpRes;
1792 }
1793
Nick Lewycky35b56022009-01-13 09:18:58 +00001794 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001795 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001796}
1797
1798/// createSCEV - We know that there is no SCEV for the specified value.
1799/// Analyze the expression.
1800///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001801SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001802 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001803 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001804
Dan Gohman3996f472008-06-22 19:56:46 +00001805 unsigned Opcode = Instruction::UserOp1;
1806 if (Instruction *I = dyn_cast<Instruction>(V))
1807 Opcode = I->getOpcode();
1808 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1809 Opcode = CE->getOpcode();
1810 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001811 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001812
Dan Gohman3996f472008-06-22 19:56:46 +00001813 User *U = cast<User>(V);
1814 switch (Opcode) {
1815 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001816 return getAddExpr(getSCEV(U->getOperand(0)),
1817 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001818 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001819 return getMulExpr(getSCEV(U->getOperand(0)),
1820 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001821 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001822 return getUDivExpr(getSCEV(U->getOperand(0)),
1823 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001824 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001825 return getMinusSCEV(getSCEV(U->getOperand(0)),
1826 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00001827 case Instruction::And:
1828 // For an expression like x&255 that merely masks off the high bits,
1829 // use zext(trunc(x)) as the SCEV expression.
1830 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00001831 if (CI->isNullValue())
1832 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00001833 if (CI->isAllOnesValue())
1834 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00001835 const APInt &A = CI->getValue();
1836 unsigned Ones = A.countTrailingOnes();
1837 if (APIntOps::isMask(Ones, A))
1838 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001839 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
1840 IntegerType::get(Ones)),
1841 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00001842 }
1843 break;
Dan Gohman3996f472008-06-22 19:56:46 +00001844 case Instruction::Or:
1845 // If the RHS of the Or is a constant, we may have something like:
1846 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1847 // optimizations will transparently handle this case.
1848 //
1849 // In order for this transformation to be safe, the LHS must be of the
1850 // form X*(2^n) and the Or constant must be less than 2^n.
1851 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1852 SCEVHandle LHS = getSCEV(U->getOperand(0));
1853 const APInt &CIVal = CI->getValue();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001854 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman3996f472008-06-22 19:56:46 +00001855 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001856 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001857 }
Dan Gohman3996f472008-06-22 19:56:46 +00001858 break;
1859 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00001860 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00001861 // If the RHS of the xor is a signbit, then this is just an add.
1862 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00001863 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001864 return getAddExpr(getSCEV(U->getOperand(0)),
1865 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001866
1867 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman3996f472008-06-22 19:56:46 +00001868 else if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001869 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman3996f472008-06-22 19:56:46 +00001870 }
1871 break;
1872
1873 case Instruction::Shl:
1874 // Turn shift left of a constant amount into a multiply.
1875 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1876 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1877 Constant *X = ConstantInt::get(
1878 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001879 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00001880 }
1881 break;
1882
Nick Lewycky7fd27892008-07-07 06:15:49 +00001883 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00001884 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00001885 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1886 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1887 Constant *X = ConstantInt::get(
1888 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001889 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001890 }
1891 break;
1892
Dan Gohman53bf64a2009-04-21 02:26:00 +00001893 case Instruction::AShr:
1894 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
1895 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
1896 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
1897 if (L->getOpcode() == Instruction::Shl &&
1898 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00001899 unsigned BitWidth = getTypeSizeInBits(U->getType());
1900 uint64_t Amt = BitWidth - CI->getZExtValue();
1901 if (Amt == BitWidth)
1902 return getSCEV(L->getOperand(0)); // shift by zero --> noop
1903 if (Amt > BitWidth)
1904 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00001905 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001906 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00001907 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00001908 U->getType());
1909 }
1910 break;
1911
Dan Gohman3996f472008-06-22 19:56:46 +00001912 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001913 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001914
1915 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001916 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001917
1918 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001919 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001920
1921 case Instruction::BitCast:
1922 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001923 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00001924 return getSCEV(U->getOperand(0));
1925 break;
1926
Dan Gohman01c2ee72009-04-16 03:18:22 +00001927 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001928 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001929 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001930 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00001931
1932 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001933 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001934 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1935 U->getType());
1936
1937 case Instruction::GetElementPtr: {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001938 if (!TD) break; // Without TD we can't analyze pointers.
1939 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001940 Value *Base = U->getOperand(0);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001941 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001942 gep_type_iterator GTI = gep_type_begin(U);
1943 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
1944 E = U->op_end();
1945 I != E; ++I) {
1946 Value *Index = *I;
1947 // Compute the (potentially symbolic) offset in bytes for this index.
1948 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1949 // For a struct, add the member offset.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001950 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001951 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1952 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001953 TotalOffset = getAddExpr(TotalOffset,
1954 getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001955 } else {
1956 // For an array, add the element offset, explicitly scaled.
1957 SCEVHandle LocalOffset = getSCEV(Index);
1958 if (!isa<PointerType>(LocalOffset->getType()))
1959 // Getelementptr indicies are signed.
1960 LocalOffset = getTruncateOrSignExtend(LocalOffset,
1961 IntPtrTy);
1962 LocalOffset =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001963 getMulExpr(LocalOffset,
1964 getIntegerSCEV(TD->getTypePaddedSize(*GTI),
1965 IntPtrTy));
1966 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001967 }
1968 }
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001969 return getAddExpr(getSCEV(Base), TotalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001970 }
1971
Dan Gohman3996f472008-06-22 19:56:46 +00001972 case Instruction::PHI:
1973 return createNodeForPHI(cast<PHINode>(U));
1974
1975 case Instruction::Select:
1976 // This could be a smax or umax that was lowered earlier.
1977 // Try to recover it.
1978 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1979 Value *LHS = ICI->getOperand(0);
1980 Value *RHS = ICI->getOperand(1);
1981 switch (ICI->getPredicate()) {
1982 case ICmpInst::ICMP_SLT:
1983 case ICmpInst::ICMP_SLE:
1984 std::swap(LHS, RHS);
1985 // fall through
1986 case ICmpInst::ICMP_SGT:
1987 case ICmpInst::ICMP_SGE:
1988 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001989 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00001990 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00001991 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001992 return getNotSCEV(getSMaxExpr(
1993 getNotSCEV(getSCEV(LHS)),
1994 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00001995 break;
1996 case ICmpInst::ICMP_ULT:
1997 case ICmpInst::ICMP_ULE:
1998 std::swap(LHS, RHS);
1999 // fall through
2000 case ICmpInst::ICMP_UGT:
2001 case ICmpInst::ICMP_UGE:
2002 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002003 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002004 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2005 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002006 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2007 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002008 break;
2009 default:
2010 break;
2011 }
2012 }
2013
2014 default: // We cannot analyze this expression.
2015 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002016 }
2017
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002018 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002019}
2020
2021
2022
2023//===----------------------------------------------------------------------===//
2024// Iteration Count Computation Code
2025//
2026
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002027/// getBackedgeTakenCount - If the specified loop has a predictable
2028/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2029/// object. The backedge-taken count is the number of times the loop header
2030/// will be branched to from within the loop. This is one less than the
2031/// trip count of the loop, since it doesn't count the first iteration,
2032/// when the header is branched to from outside the loop.
2033///
2034/// Note that it is not valid to call this method on a loop without a
2035/// loop-invariant backedge-taken count (see
2036/// hasLoopInvariantBackedgeTakenCount).
2037///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002038SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002039 return getBackedgeTakenInfo(L).Exact;
2040}
2041
2042/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2043/// return the least SCEV value that is known never to be less than the
2044/// actual backedge taken count.
2045SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2046 return getBackedgeTakenInfo(L).Max;
2047}
2048
2049const ScalarEvolution::BackedgeTakenInfo &
2050ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002051 // Initially insert a CouldNotCompute for this loop. If the insertion
2052 // succeeds, procede to actually compute a backedge-taken count and
2053 // update the value. The temporary CouldNotCompute value tells SCEV
2054 // code elsewhere that it shouldn't attempt to request a new
2055 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002056 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002057 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2058 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002059 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2060 if (ItCount.Exact != UnknownValue) {
2061 assert(ItCount.Exact->isLoopInvariant(L) &&
2062 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002063 "Computed trip count isn't loop invariant for loop!");
2064 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002065
Dan Gohmana9dba962009-04-27 20:16:15 +00002066 // Update the value in the map.
2067 Pair.first->second = ItCount;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002068 } else if (isa<PHINode>(L->getHeader()->begin())) {
2069 // Only count loops that have phi nodes as not being computable.
2070 ++NumTripCountsNotComputed;
2071 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002072
2073 // Now that we know more about the trip count for this loop, forget any
2074 // existing SCEV values for PHI nodes in this loop since they are only
2075 // conservative estimates made without the benefit
2076 // of trip count information.
2077 if (ItCount.hasAnyInfo())
Dan Gohman94623022009-05-02 17:43:35 +00002078 forgetLoopPHIs(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002079 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002080 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002081}
2082
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002083/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002084/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002085/// ScalarEvolution's ability to compute a trip count, or if the loop
2086/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002087void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002088 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002089 forgetLoopPHIs(L);
2090}
2091
2092/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2093/// PHI nodes in the given loop. This is used when the trip count of
2094/// the loop may have changed.
2095void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002096 BasicBlock *Header = L->getHeader();
2097
2098 SmallVector<Instruction *, 16> Worklist;
2099 for (BasicBlock::iterator I = Header->begin();
Dan Gohman94623022009-05-02 17:43:35 +00002100 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Dan Gohmanbff6b582009-05-04 22:30:44 +00002101 Worklist.push_back(PN);
2102
2103 while (!Worklist.empty()) {
2104 Instruction *I = Worklist.pop_back_val();
2105 if (Scalars.erase(I))
2106 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2107 UI != UE; ++UI)
2108 Worklist.push_back(cast<Instruction>(UI));
2109 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002110}
2111
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002112/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2113/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002114ScalarEvolution::BackedgeTakenInfo
2115ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002116 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00002117 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002118 L->getExitBlocks(ExitBlocks);
2119 if (ExitBlocks.size() != 1) return UnknownValue;
2120
2121 // Okay, there is one exit block. Try to find the condition that causes the
2122 // loop to be exited.
2123 BasicBlock *ExitBlock = ExitBlocks[0];
2124
2125 BasicBlock *ExitingBlock = 0;
2126 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2127 PI != E; ++PI)
2128 if (L->contains(*PI)) {
2129 if (ExitingBlock == 0)
2130 ExitingBlock = *PI;
2131 else
2132 return UnknownValue; // More than one block exiting!
2133 }
2134 assert(ExitingBlock && "No exits from loop, something is broken!");
2135
2136 // Okay, we've computed the exiting block. See what condition causes us to
2137 // exit.
2138 //
2139 // FIXME: we should be able to handle switch instructions (with a single exit)
2140 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2141 if (ExitBr == 0) return UnknownValue;
2142 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2143
2144 // At this point, we know we have a conditional branch that determines whether
2145 // the loop is exited. However, we don't know if the branch is executed each
2146 // time through the loop. If not, then the execution count of the branch will
2147 // not be equal to the trip count of the loop.
2148 //
2149 // Currently we check for this by checking to see if the Exit branch goes to
2150 // the loop header. If so, we know it will always execute the same number of
2151 // times as the loop. We also handle the case where the exit block *is* the
2152 // loop header. This is common for un-rotated loops. More extensive analysis
2153 // could be done to handle more cases here.
2154 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2155 ExitBr->getSuccessor(1) != L->getHeader() &&
2156 ExitBr->getParent() != L->getHeader())
2157 return UnknownValue;
2158
2159 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2160
Nick Lewyckyb3d24332008-02-21 08:34:02 +00002161 // If it's not an integer comparison then compute it the hard way.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002162 // Note that ICmpInst deals with pointer comparisons too so we must check
2163 // the type of the operand.
2164 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002165 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002166 ExitBr->getSuccessor(0) == ExitBlock);
2167
2168 // If the condition was exit on true, convert the condition to exit on false
2169 ICmpInst::Predicate Cond;
2170 if (ExitBr->getSuccessor(1) == ExitBlock)
2171 Cond = ExitCond->getPredicate();
2172 else
2173 Cond = ExitCond->getInversePredicate();
2174
2175 // Handle common loops like: for (X = "string"; *X; ++X)
2176 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2177 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2178 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002179 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002180 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2181 }
2182
2183 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2184 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2185
2186 // Try to evaluate any dependencies out of the loop.
2187 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2188 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2189 Tmp = getSCEVAtScope(RHS, L);
2190 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2191
2192 // At this point, we would like to compute how many iterations of the
2193 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002194 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2195 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002196 std::swap(LHS, RHS);
2197 Cond = ICmpInst::getSwappedPredicate(Cond);
2198 }
2199
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002200 // If we have a comparison of a chrec against a constant, try to use value
2201 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002202 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2203 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002204 if (AddRec->getLoop() == L) {
2205 // Form the comparison range using the constant of the correct type so
2206 // that the ConstantRange class knows to do a signed or unsigned
2207 // comparison.
2208 ConstantInt *CompVal = RHSC->getValue();
2209 const Type *RealTy = ExitCond->getOperand(0)->getType();
2210 CompVal = dyn_cast<ConstantInt>(
2211 ConstantExpr::getBitCast(CompVal, RealTy));
2212 if (CompVal) {
2213 // Form the constant range.
2214 ConstantRange CompRange(
2215 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2216
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002217 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002218 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2219 }
2220 }
2221
2222 switch (Cond) {
2223 case ICmpInst::ICMP_NE: { // while (X != Y)
2224 // Convert to: while (X-Y != 0)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002225 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002226 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2227 break;
2228 }
2229 case ICmpInst::ICMP_EQ: {
2230 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002231 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002232 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2233 break;
2234 }
2235 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002236 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2237 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002238 break;
2239 }
2240 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002241 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2242 getNotSCEV(RHS), L, true);
2243 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002244 break;
2245 }
2246 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002247 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2248 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002249 break;
2250 }
2251 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002252 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2253 getNotSCEV(RHS), L, false);
2254 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002255 break;
2256 }
2257 default:
2258#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002259 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002260 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002261 errs() << "[unsigned] ";
2262 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002263 << Instruction::getOpcodeName(Instruction::ICmp)
2264 << " " << *RHS << "\n";
2265#endif
2266 break;
2267 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002268 return
2269 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2270 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002271}
2272
2273static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002274EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2275 ScalarEvolution &SE) {
2276 SCEVHandle InVal = SE.getConstant(C);
2277 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002278 assert(isa<SCEVConstant>(Val) &&
2279 "Evaluation of SCEV at constant didn't fold correctly?");
2280 return cast<SCEVConstant>(Val)->getValue();
2281}
2282
2283/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2284/// and a GEP expression (missing the pointer index) indexing into it, return
2285/// the addressed element of the initializer or null if the index expression is
2286/// invalid.
2287static Constant *
2288GetAddressedElementFromGlobal(GlobalVariable *GV,
2289 const std::vector<ConstantInt*> &Indices) {
2290 Constant *Init = GV->getInitializer();
2291 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2292 uint64_t Idx = Indices[i]->getZExtValue();
2293 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2294 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2295 Init = cast<Constant>(CS->getOperand(Idx));
2296 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2297 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2298 Init = cast<Constant>(CA->getOperand(Idx));
2299 } else if (isa<ConstantAggregateZero>(Init)) {
2300 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2301 assert(Idx < STy->getNumElements() && "Bad struct index!");
2302 Init = Constant::getNullValue(STy->getElementType(Idx));
2303 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2304 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2305 Init = Constant::getNullValue(ATy->getElementType());
2306 } else {
2307 assert(0 && "Unknown constant aggregate type!");
2308 }
2309 return 0;
2310 } else {
2311 return 0; // Unknown initializer type
2312 }
2313 }
2314 return Init;
2315}
2316
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002317/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2318/// 'icmp op load X, cst', try to see if we can compute the backedge
2319/// execution count.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002320SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002321ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2322 const Loop *L,
2323 ICmpInst::Predicate predicate) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002324 if (LI->isVolatile()) return UnknownValue;
2325
2326 // Check to see if the loaded pointer is a getelementptr of a global.
2327 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2328 if (!GEP) return UnknownValue;
2329
2330 // Make sure that it is really a constant global we are gepping, with an
2331 // initializer, and make sure the first IDX is really 0.
2332 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2333 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2334 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2335 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2336 return UnknownValue;
2337
2338 // Okay, we allow one non-constant index into the GEP instruction.
2339 Value *VarIdx = 0;
2340 std::vector<ConstantInt*> Indexes;
2341 unsigned VarIdxNum = 0;
2342 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2343 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2344 Indexes.push_back(CI);
2345 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2346 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2347 VarIdx = GEP->getOperand(i);
2348 VarIdxNum = i-2;
2349 Indexes.push_back(0);
2350 }
2351
2352 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2353 // Check to see if X is a loop variant variable value now.
2354 SCEVHandle Idx = getSCEV(VarIdx);
2355 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2356 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2357
2358 // We can only recognize very limited forms of loop index expressions, in
2359 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002360 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002361 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2362 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2363 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2364 return UnknownValue;
2365
2366 unsigned MaxSteps = MaxBruteForceIterations;
2367 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2368 ConstantInt *ItCst =
2369 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002370 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002371
2372 // Form the GEP offset.
2373 Indexes[VarIdxNum] = Val;
2374
2375 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2376 if (Result == 0) break; // Cannot compute!
2377
2378 // Evaluate the condition for this iteration.
2379 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2380 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2381 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2382#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002383 errs() << "\n***\n*** Computed loop count " << *ItCst
2384 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2385 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002386#endif
2387 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002388 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002389 }
2390 }
2391 return UnknownValue;
2392}
2393
2394
2395/// CanConstantFold - Return true if we can constant fold an instruction of the
2396/// specified type, assuming that all operands were constants.
2397static bool CanConstantFold(const Instruction *I) {
2398 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2399 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2400 return true;
2401
2402 if (const CallInst *CI = dyn_cast<CallInst>(I))
2403 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002404 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002405 return false;
2406}
2407
2408/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2409/// in the loop that V is derived from. We allow arbitrary operations along the
2410/// way, but the operands of an operation must either be constants or a value
2411/// derived from a constant PHI. If this expression does not fit with these
2412/// constraints, return null.
2413static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2414 // If this is not an instruction, or if this is an instruction outside of the
2415 // loop, it can't be derived from a loop PHI.
2416 Instruction *I = dyn_cast<Instruction>(V);
2417 if (I == 0 || !L->contains(I->getParent())) return 0;
2418
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002419 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002420 if (L->getHeader() == I->getParent())
2421 return PN;
2422 else
2423 // We don't currently keep track of the control flow needed to evaluate
2424 // PHIs, so we cannot handle PHIs inside of loops.
2425 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002426 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002427
2428 // If we won't be able to constant fold this expression even if the operands
2429 // are constants, return early.
2430 if (!CanConstantFold(I)) return 0;
2431
2432 // Otherwise, we can evaluate this instruction if all of its operands are
2433 // constant or derived from a PHI node themselves.
2434 PHINode *PHI = 0;
2435 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2436 if (!(isa<Constant>(I->getOperand(Op)) ||
2437 isa<GlobalValue>(I->getOperand(Op)))) {
2438 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2439 if (P == 0) return 0; // Not evolving from PHI
2440 if (PHI == 0)
2441 PHI = P;
2442 else if (PHI != P)
2443 return 0; // Evolving from multiple different PHIs.
2444 }
2445
2446 // This is a expression evolving from a constant PHI!
2447 return PHI;
2448}
2449
2450/// EvaluateExpression - Given an expression that passes the
2451/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2452/// in the loop has the value PHIVal. If we can't fold this expression for some
2453/// reason, return null.
2454static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2455 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002456 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002457 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002458 Instruction *I = cast<Instruction>(V);
2459
2460 std::vector<Constant*> Operands;
2461 Operands.resize(I->getNumOperands());
2462
2463 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2464 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2465 if (Operands[i] == 0) return 0;
2466 }
2467
Chris Lattnerd6e56912007-12-10 22:53:04 +00002468 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2469 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2470 &Operands[0], Operands.size());
2471 else
2472 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2473 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002474}
2475
2476/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2477/// in the header of its containing loop, we know the loop executes a
2478/// constant number of times, and the PHI node is just a recurrence
2479/// involving constants, fold it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002480Constant *ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002481getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002482 std::map<PHINode*, Constant*>::iterator I =
2483 ConstantEvolutionLoopExitValue.find(PN);
2484 if (I != ConstantEvolutionLoopExitValue.end())
2485 return I->second;
2486
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002487 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002488 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2489
2490 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2491
2492 // Since the loop is canonicalized, the PHI node must have two entries. One
2493 // entry must be a constant (coming in from outside of the loop), and the
2494 // second must be derived from the same PHI.
2495 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2496 Constant *StartCST =
2497 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2498 if (StartCST == 0)
2499 return RetVal = 0; // Must be a constant.
2500
2501 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2502 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2503 if (PN2 != PN)
2504 return RetVal = 0; // Not derived from same PHI.
2505
2506 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002507 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002508 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2509
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002510 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002511 unsigned IterationNum = 0;
2512 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2513 if (IterationNum == NumIterations)
2514 return RetVal = PHIVal; // Got exit value!
2515
2516 // Compute the value of the PHI node for the next iteration.
2517 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2518 if (NextPHI == PHIVal)
2519 return RetVal = NextPHI; // Stopped evolving!
2520 if (NextPHI == 0)
2521 return 0; // Couldn't evaluate!
2522 PHIVal = NextPHI;
2523 }
2524}
2525
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002526/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002527/// constant number of times (the condition evolves only from constants),
2528/// try to evaluate a few iterations of the loop until we get the exit
2529/// condition gets a value of ExitWhen (true or false). If we cannot
2530/// evaluate the trip count of the loop, return UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002531SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002532ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002533 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2534 if (PN == 0) return UnknownValue;
2535
2536 // Since the loop is canonicalized, the PHI node must have two entries. One
2537 // entry must be a constant (coming in from outside of the loop), and the
2538 // second must be derived from the same PHI.
2539 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2540 Constant *StartCST =
2541 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2542 if (StartCST == 0) return UnknownValue; // Must be a constant.
2543
2544 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2545 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2546 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2547
2548 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2549 // the loop symbolically to determine when the condition gets a value of
2550 // "ExitWhen".
2551 unsigned IterationNum = 0;
2552 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2553 for (Constant *PHIVal = StartCST;
2554 IterationNum != MaxIterations; ++IterationNum) {
2555 ConstantInt *CondVal =
2556 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2557
2558 // Couldn't symbolically evaluate.
2559 if (!CondVal) return UnknownValue;
2560
2561 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2562 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2563 ++NumBruteForceTripCountsComputed;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002564 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002565 }
2566
2567 // Compute the value of the PHI node for the next iteration.
2568 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2569 if (NextPHI == 0 || NextPHI == PHIVal)
2570 return UnknownValue; // Couldn't evaluate or not making progress...
2571 PHIVal = NextPHI;
2572 }
2573
2574 // Too many iterations were needed to evaluate.
2575 return UnknownValue;
2576}
2577
2578/// getSCEVAtScope - Compute the value of the specified expression within the
2579/// indicated loop (which may be null to indicate in no loop). If the
2580/// expression cannot be evaluated, return UnknownValue.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002581SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002582 // FIXME: this should be turned into a virtual method on SCEV!
2583
2584 if (isa<SCEVConstant>(V)) return V;
2585
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002586 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002587 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002588 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002589 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002590 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002591 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2592 if (PHINode *PN = dyn_cast<PHINode>(I))
2593 if (PN->getParent() == LI->getHeader()) {
2594 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002595 // to see if the loop that contains it has a known backedge-taken
2596 // count. If so, we may be able to force computation of the exit
2597 // value.
2598 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002599 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002600 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002601 // Okay, we know how many times the containing loop executes. If
2602 // this is a constant evolving PHI node, get the final value at
2603 // the specified iteration number.
2604 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002605 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002606 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002607 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002608 }
2609 }
2610
2611 // Okay, this is an expression that we cannot symbolically evaluate
2612 // into a SCEV. Check to see if it's possible to symbolically evaluate
2613 // the arguments into constants, and if so, try to constant propagate the
2614 // result. This is particularly useful for computing loop exit values.
2615 if (CanConstantFold(I)) {
2616 std::vector<Constant*> Operands;
2617 Operands.reserve(I->getNumOperands());
2618 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2619 Value *Op = I->getOperand(i);
2620 if (Constant *C = dyn_cast<Constant>(Op)) {
2621 Operands.push_back(C);
2622 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002623 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00002624 // non-integer and non-pointer, don't even try to analyze them
2625 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00002626 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00002627 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002628
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002629 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002630 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00002631 Constant *C = SC->getValue();
2632 if (C->getType() != Op->getType())
2633 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2634 Op->getType(),
2635 false),
2636 C, Op->getType());
2637 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002638 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00002639 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
2640 if (C->getType() != Op->getType())
2641 C =
2642 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2643 Op->getType(),
2644 false),
2645 C, Op->getType());
2646 Operands.push_back(C);
2647 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002648 return V;
2649 } else {
2650 return V;
2651 }
2652 }
2653 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002654
2655 Constant *C;
2656 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2657 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2658 &Operands[0], Operands.size());
2659 else
2660 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2661 &Operands[0], Operands.size());
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002662 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002663 }
2664 }
2665
2666 // This is some other type of SCEVUnknown, just return it.
2667 return V;
2668 }
2669
Dan Gohmanc76b5452009-05-04 22:02:23 +00002670 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002671 // Avoid performing the look-up in the common case where the specified
2672 // expression has no loop-variant portions.
2673 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2674 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2675 if (OpAtScope != Comm->getOperand(i)) {
2676 if (OpAtScope == UnknownValue) return UnknownValue;
2677 // Okay, at least one of these operands is loop variant but might be
2678 // foldable. Build a new instance of the folded commutative expression.
2679 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2680 NewOps.push_back(OpAtScope);
2681
2682 for (++i; i != e; ++i) {
2683 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2684 if (OpAtScope == UnknownValue) return UnknownValue;
2685 NewOps.push_back(OpAtScope);
2686 }
2687 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002688 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002689 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002690 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002691 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002692 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002693 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002694 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002695 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002696 }
2697 }
2698 // If we got here, all operands are loop invariant.
2699 return Comm;
2700 }
2701
Dan Gohmanc76b5452009-05-04 22:02:23 +00002702 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Nick Lewycky35b56022009-01-13 09:18:58 +00002703 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002704 if (LHS == UnknownValue) return LHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002705 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002706 if (RHS == UnknownValue) return RHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002707 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2708 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002709 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002710 }
2711
2712 // If this is a loop recurrence for a loop that does not contain L, then we
2713 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002714 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002715 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2716 // To evaluate this recurrence, we need to know how many times the AddRec
2717 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002718 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2719 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002720
Eli Friedman7489ec92008-08-04 23:49:06 +00002721 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002722 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002723 }
2724 return UnknownValue;
2725 }
2726
Dan Gohmanc76b5452009-05-04 22:02:23 +00002727 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00002728 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2729 if (Op == UnknownValue) return Op;
2730 if (Op == Cast->getOperand())
2731 return Cast; // must be loop invariant
2732 return getZeroExtendExpr(Op, Cast->getType());
2733 }
2734
Dan Gohmanc76b5452009-05-04 22:02:23 +00002735 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00002736 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2737 if (Op == UnknownValue) return Op;
2738 if (Op == Cast->getOperand())
2739 return Cast; // must be loop invariant
2740 return getSignExtendExpr(Op, Cast->getType());
2741 }
2742
Dan Gohmanc76b5452009-05-04 22:02:23 +00002743 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00002744 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2745 if (Op == UnknownValue) return Op;
2746 if (Op == Cast->getOperand())
2747 return Cast; // must be loop invariant
2748 return getTruncateExpr(Op, Cast->getType());
2749 }
2750
2751 assert(0 && "Unknown SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002752}
2753
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002754/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2755/// at the specified scope in the program. The L value specifies a loop
2756/// nest to evaluate the expression at, where null is the top-level or a
2757/// specified loop is immediately inside of the loop.
2758///
2759/// This method can be used to compute the exit value for a variable defined
2760/// in a loop by querying what the value will hold in the parent loop.
2761///
2762/// If this value is not computable at this scope, a SCEVCouldNotCompute
2763/// object is returned.
2764SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2765 return getSCEVAtScope(getSCEV(V), L);
2766}
2767
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002768/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2769/// following equation:
2770///
2771/// A * X = B (mod N)
2772///
2773/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2774/// A and B isn't important.
2775///
2776/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2777static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2778 ScalarEvolution &SE) {
2779 uint32_t BW = A.getBitWidth();
2780 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2781 assert(A != 0 && "A must be non-zero.");
2782
2783 // 1. D = gcd(A, N)
2784 //
2785 // The gcd of A and N may have only one prime factor: 2. The number of
2786 // trailing zeros in A is its multiplicity
2787 uint32_t Mult2 = A.countTrailingZeros();
2788 // D = 2^Mult2
2789
2790 // 2. Check if B is divisible by D.
2791 //
2792 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2793 // is not less than multiplicity of this prime factor for D.
2794 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00002795 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002796
2797 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2798 // modulo (N / D).
2799 //
2800 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2801 // bit width during computations.
2802 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2803 APInt Mod(BW + 1, 0);
2804 Mod.set(BW - Mult2); // Mod = N / D
2805 APInt I = AD.multiplicativeInverse(Mod);
2806
2807 // 4. Compute the minimum unsigned root of the equation:
2808 // I * (B / D) mod (N / D)
2809 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2810
2811 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2812 // bits.
2813 return SE.getConstant(Result.trunc(BW));
2814}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002815
2816/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2817/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2818/// might be the same) or two SCEVCouldNotCompute objects.
2819///
2820static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00002821SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002822 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002823 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2824 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2825 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002826
2827 // We currently can only solve this if the coefficients are constants.
2828 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002829 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002830 return std::make_pair(CNC, CNC);
2831 }
2832
2833 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2834 const APInt &L = LC->getValue()->getValue();
2835 const APInt &M = MC->getValue()->getValue();
2836 const APInt &N = NC->getValue()->getValue();
2837 APInt Two(BitWidth, 2);
2838 APInt Four(BitWidth, 4);
2839
2840 {
2841 using namespace APIntOps;
2842 const APInt& C = L;
2843 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2844 // The B coefficient is M-N/2
2845 APInt B(M);
2846 B -= sdiv(N,Two);
2847
2848 // The A coefficient is N/2
2849 APInt A(N.sdiv(Two));
2850
2851 // Compute the B^2-4ac term.
2852 APInt SqrtTerm(B);
2853 SqrtTerm *= B;
2854 SqrtTerm -= Four * (A * C);
2855
2856 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2857 // integer value or else APInt::sqrt() will assert.
2858 APInt SqrtVal(SqrtTerm.sqrt());
2859
2860 // Compute the two solutions for the quadratic formula.
2861 // The divisions must be performed as signed divisions.
2862 APInt NegB(-B);
2863 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00002864 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002865 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00002866 return std::make_pair(CNC, CNC);
2867 }
2868
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002869 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2870 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2871
Dan Gohman89f85052007-10-22 18:31:58 +00002872 return std::make_pair(SE.getConstant(Solution1),
2873 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002874 } // end APIntOps namespace
2875}
2876
2877/// HowFarToZero - Return the number of times a backedge comparing the specified
2878/// value to zero will execute. If not computable, return UnknownValue
Dan Gohmanbff6b582009-05-04 22:30:44 +00002879SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002880 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00002881 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002882 // If the value is already zero, the branch will execute zero times.
2883 if (C->getValue()->isZero()) return C;
2884 return UnknownValue; // Otherwise it will loop infinitely.
2885 }
2886
Dan Gohmanbff6b582009-05-04 22:30:44 +00002887 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002888 if (!AddRec || AddRec->getLoop() != L)
2889 return UnknownValue;
2890
2891 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002892 // If this is an affine expression, the execution count of this branch is
2893 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002894 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002895 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002896 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002897 // equivalent to:
2898 //
2899 // Step*N = -Start (mod 2^BW)
2900 //
2901 // where BW is the common bit width of Start and Step.
2902
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002903 // Get the initial value for the loop.
2904 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2905 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002906
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002907 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002908
Dan Gohmanc76b5452009-05-04 22:02:23 +00002909 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002910 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002911
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002912 // First, handle unitary steps.
2913 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002914 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002915 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2916 return Start; // N = Start (as unsigned)
2917
2918 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002919 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002920 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002921 -StartC->getValue()->getValue(),
2922 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002923 }
2924 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2925 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2926 // the quadratic equation to solve it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002927 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
2928 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00002929 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2930 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002931 if (R1) {
2932#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002933 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
2934 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002935#endif
2936 // Pick the smallest positive root value.
2937 if (ConstantInt *CB =
2938 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2939 R1->getValue(), R2->getValue()))) {
2940 if (CB->getZExtValue() == false)
2941 std::swap(R1, R2); // R1 is the minimum root now.
2942
2943 // We can only use this value if the chrec ends up with an exact zero
2944 // value at this index. When solving for "X*X != 5", for example, we
2945 // should not accept a root of 2.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002946 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00002947 if (Val->isZero())
2948 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002949 }
2950 }
2951 }
2952
2953 return UnknownValue;
2954}
2955
2956/// HowFarToNonZero - Return the number of times a backedge checking the
2957/// specified value for nonzero will execute. If not computable, return
2958/// UnknownValue
Dan Gohmanbff6b582009-05-04 22:30:44 +00002959SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002960 // Loops that look like: while (X == 0) are very strange indeed. We don't
2961 // handle them yet except for the trivial case. This could be expanded in the
2962 // future as needed.
2963
2964 // If the value is a constant, check to see if it is known to be non-zero
2965 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002966 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00002967 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002968 return getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002969 return UnknownValue; // Otherwise it will loop infinitely.
2970 }
2971
2972 // We could implement others, but I really doubt anyone writes loops like
2973 // this, and if they did, they would already be constant folded.
2974 return UnknownValue;
2975}
2976
Dan Gohman1cddf972008-09-15 22:18:04 +00002977/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2978/// (which may not be an immediate predecessor) which has exactly one
2979/// successor from which BB is reachable, or null if no such block is
2980/// found.
2981///
2982BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002983ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00002984 // If the block has a unique predecessor, then there is no path from the
2985 // predecessor to the block that does not go through the direct edge
2986 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00002987 if (BasicBlock *Pred = BB->getSinglePredecessor())
2988 return Pred;
2989
2990 // A loop's header is defined to be a block that dominates the loop.
2991 // If the loop has a preheader, it must be a block that has exactly
2992 // one successor that can reach BB. This is slightly more strict
2993 // than necessary, but works if critical edges are split.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002994 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman1cddf972008-09-15 22:18:04 +00002995 return L->getLoopPreheader();
2996
2997 return 0;
2998}
2999
Dan Gohmancacd2012009-02-12 22:19:27 +00003000/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman1116ea72009-04-30 20:48:53 +00003001/// a conditional between LHS and RHS. This is used to help avoid max
3002/// expressions in loop trip counts.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003003bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman1116ea72009-04-30 20:48:53 +00003004 ICmpInst::Predicate Pred,
Dan Gohmanbff6b582009-05-04 22:30:44 +00003005 const SCEV *LHS, const SCEV *RHS) {
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003006 BasicBlock *Preheader = L->getLoopPreheader();
3007 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003008
Dan Gohmanab678fb2008-08-12 20:17:31 +00003009 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohman1cddf972008-09-15 22:18:04 +00003010 // there are predecessors that can be found that have unique successors
3011 // leading to the original header.
3012 for (; Preheader;
3013 PreheaderDest = Preheader,
3014 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00003015
3016 BranchInst *LoopEntryPredicate =
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003017 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00003018 if (!LoopEntryPredicate ||
3019 LoopEntryPredicate->isUnconditional())
3020 continue;
3021
3022 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3023 if (!ICI) continue;
3024
3025 // Now that we found a conditional branch that dominates the loop, check to
3026 // see if it is the comparison we are looking for.
3027 Value *PreCondLHS = ICI->getOperand(0);
3028 Value *PreCondRHS = ICI->getOperand(1);
3029 ICmpInst::Predicate Cond;
3030 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3031 Cond = ICI->getPredicate();
3032 else
3033 Cond = ICI->getInversePredicate();
3034
Dan Gohmancacd2012009-02-12 22:19:27 +00003035 if (Cond == Pred)
3036 ; // An exact match.
3037 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3038 ; // The actual condition is beyond sufficient.
3039 else
3040 // Check a few special cases.
3041 switch (Cond) {
3042 case ICmpInst::ICMP_UGT:
3043 if (Pred == ICmpInst::ICMP_ULT) {
3044 std::swap(PreCondLHS, PreCondRHS);
3045 Cond = ICmpInst::ICMP_ULT;
3046 break;
3047 }
3048 continue;
3049 case ICmpInst::ICMP_SGT:
3050 if (Pred == ICmpInst::ICMP_SLT) {
3051 std::swap(PreCondLHS, PreCondRHS);
3052 Cond = ICmpInst::ICMP_SLT;
3053 break;
3054 }
3055 continue;
3056 case ICmpInst::ICMP_NE:
3057 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3058 // so check for this case by checking if the NE is comparing against
3059 // a minimum or maximum constant.
3060 if (!ICmpInst::isTrueWhenEqual(Pred))
3061 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3062 const APInt &A = CI->getValue();
3063 switch (Pred) {
3064 case ICmpInst::ICMP_SLT:
3065 if (A.isMaxSignedValue()) break;
3066 continue;
3067 case ICmpInst::ICMP_SGT:
3068 if (A.isMinSignedValue()) break;
3069 continue;
3070 case ICmpInst::ICMP_ULT:
3071 if (A.isMaxValue()) break;
3072 continue;
3073 case ICmpInst::ICMP_UGT:
3074 if (A.isMinValue()) break;
3075 continue;
3076 default:
3077 continue;
3078 }
3079 Cond = ICmpInst::ICMP_NE;
3080 // NE is symmetric but the original comparison may not be. Swap
3081 // the operands if necessary so that they match below.
3082 if (isa<SCEVConstant>(LHS))
3083 std::swap(PreCondLHS, PreCondRHS);
3084 break;
3085 }
3086 continue;
3087 default:
3088 // We weren't able to reconcile the condition.
3089 continue;
3090 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003091
3092 if (!PreCondLHS->getType()->isInteger()) continue;
3093
3094 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3095 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3096 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003097 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3098 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohmanab678fb2008-08-12 20:17:31 +00003099 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003100 }
3101
Dan Gohmanab678fb2008-08-12 20:17:31 +00003102 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003103}
3104
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003105/// HowManyLessThans - Return the number of times a backedge containing the
3106/// specified less-than comparison will execute. If not computable, return
3107/// UnknownValue.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003108ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Dan Gohmanbff6b582009-05-04 22:30:44 +00003109HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3110 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003111 // Only handle: "ADDREC < LoopInvariant".
3112 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3113
Dan Gohmanbff6b582009-05-04 22:30:44 +00003114 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003115 if (!AddRec || AddRec->getLoop() != L)
3116 return UnknownValue;
3117
3118 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003119 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003120 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3121 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3122 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3123
3124 // TODO: handle non-constant strides.
3125 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3126 if (!CStep || CStep->isZero())
3127 return UnknownValue;
3128 if (CStep->getValue()->getValue() == 1) {
3129 // With unit stride, the iteration never steps past the limit value.
3130 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3131 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3132 // Test whether a positive iteration iteration can step past the limit
3133 // value and past the maximum value for its type in a single step.
3134 if (isSigned) {
3135 APInt Max = APInt::getSignedMaxValue(BitWidth);
3136 if ((Max - CStep->getValue()->getValue())
3137 .slt(CLimit->getValue()->getValue()))
3138 return UnknownValue;
3139 } else {
3140 APInt Max = APInt::getMaxValue(BitWidth);
3141 if ((Max - CStep->getValue()->getValue())
3142 .ult(CLimit->getValue()->getValue()))
3143 return UnknownValue;
3144 }
3145 } else
3146 // TODO: handle non-constant limit values below.
3147 return UnknownValue;
3148 } else
3149 // TODO: handle negative strides below.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003150 return UnknownValue;
3151
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003152 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3153 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3154 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00003155 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003156
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003157 // First, we get the value of the LHS in the first iteration: n
3158 SCEVHandle Start = AddRec->getOperand(0);
3159
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003160 // Determine the minimum constant start value.
3161 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3162 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3163 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003164
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003165 // If we know that the condition is true in order to enter the loop,
3166 // then we know that it will run exactly (m-n)/s times. Otherwise, we
3167 // only know if will execute (max(m,n)-n)/s times. In both cases, the
3168 // division must round up.
3169 SCEVHandle End = RHS;
3170 if (!isLoopGuardedByCond(L,
3171 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3172 getMinusSCEV(Start, Step), RHS))
3173 End = isSigned ? getSMaxExpr(RHS, Start)
3174 : getUMaxExpr(RHS, Start);
3175
3176 // Determine the maximum constant end value.
3177 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3178 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3179 APInt::getMaxValue(BitWidth));
3180
3181 // Finally, we subtract these two values and divide, rounding up, to get
3182 // the number of times the backedge is executed.
3183 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3184 getAddExpr(Step, NegOne)),
3185 Step);
3186
3187 // The maximum backedge count is similar, except using the minimum start
3188 // value and the maximum end value.
3189 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3190 MinStart),
3191 getAddExpr(Step, NegOne)),
3192 Step);
3193
3194 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003195 }
3196
3197 return UnknownValue;
3198}
3199
3200/// getNumIterationsInRange - Return the number of iterations of this loop that
3201/// produce values in the specified constant range. Another way of looking at
3202/// this is that it returns the first iteration number where the value is not in
3203/// the condition, thus computing the exit count. If the iteration count can't
3204/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00003205SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3206 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003207 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003208 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003209
3210 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003211 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003212 if (!SC->getValue()->isZero()) {
3213 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003214 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3215 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00003216 if (const SCEVAddRecExpr *ShiftedAddRec =
3217 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003218 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003219 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003220 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003221 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003222 }
3223
3224 // The only time we can solve this is when we have all constant indices.
3225 // Otherwise, we cannot determine the overflow conditions.
3226 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3227 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003228 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003229
3230
3231 // Okay at this point we know that all elements of the chrec are constants and
3232 // that the start element is zero.
3233
3234 // First check to see if the range contains zero. If not, the first
3235 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003236 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003237 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003238 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003239
3240 if (isAffine()) {
3241 // If this is an affine expression then we have this situation:
3242 // Solve {0,+,A} in Range === Ax in Range
3243
3244 // We know that zero is in the range. If A is positive then we know that
3245 // the upper value of the range must be the first possible exit value.
3246 // If A is negative then the lower of the range is the last possible loop
3247 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003248 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003249 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3250 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3251
3252 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003253 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003254 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3255
3256 // Evaluate at the exit value. If we really did fall out of the valid
3257 // range, then we computed our trip count, otherwise wrap around or other
3258 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003259 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003260 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003261 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003262
3263 // Ensure that the previous value is in the range. This is a sanity check.
3264 assert(Range.contains(
3265 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003266 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003267 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003268 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003269 } else if (isQuadratic()) {
3270 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3271 // quadratic equation to solve it. To do this, we must frame our problem in
3272 // terms of figuring out when zero is crossed, instead of when
3273 // Range.getUpper() is crossed.
3274 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003275 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3276 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003277
3278 // Next, solve the constructed addrec
3279 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003280 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003281 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3282 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003283 if (R1) {
3284 // Pick the smallest positive root value.
3285 if (ConstantInt *CB =
3286 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3287 R1->getValue(), R2->getValue()))) {
3288 if (CB->getZExtValue() == false)
3289 std::swap(R1, R2); // R1 is the minimum root now.
3290
3291 // Make sure the root is not off by one. The returned iteration should
3292 // not be in the range, but the previous one should be. When solving
3293 // for "X*X < 5", for example, we should not return a root of 2.
3294 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003295 R1->getValue(),
3296 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003297 if (Range.contains(R1Val->getValue())) {
3298 // The next iteration must be out of the range...
3299 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3300
Dan Gohman89f85052007-10-22 18:31:58 +00003301 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003302 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003303 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003304 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003305 }
3306
3307 // If R1 was not in the range, then it is a good return value. Make
3308 // sure that R1-1 WAS in the range though, just in case.
3309 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003310 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003311 if (Range.contains(R1Val->getValue()))
3312 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003313 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003314 }
3315 }
3316 }
3317
Dan Gohman0ad08b02009-04-18 17:58:19 +00003318 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003319}
3320
3321
3322
3323//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00003324// SCEVCallbackVH Class Implementation
3325//===----------------------------------------------------------------------===//
3326
3327void SCEVCallbackVH::deleted() {
3328 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3329 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3330 SE->ConstantEvolutionLoopExitValue.erase(PN);
3331 SE->Scalars.erase(getValPtr());
3332 // this now dangles!
3333}
3334
3335void SCEVCallbackVH::allUsesReplacedWith(Value *) {
3336 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3337
3338 // Forget all the expressions associated with users of the old value,
3339 // so that future queries will recompute the expressions using the new
3340 // value.
3341 SmallVector<User *, 16> Worklist;
3342 Value *Old = getValPtr();
3343 bool DeleteOld = false;
3344 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3345 UI != UE; ++UI)
3346 Worklist.push_back(*UI);
3347 while (!Worklist.empty()) {
3348 User *U = Worklist.pop_back_val();
3349 // Deleting the Old value will cause this to dangle. Postpone
3350 // that until everything else is done.
3351 if (U == Old) {
3352 DeleteOld = true;
3353 continue;
3354 }
3355 if (PHINode *PN = dyn_cast<PHINode>(U))
3356 SE->ConstantEvolutionLoopExitValue.erase(PN);
3357 if (SE->Scalars.erase(U))
3358 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3359 UI != UE; ++UI)
3360 Worklist.push_back(*UI);
3361 }
3362 if (DeleteOld) {
3363 if (PHINode *PN = dyn_cast<PHINode>(Old))
3364 SE->ConstantEvolutionLoopExitValue.erase(PN);
3365 SE->Scalars.erase(Old);
3366 // this now dangles!
3367 }
3368 // this may dangle!
3369}
3370
3371SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
3372 : CallbackVH(V), SE(se) {}
3373
3374//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003375// ScalarEvolution Class Implementation
3376//===----------------------------------------------------------------------===//
3377
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003378ScalarEvolution::ScalarEvolution()
3379 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3380}
3381
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003382bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003383 this->F = &F;
3384 LI = &getAnalysis<LoopInfo>();
3385 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003386 return false;
3387}
3388
3389void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003390 Scalars.clear();
3391 BackedgeTakenCounts.clear();
3392 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003393}
3394
3395void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3396 AU.setPreservesAll();
3397 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003398}
3399
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003400bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003401 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003402}
3403
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003404static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003405 const Loop *L) {
3406 // Print all inner loops first
3407 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3408 PrintLoopInfo(OS, SE, *I);
3409
Nick Lewyckye5da1912008-01-02 02:49:20 +00003410 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003411
Devang Patel02451fa2007-08-21 00:31:24 +00003412 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003413 L->getExitBlocks(ExitBlocks);
3414 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003415 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003416
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003417 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3418 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003419 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003420 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003421 }
3422
Nick Lewyckye5da1912008-01-02 02:49:20 +00003423 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003424}
3425
Dan Gohman13058cc2009-04-21 00:47:46 +00003426void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003427 // ScalarEvolution's implementaiton of the print method is to print
3428 // out SCEV values of all instructions that are interesting. Doing
3429 // this potentially causes it to create new SCEV objects though,
3430 // which technically conflicts with the const qualifier. This isn't
3431 // observable from outside the class though (the hasSCEV function
3432 // notwithstanding), so casting away the const isn't dangerous.
3433 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003434
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003435 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003436 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00003437 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003438 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003439 OS << " --> ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003440 SCEVHandle SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003441 SV->print(OS);
3442 OS << "\t\t";
3443
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003444 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003445 OS << "Exits: ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003446 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003447 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3448 OS << "<<Unknown>>";
3449 } else {
3450 OS << *ExitValue;
3451 }
3452 }
3453
3454
3455 OS << "\n";
3456 }
3457
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003458 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3459 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3460 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003461}
Dan Gohman13058cc2009-04-21 00:47:46 +00003462
3463void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3464 raw_os_ostream OS(o);
3465 print(OS, M);
3466}