blob: 1b3aae878958b622c7285a002c7e4f28f41a5556 [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
Evan Cheng98c073b2009-02-17 00:13:06 +0000319bool SCEVCommutativeExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
320 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
Evan Cheng98c073b2009-02-17 00:13:06 +0000362bool SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
363 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
364 if (!getOperand(i)->dominates(BB, DT))
365 return false;
366 }
367 return true;
368}
369
370
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000371SCEVHandle SCEVAddRecExpr::
372replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000373 const SCEVHandle &Conc,
374 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000376 SCEVHandle H =
377 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378 if (H != getOperand(i)) {
379 std::vector<SCEVHandle> NewOps;
380 NewOps.reserve(getNumOperands());
381 for (unsigned j = 0; j != i; ++j)
382 NewOps.push_back(getOperand(j));
383 NewOps.push_back(H);
384 for (++i; i != e; ++i)
385 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000386 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000387
Dan Gohman89f85052007-10-22 18:31:58 +0000388 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000389 }
390 }
391 return this;
392}
393
394
395bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
396 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
397 // contain L and if the start is invariant.
398 return !QueryLoop->contains(L->getHeader()) &&
399 getOperand(0)->isLoopInvariant(QueryLoop);
400}
401
402
Dan Gohman13058cc2009-04-21 00:47:46 +0000403void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404 OS << "{" << *Operands[0];
405 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
406 OS << ",+," << *Operands[i];
407 OS << "}<" << L->getHeader()->getName() + ">";
408}
409
410// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
411// value. Don't use a SCEVHandle here, or else the object will never be
412// deleted!
413static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
414
415SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
416
417bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
418 // All non-instruction values are loop invariant. All instructions are loop
419 // invariant if they are not contained in the specified loop.
420 if (Instruction *I = dyn_cast<Instruction>(V))
421 return !L->contains(I->getParent());
422 return true;
423}
424
Evan Cheng98c073b2009-02-17 00:13:06 +0000425bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
426 if (Instruction *I = dyn_cast<Instruction>(getValue()))
427 return DT->dominates(I->getParent(), BB);
428 return true;
429}
430
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000431const Type *SCEVUnknown::getType() const {
432 return V->getType();
433}
434
Dan Gohman13058cc2009-04-21 00:47:46 +0000435void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000436 WriteAsOperand(OS, V, false);
437}
438
439//===----------------------------------------------------------------------===//
440// SCEV Utilities
441//===----------------------------------------------------------------------===//
442
443namespace {
444 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
445 /// than the complexity of the RHS. This comparator is used to canonicalize
446 /// expressions.
447 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000448 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000449 return LHS->getSCEVType() < RHS->getSCEVType();
450 }
451 };
452}
453
454/// GroupByComplexity - Given a list of SCEV objects, order them by their
455/// complexity, and group objects of the same complexity together by value.
456/// When this routine is finished, we know that any duplicates in the vector are
457/// consecutive and that complexity is monotonically increasing.
458///
459/// Note that we go take special precautions to ensure that we get determinstic
460/// results from this routine. In other words, we don't want the results of
461/// this to depend on where the addresses of various SCEV objects happened to
462/// land in memory.
463///
464static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
465 if (Ops.size() < 2) return; // Noop
466 if (Ops.size() == 2) {
467 // This is the common case, which also happens to be trivially simple.
468 // Special case it.
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000469 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000470 std::swap(Ops[0], Ops[1]);
471 return;
472 }
473
474 // Do the rough sort by complexity.
475 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
476
477 // Now that we are sorted by complexity, group elements of the same
478 // complexity. Note that this is, at worst, N^2, but the vector is likely to
479 // be extremely short in practice. Note that we take this approach because we
480 // do not want to depend on the addresses of the objects we are grouping.
481 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000482 const SCEV *S = Ops[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000483 unsigned Complexity = S->getSCEVType();
484
485 // If there are any objects of the same complexity and same value as this
486 // one, group them.
487 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
488 if (Ops[j] == S) { // Found a duplicate.
489 // Move it to immediately after i'th element.
490 std::swap(Ops[i+1], Ops[j]);
491 ++i; // no need to rescan it.
492 if (i == e-2) return; // Done!
493 }
494 }
495 }
496}
497
498
499
500//===----------------------------------------------------------------------===//
501// Simple SCEV method implementations
502//===----------------------------------------------------------------------===//
503
Eli Friedman7489ec92008-08-04 23:49:06 +0000504/// BinomialCoefficient - Compute BC(It, K). The result has width W.
505// Assume, K > 0.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000506static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000507 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000508 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000509 // Handle the simplest case efficiently.
510 if (K == 1)
511 return SE.getTruncateOrZeroExtend(It, ResultTy);
512
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000513 // We are using the following formula for BC(It, K):
514 //
515 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
516 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000517 // Suppose, W is the bitwidth of the return value. We must be prepared for
518 // overflow. Hence, we must assure that the result of our computation is
519 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
520 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000521 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000522 // However, this code doesn't use exactly that formula; the formula it uses
523 // is something like the following, where T is the number of factors of 2 in
524 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
525 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000526 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000527 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000528 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000529 // This formula is trivially equivalent to the previous formula. However,
530 // this formula can be implemented much more efficiently. The trick is that
531 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
532 // arithmetic. To do exact division in modular arithmetic, all we have
533 // to do is multiply by the inverse. Therefore, this step can be done at
534 // width W.
535 //
536 // The next issue is how to safely do the division by 2^T. The way this
537 // is done is by doing the multiplication step at a width of at least W + T
538 // bits. This way, the bottom W+T bits of the product are accurate. Then,
539 // when we perform the division by 2^T (which is equivalent to a right shift
540 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
541 // truncated out after the division by 2^T.
542 //
543 // In comparison to just directly using the first formula, this technique
544 // is much more efficient; using the first formula requires W * K bits,
545 // but this formula less than W + K bits. Also, the first formula requires
546 // a division step, whereas this formula only requires multiplies and shifts.
547 //
548 // It doesn't matter whether the subtraction step is done in the calculation
549 // width or the input iteration count's width; if the subtraction overflows,
550 // the result must be zero anyway. We prefer here to do it in the width of
551 // the induction variable because it helps a lot for certain cases; CodeGen
552 // isn't smart enough to ignore the overflow, which leads to much less
553 // efficient code if the width of the subtraction is wider than the native
554 // register width.
555 //
556 // (It's possible to not widen at all by pulling out factors of 2 before
557 // the multiplication; for example, K=2 can be calculated as
558 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
559 // extra arithmetic, so it's not an obvious win, and it gets
560 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000561
Eli Friedman7489ec92008-08-04 23:49:06 +0000562 // Protection from insane SCEVs; this bound is conservative,
563 // but it probably doesn't matter.
564 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000565 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000566
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000567 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000568
Eli Friedman7489ec92008-08-04 23:49:06 +0000569 // Calculate K! / 2^T and T; we divide out the factors of two before
570 // multiplying for calculating K! / 2^T to avoid overflow.
571 // Other overflow doesn't matter because we only care about the bottom
572 // W bits of the result.
573 APInt OddFactorial(W, 1);
574 unsigned T = 1;
575 for (unsigned i = 3; i <= K; ++i) {
576 APInt Mult(W, i);
577 unsigned TwoFactors = Mult.countTrailingZeros();
578 T += TwoFactors;
579 Mult = Mult.lshr(TwoFactors);
580 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000581 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000582
Eli Friedman7489ec92008-08-04 23:49:06 +0000583 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000584 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000585
586 // Calcuate 2^T, at width T+W.
587 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
588
589 // Calculate the multiplicative inverse of K! / 2^T;
590 // this multiplication factor will perform the exact division by
591 // K! / 2^T.
592 APInt Mod = APInt::getSignedMinValue(W+1);
593 APInt MultiplyFactor = OddFactorial.zext(W+1);
594 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
595 MultiplyFactor = MultiplyFactor.trunc(W);
596
597 // Calculate the product, at width T+W
598 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
599 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
600 for (unsigned i = 1; i != K; ++i) {
601 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
602 Dividend = SE.getMulExpr(Dividend,
603 SE.getTruncateOrZeroExtend(S, CalculationTy));
604 }
605
606 // Divide by 2^T
607 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
608
609 // Truncate the result, and divide by K! / 2^T.
610
611 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
612 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000613}
614
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000615/// evaluateAtIteration - Return the value of this chain of recurrences at
616/// the specified iteration number. We can evaluate this recurrence by
617/// multiplying each element in the chain by the binomial coefficient
618/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
619///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000620/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000621///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000622/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000623///
Dan Gohman89f85052007-10-22 18:31:58 +0000624SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
625 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000627 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000628 // The computation is correct in the face of overflow provided that the
629 // multiplication is performed _after_ the evaluation of the binomial
630 // coefficient.
Dan Gohman01c2ee72009-04-16 03:18:22 +0000631 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000632 if (isa<SCEVCouldNotCompute>(Coeff))
633 return Coeff;
634
635 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000636 }
637 return Result;
638}
639
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640//===----------------------------------------------------------------------===//
641// SCEV Expression folder implementations
642//===----------------------------------------------------------------------===//
643
Dan Gohman9c8abcc2009-05-01 16:44:56 +0000644SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
645 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000646 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000647 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000648 assert(isSCEVable(Ty) &&
649 "This is not a conversion to a SCEVable type!");
650 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000651
Dan Gohmanc76b5452009-05-04 22:02:23 +0000652 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000653 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000654 ConstantExpr::getTrunc(SC->getValue(), Ty));
655
Dan Gohman1a5c4992009-04-22 16:20:48 +0000656 // trunc(trunc(x)) --> trunc(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000657 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000658 return getTruncateExpr(ST->getOperand(), Ty);
659
Nick Lewycky37d04642009-04-23 05:15:08 +0000660 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000661 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000662 return getTruncateOrSignExtend(SS->getOperand(), Ty);
663
664 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000665 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000666 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
667
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000668 // If the input value is a chrec scev made out of constants, truncate
669 // all of the constants.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000670 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000671 std::vector<SCEVHandle> Operands;
672 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
673 // FIXME: This should allow truncation of other expression types!
674 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman89f85052007-10-22 18:31:58 +0000675 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000676 else
677 break;
678 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman89f85052007-10-22 18:31:58 +0000679 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000680 }
681
682 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
683 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
684 return Result;
685}
686
Dan Gohman36d40922009-04-16 19:25:55 +0000687SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
688 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000689 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000690 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000691 assert(isSCEVable(Ty) &&
692 "This is not a conversion to a SCEVable type!");
693 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000694
Dan Gohmanc76b5452009-05-04 22:02:23 +0000695 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000696 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000697 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
698 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
699 return getUnknown(C);
700 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000701
Dan Gohman1a5c4992009-04-22 16:20:48 +0000702 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000703 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000704 return getZeroExtendExpr(SZ->getOperand(), Ty);
705
Dan Gohmana9dba962009-04-27 20:16:15 +0000706 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000707 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000708 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000709 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000710 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000711 if (AR->isAffine()) {
712 // Check whether the backedge-taken count is SCEVCouldNotCompute.
713 // Note that this serves two purposes: It filters out loops that are
714 // simply not analyzable, and it covers the case where this code is
715 // being called from within backedge-taken count analysis, such that
716 // attempting to ask for the backedge-taken count would likely result
717 // in infinite recursion. In the later case, the analysis code will
718 // cope with a conservative value, and it will take care to purge
719 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000720 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
721 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000722 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000723 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000724 SCEVHandle Start = AR->getStart();
725 SCEVHandle Step = AR->getStepRecurrence(*this);
726
727 // Check whether the backedge-taken count can be losslessly casted to
728 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000729 SCEVHandle CastedMaxBECount =
730 getTruncateOrZeroExtend(MaxBECount, Start->getType());
731 if (MaxBECount ==
732 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000733 const Type *WideTy =
734 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000735 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000736 SCEVHandle ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000737 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000738 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000739 SCEVHandle Add = getAddExpr(Start, ZMul);
740 if (getZeroExtendExpr(Add, WideTy) ==
741 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000742 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000743 getZeroExtendExpr(Step, WideTy))))
744 // Return the expression with the addrec on the outside.
745 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
746 getZeroExtendExpr(Step, Ty),
747 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000748
749 // Similar to above, only this time treat the step value as signed.
750 // This covers loops that count down.
751 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000752 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000753 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000754 Add = getAddExpr(Start, SMul);
755 if (getZeroExtendExpr(Add, WideTy) ==
756 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000757 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000758 getSignExtendExpr(Step, WideTy))))
759 // Return the expression with the addrec on the outside.
760 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
761 getSignExtendExpr(Step, Ty),
762 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000763 }
764 }
765 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000766
767 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
768 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
769 return Result;
770}
771
Dan Gohmana9dba962009-04-27 20:16:15 +0000772SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
773 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000774 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000775 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000776 assert(isSCEVable(Ty) &&
777 "This is not a conversion to a SCEVable type!");
778 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000779
Dan Gohmanc76b5452009-05-04 22:02:23 +0000780 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000781 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000782 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
783 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
784 return getUnknown(C);
785 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000786
Dan Gohman1a5c4992009-04-22 16:20:48 +0000787 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000788 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000789 return getSignExtendExpr(SS->getOperand(), Ty);
790
Dan Gohmana9dba962009-04-27 20:16:15 +0000791 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000792 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000793 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000794 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000795 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000796 if (AR->isAffine()) {
797 // Check whether the backedge-taken count is SCEVCouldNotCompute.
798 // Note that this serves two purposes: It filters out loops that are
799 // simply not analyzable, and it covers the case where this code is
800 // being called from within backedge-taken count analysis, such that
801 // attempting to ask for the backedge-taken count would likely result
802 // in infinite recursion. In the later case, the analysis code will
803 // cope with a conservative value, and it will take care to purge
804 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000805 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
806 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000807 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000808 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000809 SCEVHandle Start = AR->getStart();
810 SCEVHandle Step = AR->getStepRecurrence(*this);
811
812 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000813 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000814 SCEVHandle CastedMaxBECount =
815 getTruncateOrZeroExtend(MaxBECount, Start->getType());
816 if (MaxBECount ==
817 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000818 const Type *WideTy =
819 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000820 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000821 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000822 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000823 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000824 SCEVHandle Add = getAddExpr(Start, SMul);
825 if (getSignExtendExpr(Add, WideTy) ==
826 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000827 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000828 getSignExtendExpr(Step, WideTy))))
829 // Return the expression with the addrec on the outside.
830 return getAddRecExpr(getSignExtendExpr(Start, Ty),
831 getSignExtendExpr(Step, Ty),
832 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000833 }
834 }
835 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000836
837 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
838 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
839 return Result;
840}
841
842// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000843SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000844 assert(!Ops.empty() && "Cannot get empty add!");
845 if (Ops.size() == 1) return Ops[0];
846
847 // Sort by complexity, this groups all similar expression types together.
848 GroupByComplexity(Ops);
849
850 // If there are any constants, fold them together.
851 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +0000852 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000853 ++Idx;
854 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +0000855 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000856 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000857 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
858 RHSC->getValue()->getValue());
859 Ops[0] = getConstant(Fold);
860 Ops.erase(Ops.begin()+1); // Erase the folded element
861 if (Ops.size() == 1) return Ops[0];
862 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000863 }
864
865 // If we are left with a constant zero being added, strip it off.
866 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
867 Ops.erase(Ops.begin());
868 --Idx;
869 }
870 }
871
872 if (Ops.size() == 1) return Ops[0];
873
874 // Okay, check to see if the same value occurs in the operand list twice. If
875 // so, merge them together into an multiply expression. Since we sorted the
876 // list, these values are required to be adjacent.
877 const Type *Ty = Ops[0]->getType();
878 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
879 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
880 // Found a match, merge the two values into a multiply, and add any
881 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000882 SCEVHandle Two = getIntegerSCEV(2, Ty);
883 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000884 if (Ops.size() == 2)
885 return Mul;
886 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
887 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000888 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000889 }
890
891 // Now we know the first non-constant operand. Skip past any cast SCEVs.
892 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
893 ++Idx;
894
895 // If there are add operands they would be next.
896 if (Idx < Ops.size()) {
897 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +0000898 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000899 // If we have an add, expand the add operands onto the end of the operands
900 // list.
901 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
902 Ops.erase(Ops.begin()+Idx);
903 DeletedAdd = true;
904 }
905
906 // If we deleted at least one add, we added operands to the end of the list,
907 // and they are not necessarily sorted. Recurse to resort and resimplify
908 // any operands we just aquired.
909 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +0000910 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000911 }
912
913 // Skip over the add expression until we get to a multiply.
914 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
915 ++Idx;
916
917 // If we are adding something to a multiply expression, make sure the
918 // something is not already an operand of the multiply. If so, merge it into
919 // the multiply.
920 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000921 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000922 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000923 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000924 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
925 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
926 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
927 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
928 if (Mul->getNumOperands() != 2) {
929 // If the multiply has more than two operands, we must get the
930 // Y*Z term.
931 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
932 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000933 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934 }
Dan Gohman89f85052007-10-22 18:31:58 +0000935 SCEVHandle One = getIntegerSCEV(1, Ty);
936 SCEVHandle AddOne = getAddExpr(InnerMul, One);
937 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000938 if (Ops.size() == 2) return OuterMul;
939 if (AddOp < Idx) {
940 Ops.erase(Ops.begin()+AddOp);
941 Ops.erase(Ops.begin()+Idx-1);
942 } else {
943 Ops.erase(Ops.begin()+Idx);
944 Ops.erase(Ops.begin()+AddOp-1);
945 }
946 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000947 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000948 }
949
950 // Check this multiply against other multiplies being added together.
951 for (unsigned OtherMulIdx = Idx+1;
952 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
953 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000954 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000955 // If MulOp occurs in OtherMul, we can fold the two multiplies
956 // together.
957 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
958 OMulOp != e; ++OMulOp)
959 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
960 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
961 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
962 if (Mul->getNumOperands() != 2) {
963 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
964 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000965 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000966 }
967 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
968 if (OtherMul->getNumOperands() != 2) {
969 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
970 OtherMul->op_end());
971 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000972 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000973 }
Dan Gohman89f85052007-10-22 18:31:58 +0000974 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
975 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000976 if (Ops.size() == 2) return OuterMul;
977 Ops.erase(Ops.begin()+Idx);
978 Ops.erase(Ops.begin()+OtherMulIdx-1);
979 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000980 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000981 }
982 }
983 }
984 }
985
986 // If there are any add recurrences in the operands list, see if any other
987 // added values are loop invariant. If so, we can fold them into the
988 // recurrence.
989 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
990 ++Idx;
991
992 // Scan over all recurrences, trying to fold loop invariants into them.
993 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
994 // Scan all of the other operands to this add and add them to the vector if
995 // they are loop invariant w.r.t. the recurrence.
996 std::vector<SCEVHandle> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +0000997 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000998 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
999 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1000 LIOps.push_back(Ops[i]);
1001 Ops.erase(Ops.begin()+i);
1002 --i; --e;
1003 }
1004
1005 // If we found some loop invariants, fold them into the recurrence.
1006 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001007 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001008 LIOps.push_back(AddRec->getStart());
1009
1010 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001011 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012
Dan Gohman89f85052007-10-22 18:31:58 +00001013 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001014 // If all of the other operands were loop invariant, we are done.
1015 if (Ops.size() == 1) return NewRec;
1016
1017 // Otherwise, add the folded AddRec by the non-liv parts.
1018 for (unsigned i = 0;; ++i)
1019 if (Ops[i] == AddRec) {
1020 Ops[i] = NewRec;
1021 break;
1022 }
Dan Gohman89f85052007-10-22 18:31:58 +00001023 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001024 }
1025
1026 // Okay, if there weren't any loop invariants to be folded, check to see if
1027 // there are multiple AddRec's with the same loop induction variable being
1028 // added together. If so, we can fold them.
1029 for (unsigned OtherIdx = Idx+1;
1030 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1031 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001032 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001033 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1034 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1035 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1036 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1037 if (i >= NewOps.size()) {
1038 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1039 OtherAddRec->op_end());
1040 break;
1041 }
Dan Gohman89f85052007-10-22 18:31:58 +00001042 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043 }
Dan Gohman89f85052007-10-22 18:31:58 +00001044 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001045
1046 if (Ops.size() == 2) return NewAddRec;
1047
1048 Ops.erase(Ops.begin()+Idx);
1049 Ops.erase(Ops.begin()+OtherIdx-1);
1050 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001051 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001052 }
1053 }
1054
1055 // Otherwise couldn't fold anything into this recurrence. Move onto the
1056 // next one.
1057 }
1058
1059 // Okay, it looks like we really DO need an add expr. Check to see if we
1060 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001061 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001062 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1063 SCEVOps)];
1064 if (Result == 0) Result = new SCEVAddExpr(Ops);
1065 return Result;
1066}
1067
1068
Dan Gohman89f85052007-10-22 18:31:58 +00001069SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001070 assert(!Ops.empty() && "Cannot get empty mul!");
1071
1072 // Sort by complexity, this groups all similar expression types together.
1073 GroupByComplexity(Ops);
1074
1075 // If there are any constants, fold them together.
1076 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001077 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001078
1079 // C1*(C2+V) -> C1*C2 + C1*V
1080 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001081 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001082 if (Add->getNumOperands() == 2 &&
1083 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001084 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1085 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001086
1087
1088 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001089 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001090 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001091 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1092 RHSC->getValue()->getValue());
1093 Ops[0] = getConstant(Fold);
1094 Ops.erase(Ops.begin()+1); // Erase the folded element
1095 if (Ops.size() == 1) return Ops[0];
1096 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001097 }
1098
1099 // If we are left with a constant one being multiplied, strip it off.
1100 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1101 Ops.erase(Ops.begin());
1102 --Idx;
1103 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1104 // If we have a multiply of zero, it will always be zero.
1105 return Ops[0];
1106 }
1107 }
1108
1109 // Skip over the add expression until we get to a multiply.
1110 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1111 ++Idx;
1112
1113 if (Ops.size() == 1)
1114 return Ops[0];
1115
1116 // If there are mul operands inline them all into this expression.
1117 if (Idx < Ops.size()) {
1118 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001119 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001120 // If we have an mul, expand the mul operands onto the end of the operands
1121 // list.
1122 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1123 Ops.erase(Ops.begin()+Idx);
1124 DeletedMul = true;
1125 }
1126
1127 // If we deleted at least one mul, we added operands to the end of the list,
1128 // and they are not necessarily sorted. Recurse to resort and resimplify
1129 // any operands we just aquired.
1130 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001131 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001132 }
1133
1134 // If there are any add recurrences in the operands list, see if any other
1135 // added values are loop invariant. If so, we can fold them into the
1136 // recurrence.
1137 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1138 ++Idx;
1139
1140 // Scan over all recurrences, trying to fold loop invariants into them.
1141 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1142 // Scan all of the other operands to this mul and add them to the vector if
1143 // they are loop invariant w.r.t. the recurrence.
1144 std::vector<SCEVHandle> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001145 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1147 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1148 LIOps.push_back(Ops[i]);
1149 Ops.erase(Ops.begin()+i);
1150 --i; --e;
1151 }
1152
1153 // If we found some loop invariants, fold them into the recurrence.
1154 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001155 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001156 std::vector<SCEVHandle> NewOps;
1157 NewOps.reserve(AddRec->getNumOperands());
1158 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001159 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001160 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001161 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001162 } else {
1163 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1164 std::vector<SCEVHandle> MulOps(LIOps);
1165 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001166 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001167 }
1168 }
1169
Dan Gohman89f85052007-10-22 18:31:58 +00001170 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001171
1172 // If all of the other operands were loop invariant, we are done.
1173 if (Ops.size() == 1) return NewRec;
1174
1175 // Otherwise, multiply the folded AddRec by the non-liv parts.
1176 for (unsigned i = 0;; ++i)
1177 if (Ops[i] == AddRec) {
1178 Ops[i] = NewRec;
1179 break;
1180 }
Dan Gohman89f85052007-10-22 18:31:58 +00001181 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001182 }
1183
1184 // Okay, if there weren't any loop invariants to be folded, check to see if
1185 // there are multiple AddRec's with the same loop induction variable being
1186 // multiplied together. If so, we can fold them.
1187 for (unsigned OtherIdx = Idx+1;
1188 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1189 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001190 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001191 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1192 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001193 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001194 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001195 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001196 SCEVHandle B = F->getStepRecurrence(*this);
1197 SCEVHandle D = G->getStepRecurrence(*this);
1198 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1199 getMulExpr(G, B),
1200 getMulExpr(B, D));
1201 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1202 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001203 if (Ops.size() == 2) return NewAddRec;
1204
1205 Ops.erase(Ops.begin()+Idx);
1206 Ops.erase(Ops.begin()+OtherIdx-1);
1207 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001208 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001209 }
1210 }
1211
1212 // Otherwise couldn't fold anything into this recurrence. Move onto the
1213 // next one.
1214 }
1215
1216 // Okay, it looks like we really DO need an mul expr. Check to see if we
1217 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001218 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001219 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1220 SCEVOps)];
1221 if (Result == 0)
1222 Result = new SCEVMulExpr(Ops);
1223 return Result;
1224}
1225
Dan Gohman77841cd2009-05-04 22:23:18 +00001226SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1227 const SCEVHandle &RHS) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001228 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001229 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001230 return LHS; // X udiv 1 --> x
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001231
Dan Gohmanc76b5452009-05-04 22:02:23 +00001232 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001233 Constant *LHSCV = LHSC->getValue();
1234 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001235 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001236 }
1237 }
1238
Nick Lewycky35b56022009-01-13 09:18:58 +00001239 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1240
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001241 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1242 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001243 return Result;
1244}
1245
1246
1247/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1248/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001249SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001250 const SCEVHandle &Step, const Loop *L) {
1251 std::vector<SCEVHandle> Operands;
1252 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001253 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001254 if (StepChrec->getLoop() == L) {
1255 Operands.insert(Operands.end(), StepChrec->op_begin(),
1256 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001257 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001258 }
1259
1260 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001261 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001262}
1263
1264/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1265/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001266SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Nick Lewycky37d04642009-04-23 05:15:08 +00001267 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001268 if (Operands.size() == 1) return Operands[0];
1269
Dan Gohman7b560c42008-06-18 16:23:07 +00001270 if (Operands.back()->isZero()) {
1271 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001272 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001273 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274
Dan Gohman42936882008-08-08 18:33:12 +00001275 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001276 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001277 const Loop* NestedLoop = NestedAR->getLoop();
1278 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1279 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1280 NestedAR->op_end());
1281 SCEVHandle NestedARHandle(NestedAR);
1282 Operands[0] = NestedAR->getStart();
1283 NestedOperands[0] = getAddRecExpr(Operands, L);
1284 return getAddRecExpr(NestedOperands, NestedLoop);
1285 }
1286 }
1287
Dan Gohmanbff6b582009-05-04 22:30:44 +00001288 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1289 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001290 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1291 return Result;
1292}
1293
Nick Lewycky711640a2007-11-25 22:41:31 +00001294SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1295 const SCEVHandle &RHS) {
1296 std::vector<SCEVHandle> Ops;
1297 Ops.push_back(LHS);
1298 Ops.push_back(RHS);
1299 return getSMaxExpr(Ops);
1300}
1301
1302SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1303 assert(!Ops.empty() && "Cannot get empty smax!");
1304 if (Ops.size() == 1) return Ops[0];
1305
1306 // Sort by complexity, this groups all similar expression types together.
1307 GroupByComplexity(Ops);
1308
1309 // If there are any constants, fold them together.
1310 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001311 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001312 ++Idx;
1313 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001314 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001315 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001316 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001317 APIntOps::smax(LHSC->getValue()->getValue(),
1318 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001319 Ops[0] = getConstant(Fold);
1320 Ops.erase(Ops.begin()+1); // Erase the folded element
1321 if (Ops.size() == 1) return Ops[0];
1322 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001323 }
1324
1325 // If we are left with a constant -inf, strip it off.
1326 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1327 Ops.erase(Ops.begin());
1328 --Idx;
1329 }
1330 }
1331
1332 if (Ops.size() == 1) return Ops[0];
1333
1334 // Find the first SMax
1335 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1336 ++Idx;
1337
1338 // Check to see if one of the operands is an SMax. If so, expand its operands
1339 // onto our operand list, and recurse to simplify.
1340 if (Idx < Ops.size()) {
1341 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001342 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001343 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1344 Ops.erase(Ops.begin()+Idx);
1345 DeletedSMax = true;
1346 }
1347
1348 if (DeletedSMax)
1349 return getSMaxExpr(Ops);
1350 }
1351
1352 // Okay, check to see if the same value occurs in the operand list twice. If
1353 // so, delete one. Since we sorted the list, these values are required to
1354 // be adjacent.
1355 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1356 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1357 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1358 --i; --e;
1359 }
1360
1361 if (Ops.size() == 1) return Ops[0];
1362
1363 assert(!Ops.empty() && "Reduced smax down to nothing!");
1364
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001365 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001366 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001367 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewycky711640a2007-11-25 22:41:31 +00001368 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1369 SCEVOps)];
1370 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1371 return Result;
1372}
1373
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001374SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1375 const SCEVHandle &RHS) {
1376 std::vector<SCEVHandle> Ops;
1377 Ops.push_back(LHS);
1378 Ops.push_back(RHS);
1379 return getUMaxExpr(Ops);
1380}
1381
1382SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1383 assert(!Ops.empty() && "Cannot get empty umax!");
1384 if (Ops.size() == 1) return Ops[0];
1385
1386 // Sort by complexity, this groups all similar expression types together.
1387 GroupByComplexity(Ops);
1388
1389 // If there are any constants, fold them together.
1390 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001391 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001392 ++Idx;
1393 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001394 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001395 // We found two constants, fold them together!
1396 ConstantInt *Fold = ConstantInt::get(
1397 APIntOps::umax(LHSC->getValue()->getValue(),
1398 RHSC->getValue()->getValue()));
1399 Ops[0] = getConstant(Fold);
1400 Ops.erase(Ops.begin()+1); // Erase the folded element
1401 if (Ops.size() == 1) return Ops[0];
1402 LHSC = cast<SCEVConstant>(Ops[0]);
1403 }
1404
1405 // If we are left with a constant zero, strip it off.
1406 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1407 Ops.erase(Ops.begin());
1408 --Idx;
1409 }
1410 }
1411
1412 if (Ops.size() == 1) return Ops[0];
1413
1414 // Find the first UMax
1415 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1416 ++Idx;
1417
1418 // Check to see if one of the operands is a UMax. If so, expand its operands
1419 // onto our operand list, and recurse to simplify.
1420 if (Idx < Ops.size()) {
1421 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001422 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001423 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1424 Ops.erase(Ops.begin()+Idx);
1425 DeletedUMax = true;
1426 }
1427
1428 if (DeletedUMax)
1429 return getUMaxExpr(Ops);
1430 }
1431
1432 // Okay, check to see if the same value occurs in the operand list twice. If
1433 // so, delete one. Since we sorted the list, these values are required to
1434 // be adjacent.
1435 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1436 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1437 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1438 --i; --e;
1439 }
1440
1441 if (Ops.size() == 1) return Ops[0];
1442
1443 assert(!Ops.empty() && "Reduced umax down to nothing!");
1444
1445 // Okay, it looks like we really DO need a umax expr. Check to see if we
1446 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001447 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001448 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1449 SCEVOps)];
1450 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1451 return Result;
1452}
1453
Dan Gohman89f85052007-10-22 18:31:58 +00001454SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001455 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001456 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001457 if (isa<ConstantPointerNull>(V))
1458 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001459 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1460 if (Result == 0) Result = new SCEVUnknown(V);
1461 return Result;
1462}
1463
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001464//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001465// Basic SCEV Analysis and PHI Idiom Recognition Code
1466//
1467
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001468/// isSCEVable - Test if values of the given type are analyzable within
1469/// the SCEV framework. This primarily includes integer types, and it
1470/// can optionally include pointer types if the ScalarEvolution class
1471/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001472bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001473 // Integers are always SCEVable.
1474 if (Ty->isInteger())
1475 return true;
1476
1477 // Pointers are SCEVable if TargetData information is available
1478 // to provide pointer size information.
1479 if (isa<PointerType>(Ty))
1480 return TD != NULL;
1481
1482 // Otherwise it's not SCEVable.
1483 return false;
1484}
1485
1486/// getTypeSizeInBits - Return the size in bits of the specified type,
1487/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001488uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001489 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1490
1491 // If we have a TargetData, use it!
1492 if (TD)
1493 return TD->getTypeSizeInBits(Ty);
1494
1495 // Otherwise, we support only integer types.
1496 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1497 return Ty->getPrimitiveSizeInBits();
1498}
1499
1500/// getEffectiveSCEVType - Return a type with the same bitwidth as
1501/// the given type and which represents how SCEV will treat the given
1502/// type, for which isSCEVable must return true. For pointer types,
1503/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001504const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001505 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1506
1507 if (Ty->isInteger())
1508 return Ty;
1509
1510 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1511 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001512}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001513
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001514SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman0ad08b02009-04-18 17:58:19 +00001515 return UnknownValue;
1516}
1517
Dan Gohmand83d4af2009-05-04 22:20:30 +00001518/// hasSCEV - Return true if the SCEV for this value has already been
Edwin Török0e828d62009-05-01 08:33:47 +00001519/// computed.
1520bool ScalarEvolution::hasSCEV(Value *V) const {
1521 return Scalars.count(V);
1522}
1523
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001524/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1525/// expression and create a new one.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001526SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001527 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001528
Dan Gohmanbff6b582009-05-04 22:30:44 +00001529 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001530 if (I != Scalars.end()) return I->second;
1531 SCEVHandle S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00001532 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001533 return S;
1534}
1535
Dan Gohman01c2ee72009-04-16 03:18:22 +00001536/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1537/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001538SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1539 Ty = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001540 Constant *C;
1541 if (Val == 0)
1542 C = Constant::getNullValue(Ty);
1543 else if (Ty->isFloatingPoint())
1544 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1545 APFloat::IEEEdouble, Val));
1546 else
1547 C = ConstantInt::get(Ty, Val);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001548 return getUnknown(C);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001549}
1550
1551/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1552///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001553SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001554 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001555 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001556
1557 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001558 Ty = getEffectiveSCEVType(Ty);
1559 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001560}
1561
1562/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001563SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001564 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001565 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001566
1567 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001568 Ty = getEffectiveSCEVType(Ty);
1569 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001570 return getMinusSCEV(AllOnes, V);
1571}
1572
1573/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1574///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001575SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky37d04642009-04-23 05:15:08 +00001576 const SCEVHandle &RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001577 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001578 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001579}
1580
1581/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1582/// input value to the specified type. If the type must be extended, it is zero
1583/// extended.
1584SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001585ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001586 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001587 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001588 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1589 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001590 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001591 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001592 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001593 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001594 return getTruncateExpr(V, Ty);
1595 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001596}
1597
1598/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1599/// input value to the specified type. If the type must be extended, it is sign
1600/// extended.
1601SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001602ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001603 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001604 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001605 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1606 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001607 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001608 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001609 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001610 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001611 return getTruncateExpr(V, Ty);
1612 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001613}
1614
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001615/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1616/// the specified instruction and replaces any references to the symbolic value
1617/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001618void ScalarEvolution::
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001619ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1620 const SCEVHandle &NewVal) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001621 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
1622 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001623 if (SI == Scalars.end()) return;
1624
1625 SCEVHandle NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001626 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001627 if (NV == SI->second) return; // No change.
1628
1629 SI->second = NV; // Update the scalars map!
1630
1631 // Any instruction values that use this instruction might also need to be
1632 // updated!
1633 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1634 UI != E; ++UI)
1635 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1636}
1637
1638/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1639/// a loop header, making it a potential recurrence, or it doesn't.
1640///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001641SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001642 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001643 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001644 if (L->getHeader() == PN->getParent()) {
1645 // If it lives in the loop header, it has two incoming values, one
1646 // from outside the loop, and one from inside.
1647 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1648 unsigned BackEdge = IncomingEdge^1;
1649
1650 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001651 SCEVHandle SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001652 assert(Scalars.find(PN) == Scalars.end() &&
1653 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00001654 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001655
1656 // Using this symbolic name for the PHI, analyze the value coming around
1657 // the back-edge.
1658 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1659
1660 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1661 // has a special value for the first iteration of the loop.
1662
1663 // If the value coming around the backedge is an add with the symbolic
1664 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00001665 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001666 // If there is a single occurrence of the symbolic value, replace it
1667 // with a recurrence.
1668 unsigned FoundIndex = Add->getNumOperands();
1669 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1670 if (Add->getOperand(i) == SymbolicName)
1671 if (FoundIndex == e) {
1672 FoundIndex = i;
1673 break;
1674 }
1675
1676 if (FoundIndex != Add->getNumOperands()) {
1677 // Create an add with everything but the specified operand.
1678 std::vector<SCEVHandle> Ops;
1679 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1680 if (i != FoundIndex)
1681 Ops.push_back(Add->getOperand(i));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001682 SCEVHandle Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001683
1684 // This is not a valid addrec if the step amount is varying each
1685 // loop iteration, but is not itself an addrec in this loop.
1686 if (Accum->isLoopInvariant(L) ||
1687 (isa<SCEVAddRecExpr>(Accum) &&
1688 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1689 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001690 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001691
1692 // Okay, for the entire analysis of this edge we assumed the PHI
1693 // to be symbolic. We now need to go back and update all of the
1694 // entries for the scalars that use the PHI (except for the PHI
1695 // itself) to use the new analyzed value instead of the "symbolic"
1696 // value.
1697 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1698 return PHISCEV;
1699 }
1700 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00001701 } else if (const SCEVAddRecExpr *AddRec =
1702 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001703 // Otherwise, this could be a loop like this:
1704 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1705 // In this case, j = {1,+,1} and BEValue is j.
1706 // Because the other in-value of i (0) fits the evolution of BEValue
1707 // i really is an addrec evolution.
1708 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1709 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1710
1711 // If StartVal = j.start - j.stride, we can use StartVal as the
1712 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001713 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00001714 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001715 SCEVHandle PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001716 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001717
1718 // Okay, for the entire analysis of this edge we assumed the PHI
1719 // to be symbolic. We now need to go back and update all of the
1720 // entries for the scalars that use the PHI (except for the PHI
1721 // itself) to use the new analyzed value instead of the "symbolic"
1722 // value.
1723 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1724 return PHISCEV;
1725 }
1726 }
1727 }
1728
1729 return SymbolicName;
1730 }
1731
1732 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001733 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001734}
1735
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001736/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1737/// guaranteed to end in (at every loop iteration). It is, at the same time,
1738/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1739/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001740static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001741 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001742 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001743
Dan Gohmanc76b5452009-05-04 22:02:23 +00001744 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001745 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1746 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001747
Dan Gohmanc76b5452009-05-04 22:02:23 +00001748 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001749 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1750 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1751 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001752 }
1753
Dan Gohmanc76b5452009-05-04 22:02:23 +00001754 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001755 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1756 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1757 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001758 }
1759
Dan Gohmanc76b5452009-05-04 22:02:23 +00001760 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001761 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001762 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001763 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001764 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001765 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001766 }
1767
Dan Gohmanc76b5452009-05-04 22:02:23 +00001768 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001769 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001770 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1771 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001772 for (unsigned i = 1, e = M->getNumOperands();
1773 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001774 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001775 BitWidth);
1776 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001777 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001778
Dan Gohmanc76b5452009-05-04 22:02:23 +00001779 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001780 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001781 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001782 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001783 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001784 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001785 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001786
Dan Gohmanc76b5452009-05-04 22:02:23 +00001787 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001788 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001789 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00001790 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001791 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00001792 return MinOpRes;
1793 }
1794
Dan Gohmanc76b5452009-05-04 22:02:23 +00001795 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001796 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001797 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001798 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001799 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001800 return MinOpRes;
1801 }
1802
Nick Lewycky35b56022009-01-13 09:18:58 +00001803 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001804 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001805}
1806
1807/// createSCEV - We know that there is no SCEV for the specified value.
1808/// Analyze the expression.
1809///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001810SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001811 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001812 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001813
Dan Gohman3996f472008-06-22 19:56:46 +00001814 unsigned Opcode = Instruction::UserOp1;
1815 if (Instruction *I = dyn_cast<Instruction>(V))
1816 Opcode = I->getOpcode();
1817 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1818 Opcode = CE->getOpcode();
1819 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001820 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001821
Dan Gohman3996f472008-06-22 19:56:46 +00001822 User *U = cast<User>(V);
1823 switch (Opcode) {
1824 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001825 return getAddExpr(getSCEV(U->getOperand(0)),
1826 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001827 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001828 return getMulExpr(getSCEV(U->getOperand(0)),
1829 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001830 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001831 return getUDivExpr(getSCEV(U->getOperand(0)),
1832 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001833 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001834 return getMinusSCEV(getSCEV(U->getOperand(0)),
1835 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00001836 case Instruction::And:
1837 // For an expression like x&255 that merely masks off the high bits,
1838 // use zext(trunc(x)) as the SCEV expression.
1839 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00001840 if (CI->isNullValue())
1841 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00001842 if (CI->isAllOnesValue())
1843 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00001844 const APInt &A = CI->getValue();
1845 unsigned Ones = A.countTrailingOnes();
1846 if (APIntOps::isMask(Ones, A))
1847 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001848 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
1849 IntegerType::get(Ones)),
1850 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00001851 }
1852 break;
Dan Gohman3996f472008-06-22 19:56:46 +00001853 case Instruction::Or:
1854 // If the RHS of the Or is a constant, we may have something like:
1855 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1856 // optimizations will transparently handle this case.
1857 //
1858 // In order for this transformation to be safe, the LHS must be of the
1859 // form X*(2^n) and the Or constant must be less than 2^n.
1860 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1861 SCEVHandle LHS = getSCEV(U->getOperand(0));
1862 const APInt &CIVal = CI->getValue();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001863 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman3996f472008-06-22 19:56:46 +00001864 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001865 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001866 }
Dan Gohman3996f472008-06-22 19:56:46 +00001867 break;
1868 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00001869 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00001870 // If the RHS of the xor is a signbit, then this is just an add.
1871 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00001872 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001873 return getAddExpr(getSCEV(U->getOperand(0)),
1874 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001875
1876 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman3996f472008-06-22 19:56:46 +00001877 else if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001878 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman3996f472008-06-22 19:56:46 +00001879 }
1880 break;
1881
1882 case Instruction::Shl:
1883 // Turn shift left of a constant amount into a multiply.
1884 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1885 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1886 Constant *X = ConstantInt::get(
1887 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001888 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00001889 }
1890 break;
1891
Nick Lewycky7fd27892008-07-07 06:15:49 +00001892 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00001893 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00001894 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1895 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1896 Constant *X = ConstantInt::get(
1897 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001898 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001899 }
1900 break;
1901
Dan Gohman53bf64a2009-04-21 02:26:00 +00001902 case Instruction::AShr:
1903 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
1904 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
1905 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
1906 if (L->getOpcode() == Instruction::Shl &&
1907 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00001908 unsigned BitWidth = getTypeSizeInBits(U->getType());
1909 uint64_t Amt = BitWidth - CI->getZExtValue();
1910 if (Amt == BitWidth)
1911 return getSCEV(L->getOperand(0)); // shift by zero --> noop
1912 if (Amt > BitWidth)
1913 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00001914 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001915 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00001916 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00001917 U->getType());
1918 }
1919 break;
1920
Dan Gohman3996f472008-06-22 19:56:46 +00001921 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001922 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001923
1924 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001925 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001926
1927 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001928 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001929
1930 case Instruction::BitCast:
1931 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001932 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00001933 return getSCEV(U->getOperand(0));
1934 break;
1935
Dan Gohman01c2ee72009-04-16 03:18:22 +00001936 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001937 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001938 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001939 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00001940
1941 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001942 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001943 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1944 U->getType());
1945
1946 case Instruction::GetElementPtr: {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001947 if (!TD) break; // Without TD we can't analyze pointers.
1948 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001949 Value *Base = U->getOperand(0);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001950 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001951 gep_type_iterator GTI = gep_type_begin(U);
1952 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
1953 E = U->op_end();
1954 I != E; ++I) {
1955 Value *Index = *I;
1956 // Compute the (potentially symbolic) offset in bytes for this index.
1957 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1958 // For a struct, add the member offset.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001959 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001960 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1961 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001962 TotalOffset = getAddExpr(TotalOffset,
1963 getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001964 } else {
1965 // For an array, add the element offset, explicitly scaled.
1966 SCEVHandle LocalOffset = getSCEV(Index);
1967 if (!isa<PointerType>(LocalOffset->getType()))
1968 // Getelementptr indicies are signed.
1969 LocalOffset = getTruncateOrSignExtend(LocalOffset,
1970 IntPtrTy);
1971 LocalOffset =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001972 getMulExpr(LocalOffset,
1973 getIntegerSCEV(TD->getTypePaddedSize(*GTI),
1974 IntPtrTy));
1975 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001976 }
1977 }
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001978 return getAddExpr(getSCEV(Base), TotalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001979 }
1980
Dan Gohman3996f472008-06-22 19:56:46 +00001981 case Instruction::PHI:
1982 return createNodeForPHI(cast<PHINode>(U));
1983
1984 case Instruction::Select:
1985 // This could be a smax or umax that was lowered earlier.
1986 // Try to recover it.
1987 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1988 Value *LHS = ICI->getOperand(0);
1989 Value *RHS = ICI->getOperand(1);
1990 switch (ICI->getPredicate()) {
1991 case ICmpInst::ICMP_SLT:
1992 case ICmpInst::ICMP_SLE:
1993 std::swap(LHS, RHS);
1994 // fall through
1995 case ICmpInst::ICMP_SGT:
1996 case ICmpInst::ICMP_SGE:
1997 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001998 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00001999 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00002000 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002001 return getNotSCEV(getSMaxExpr(
2002 getNotSCEV(getSCEV(LHS)),
2003 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002004 break;
2005 case ICmpInst::ICMP_ULT:
2006 case ICmpInst::ICMP_ULE:
2007 std::swap(LHS, RHS);
2008 // fall through
2009 case ICmpInst::ICMP_UGT:
2010 case ICmpInst::ICMP_UGE:
2011 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002012 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002013 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2014 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002015 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2016 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002017 break;
2018 default:
2019 break;
2020 }
2021 }
2022
2023 default: // We cannot analyze this expression.
2024 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002025 }
2026
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002027 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002028}
2029
2030
2031
2032//===----------------------------------------------------------------------===//
2033// Iteration Count Computation Code
2034//
2035
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002036/// getBackedgeTakenCount - If the specified loop has a predictable
2037/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2038/// object. The backedge-taken count is the number of times the loop header
2039/// will be branched to from within the loop. This is one less than the
2040/// trip count of the loop, since it doesn't count the first iteration,
2041/// when the header is branched to from outside the loop.
2042///
2043/// Note that it is not valid to call this method on a loop without a
2044/// loop-invariant backedge-taken count (see
2045/// hasLoopInvariantBackedgeTakenCount).
2046///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002047SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002048 return getBackedgeTakenInfo(L).Exact;
2049}
2050
2051/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2052/// return the least SCEV value that is known never to be less than the
2053/// actual backedge taken count.
2054SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2055 return getBackedgeTakenInfo(L).Max;
2056}
2057
2058const ScalarEvolution::BackedgeTakenInfo &
2059ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002060 // Initially insert a CouldNotCompute for this loop. If the insertion
2061 // succeeds, procede to actually compute a backedge-taken count and
2062 // update the value. The temporary CouldNotCompute value tells SCEV
2063 // code elsewhere that it shouldn't attempt to request a new
2064 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002065 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002066 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2067 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002068 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2069 if (ItCount.Exact != UnknownValue) {
2070 assert(ItCount.Exact->isLoopInvariant(L) &&
2071 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002072 "Computed trip count isn't loop invariant for loop!");
2073 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002074
Dan Gohmana9dba962009-04-27 20:16:15 +00002075 // Update the value in the map.
2076 Pair.first->second = ItCount;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002077 } else if (isa<PHINode>(L->getHeader()->begin())) {
2078 // Only count loops that have phi nodes as not being computable.
2079 ++NumTripCountsNotComputed;
2080 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002081
2082 // Now that we know more about the trip count for this loop, forget any
2083 // existing SCEV values for PHI nodes in this loop since they are only
2084 // conservative estimates made without the benefit
2085 // of trip count information.
2086 if (ItCount.hasAnyInfo())
Dan Gohman94623022009-05-02 17:43:35 +00002087 forgetLoopPHIs(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002088 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002089 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002090}
2091
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002092/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002093/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002094/// ScalarEvolution's ability to compute a trip count, or if the loop
2095/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002096void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002097 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002098 forgetLoopPHIs(L);
2099}
2100
2101/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2102/// PHI nodes in the given loop. This is used when the trip count of
2103/// the loop may have changed.
2104void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002105 BasicBlock *Header = L->getHeader();
2106
2107 SmallVector<Instruction *, 16> Worklist;
2108 for (BasicBlock::iterator I = Header->begin();
Dan Gohman94623022009-05-02 17:43:35 +00002109 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Dan Gohmanbff6b582009-05-04 22:30:44 +00002110 Worklist.push_back(PN);
2111
2112 while (!Worklist.empty()) {
2113 Instruction *I = Worklist.pop_back_val();
2114 if (Scalars.erase(I))
2115 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2116 UI != UE; ++UI)
2117 Worklist.push_back(cast<Instruction>(UI));
2118 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002119}
2120
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002121/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2122/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002123ScalarEvolution::BackedgeTakenInfo
2124ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002125 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00002126 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002127 L->getExitBlocks(ExitBlocks);
2128 if (ExitBlocks.size() != 1) return UnknownValue;
2129
2130 // Okay, there is one exit block. Try to find the condition that causes the
2131 // loop to be exited.
2132 BasicBlock *ExitBlock = ExitBlocks[0];
2133
2134 BasicBlock *ExitingBlock = 0;
2135 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2136 PI != E; ++PI)
2137 if (L->contains(*PI)) {
2138 if (ExitingBlock == 0)
2139 ExitingBlock = *PI;
2140 else
2141 return UnknownValue; // More than one block exiting!
2142 }
2143 assert(ExitingBlock && "No exits from loop, something is broken!");
2144
2145 // Okay, we've computed the exiting block. See what condition causes us to
2146 // exit.
2147 //
2148 // FIXME: we should be able to handle switch instructions (with a single exit)
2149 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2150 if (ExitBr == 0) return UnknownValue;
2151 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2152
2153 // At this point, we know we have a conditional branch that determines whether
2154 // the loop is exited. However, we don't know if the branch is executed each
2155 // time through the loop. If not, then the execution count of the branch will
2156 // not be equal to the trip count of the loop.
2157 //
2158 // Currently we check for this by checking to see if the Exit branch goes to
2159 // the loop header. If so, we know it will always execute the same number of
2160 // times as the loop. We also handle the case where the exit block *is* the
2161 // loop header. This is common for un-rotated loops. More extensive analysis
2162 // could be done to handle more cases here.
2163 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2164 ExitBr->getSuccessor(1) != L->getHeader() &&
2165 ExitBr->getParent() != L->getHeader())
2166 return UnknownValue;
2167
2168 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2169
Nick Lewyckyb3d24332008-02-21 08:34:02 +00002170 // If it's not an integer comparison then compute it the hard way.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002171 // Note that ICmpInst deals with pointer comparisons too so we must check
2172 // the type of the operand.
2173 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002174 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002175 ExitBr->getSuccessor(0) == ExitBlock);
2176
2177 // If the condition was exit on true, convert the condition to exit on false
2178 ICmpInst::Predicate Cond;
2179 if (ExitBr->getSuccessor(1) == ExitBlock)
2180 Cond = ExitCond->getPredicate();
2181 else
2182 Cond = ExitCond->getInversePredicate();
2183
2184 // Handle common loops like: for (X = "string"; *X; ++X)
2185 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2186 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2187 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002188 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002189 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2190 }
2191
2192 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2193 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2194
2195 // Try to evaluate any dependencies out of the loop.
2196 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2197 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2198 Tmp = getSCEVAtScope(RHS, L);
2199 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2200
2201 // At this point, we would like to compute how many iterations of the
2202 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002203 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2204 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002205 std::swap(LHS, RHS);
2206 Cond = ICmpInst::getSwappedPredicate(Cond);
2207 }
2208
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002209 // If we have a comparison of a chrec against a constant, try to use value
2210 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002211 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2212 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002213 if (AddRec->getLoop() == L) {
2214 // Form the comparison range using the constant of the correct type so
2215 // that the ConstantRange class knows to do a signed or unsigned
2216 // comparison.
2217 ConstantInt *CompVal = RHSC->getValue();
2218 const Type *RealTy = ExitCond->getOperand(0)->getType();
2219 CompVal = dyn_cast<ConstantInt>(
2220 ConstantExpr::getBitCast(CompVal, RealTy));
2221 if (CompVal) {
2222 // Form the constant range.
2223 ConstantRange CompRange(
2224 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2225
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002226 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002227 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2228 }
2229 }
2230
2231 switch (Cond) {
2232 case ICmpInst::ICMP_NE: { // while (X != Y)
2233 // Convert to: while (X-Y != 0)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002234 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002235 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2236 break;
2237 }
2238 case ICmpInst::ICMP_EQ: {
2239 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002240 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002241 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2242 break;
2243 }
2244 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002245 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2246 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002247 break;
2248 }
2249 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002250 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2251 getNotSCEV(RHS), L, true);
2252 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002253 break;
2254 }
2255 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002256 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2257 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002258 break;
2259 }
2260 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002261 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2262 getNotSCEV(RHS), L, false);
2263 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002264 break;
2265 }
2266 default:
2267#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002268 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002269 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002270 errs() << "[unsigned] ";
2271 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002272 << Instruction::getOpcodeName(Instruction::ICmp)
2273 << " " << *RHS << "\n";
2274#endif
2275 break;
2276 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002277 return
2278 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2279 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002280}
2281
2282static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002283EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2284 ScalarEvolution &SE) {
2285 SCEVHandle InVal = SE.getConstant(C);
2286 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002287 assert(isa<SCEVConstant>(Val) &&
2288 "Evaluation of SCEV at constant didn't fold correctly?");
2289 return cast<SCEVConstant>(Val)->getValue();
2290}
2291
2292/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2293/// and a GEP expression (missing the pointer index) indexing into it, return
2294/// the addressed element of the initializer or null if the index expression is
2295/// invalid.
2296static Constant *
2297GetAddressedElementFromGlobal(GlobalVariable *GV,
2298 const std::vector<ConstantInt*> &Indices) {
2299 Constant *Init = GV->getInitializer();
2300 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2301 uint64_t Idx = Indices[i]->getZExtValue();
2302 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2303 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2304 Init = cast<Constant>(CS->getOperand(Idx));
2305 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2306 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2307 Init = cast<Constant>(CA->getOperand(Idx));
2308 } else if (isa<ConstantAggregateZero>(Init)) {
2309 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2310 assert(Idx < STy->getNumElements() && "Bad struct index!");
2311 Init = Constant::getNullValue(STy->getElementType(Idx));
2312 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2313 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2314 Init = Constant::getNullValue(ATy->getElementType());
2315 } else {
2316 assert(0 && "Unknown constant aggregate type!");
2317 }
2318 return 0;
2319 } else {
2320 return 0; // Unknown initializer type
2321 }
2322 }
2323 return Init;
2324}
2325
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002326/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2327/// 'icmp op load X, cst', try to see if we can compute the backedge
2328/// execution count.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002329SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002330ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2331 const Loop *L,
2332 ICmpInst::Predicate predicate) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002333 if (LI->isVolatile()) return UnknownValue;
2334
2335 // Check to see if the loaded pointer is a getelementptr of a global.
2336 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2337 if (!GEP) return UnknownValue;
2338
2339 // Make sure that it is really a constant global we are gepping, with an
2340 // initializer, and make sure the first IDX is really 0.
2341 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2342 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2343 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2344 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2345 return UnknownValue;
2346
2347 // Okay, we allow one non-constant index into the GEP instruction.
2348 Value *VarIdx = 0;
2349 std::vector<ConstantInt*> Indexes;
2350 unsigned VarIdxNum = 0;
2351 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2352 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2353 Indexes.push_back(CI);
2354 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2355 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2356 VarIdx = GEP->getOperand(i);
2357 VarIdxNum = i-2;
2358 Indexes.push_back(0);
2359 }
2360
2361 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2362 // Check to see if X is a loop variant variable value now.
2363 SCEVHandle Idx = getSCEV(VarIdx);
2364 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2365 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2366
2367 // We can only recognize very limited forms of loop index expressions, in
2368 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002369 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002370 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2371 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2372 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2373 return UnknownValue;
2374
2375 unsigned MaxSteps = MaxBruteForceIterations;
2376 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2377 ConstantInt *ItCst =
2378 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002379 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002380
2381 // Form the GEP offset.
2382 Indexes[VarIdxNum] = Val;
2383
2384 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2385 if (Result == 0) break; // Cannot compute!
2386
2387 // Evaluate the condition for this iteration.
2388 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2389 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2390 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2391#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002392 errs() << "\n***\n*** Computed loop count " << *ItCst
2393 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2394 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002395#endif
2396 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002397 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002398 }
2399 }
2400 return UnknownValue;
2401}
2402
2403
2404/// CanConstantFold - Return true if we can constant fold an instruction of the
2405/// specified type, assuming that all operands were constants.
2406static bool CanConstantFold(const Instruction *I) {
2407 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2408 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2409 return true;
2410
2411 if (const CallInst *CI = dyn_cast<CallInst>(I))
2412 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002413 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002414 return false;
2415}
2416
2417/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2418/// in the loop that V is derived from. We allow arbitrary operations along the
2419/// way, but the operands of an operation must either be constants or a value
2420/// derived from a constant PHI. If this expression does not fit with these
2421/// constraints, return null.
2422static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2423 // If this is not an instruction, or if this is an instruction outside of the
2424 // loop, it can't be derived from a loop PHI.
2425 Instruction *I = dyn_cast<Instruction>(V);
2426 if (I == 0 || !L->contains(I->getParent())) return 0;
2427
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002428 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002429 if (L->getHeader() == I->getParent())
2430 return PN;
2431 else
2432 // We don't currently keep track of the control flow needed to evaluate
2433 // PHIs, so we cannot handle PHIs inside of loops.
2434 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002435 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002436
2437 // If we won't be able to constant fold this expression even if the operands
2438 // are constants, return early.
2439 if (!CanConstantFold(I)) return 0;
2440
2441 // Otherwise, we can evaluate this instruction if all of its operands are
2442 // constant or derived from a PHI node themselves.
2443 PHINode *PHI = 0;
2444 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2445 if (!(isa<Constant>(I->getOperand(Op)) ||
2446 isa<GlobalValue>(I->getOperand(Op)))) {
2447 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2448 if (P == 0) return 0; // Not evolving from PHI
2449 if (PHI == 0)
2450 PHI = P;
2451 else if (PHI != P)
2452 return 0; // Evolving from multiple different PHIs.
2453 }
2454
2455 // This is a expression evolving from a constant PHI!
2456 return PHI;
2457}
2458
2459/// EvaluateExpression - Given an expression that passes the
2460/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2461/// in the loop has the value PHIVal. If we can't fold this expression for some
2462/// reason, return null.
2463static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2464 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002465 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002466 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002467 Instruction *I = cast<Instruction>(V);
2468
2469 std::vector<Constant*> Operands;
2470 Operands.resize(I->getNumOperands());
2471
2472 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2473 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2474 if (Operands[i] == 0) return 0;
2475 }
2476
Chris Lattnerd6e56912007-12-10 22:53:04 +00002477 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2478 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2479 &Operands[0], Operands.size());
2480 else
2481 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2482 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002483}
2484
2485/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2486/// in the header of its containing loop, we know the loop executes a
2487/// constant number of times, and the PHI node is just a recurrence
2488/// involving constants, fold it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002489Constant *ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002490getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002491 std::map<PHINode*, Constant*>::iterator I =
2492 ConstantEvolutionLoopExitValue.find(PN);
2493 if (I != ConstantEvolutionLoopExitValue.end())
2494 return I->second;
2495
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002496 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002497 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2498
2499 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2500
2501 // Since the loop is canonicalized, the PHI node must have two entries. One
2502 // entry must be a constant (coming in from outside of the loop), and the
2503 // second must be derived from the same PHI.
2504 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2505 Constant *StartCST =
2506 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2507 if (StartCST == 0)
2508 return RetVal = 0; // Must be a constant.
2509
2510 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2511 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2512 if (PN2 != PN)
2513 return RetVal = 0; // Not derived from same PHI.
2514
2515 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002516 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002517 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2518
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002519 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002520 unsigned IterationNum = 0;
2521 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2522 if (IterationNum == NumIterations)
2523 return RetVal = PHIVal; // Got exit value!
2524
2525 // Compute the value of the PHI node for the next iteration.
2526 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2527 if (NextPHI == PHIVal)
2528 return RetVal = NextPHI; // Stopped evolving!
2529 if (NextPHI == 0)
2530 return 0; // Couldn't evaluate!
2531 PHIVal = NextPHI;
2532 }
2533}
2534
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002535/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002536/// constant number of times (the condition evolves only from constants),
2537/// try to evaluate a few iterations of the loop until we get the exit
2538/// condition gets a value of ExitWhen (true or false). If we cannot
2539/// evaluate the trip count of the loop, return UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002540SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002541ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002542 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2543 if (PN == 0) return UnknownValue;
2544
2545 // Since the loop is canonicalized, the PHI node must have two entries. One
2546 // entry must be a constant (coming in from outside of the loop), and the
2547 // second must be derived from the same PHI.
2548 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2549 Constant *StartCST =
2550 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2551 if (StartCST == 0) return UnknownValue; // Must be a constant.
2552
2553 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2554 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2555 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2556
2557 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2558 // the loop symbolically to determine when the condition gets a value of
2559 // "ExitWhen".
2560 unsigned IterationNum = 0;
2561 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2562 for (Constant *PHIVal = StartCST;
2563 IterationNum != MaxIterations; ++IterationNum) {
2564 ConstantInt *CondVal =
2565 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2566
2567 // Couldn't symbolically evaluate.
2568 if (!CondVal) return UnknownValue;
2569
2570 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2571 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2572 ++NumBruteForceTripCountsComputed;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002573 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002574 }
2575
2576 // Compute the value of the PHI node for the next iteration.
2577 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2578 if (NextPHI == 0 || NextPHI == PHIVal)
2579 return UnknownValue; // Couldn't evaluate or not making progress...
2580 PHIVal = NextPHI;
2581 }
2582
2583 // Too many iterations were needed to evaluate.
2584 return UnknownValue;
2585}
2586
2587/// getSCEVAtScope - Compute the value of the specified expression within the
2588/// indicated loop (which may be null to indicate in no loop). If the
2589/// expression cannot be evaluated, return UnknownValue.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002590SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002591 // FIXME: this should be turned into a virtual method on SCEV!
2592
2593 if (isa<SCEVConstant>(V)) return V;
2594
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002595 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002596 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002597 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002598 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002599 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002600 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2601 if (PHINode *PN = dyn_cast<PHINode>(I))
2602 if (PN->getParent() == LI->getHeader()) {
2603 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002604 // to see if the loop that contains it has a known backedge-taken
2605 // count. If so, we may be able to force computation of the exit
2606 // value.
2607 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002608 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002609 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002610 // Okay, we know how many times the containing loop executes. If
2611 // this is a constant evolving PHI node, get the final value at
2612 // the specified iteration number.
2613 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002614 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002615 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002616 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002617 }
2618 }
2619
2620 // Okay, this is an expression that we cannot symbolically evaluate
2621 // into a SCEV. Check to see if it's possible to symbolically evaluate
2622 // the arguments into constants, and if so, try to constant propagate the
2623 // result. This is particularly useful for computing loop exit values.
2624 if (CanConstantFold(I)) {
2625 std::vector<Constant*> Operands;
2626 Operands.reserve(I->getNumOperands());
2627 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2628 Value *Op = I->getOperand(i);
2629 if (Constant *C = dyn_cast<Constant>(Op)) {
2630 Operands.push_back(C);
2631 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002632 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00002633 // non-integer and non-pointer, don't even try to analyze them
2634 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00002635 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00002636 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002637
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002638 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002639 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00002640 Constant *C = SC->getValue();
2641 if (C->getType() != Op->getType())
2642 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2643 Op->getType(),
2644 false),
2645 C, Op->getType());
2646 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002647 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00002648 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
2649 if (C->getType() != Op->getType())
2650 C =
2651 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2652 Op->getType(),
2653 false),
2654 C, Op->getType());
2655 Operands.push_back(C);
2656 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002657 return V;
2658 } else {
2659 return V;
2660 }
2661 }
2662 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002663
2664 Constant *C;
2665 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2666 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2667 &Operands[0], Operands.size());
2668 else
2669 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2670 &Operands[0], Operands.size());
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002671 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002672 }
2673 }
2674
2675 // This is some other type of SCEVUnknown, just return it.
2676 return V;
2677 }
2678
Dan Gohmanc76b5452009-05-04 22:02:23 +00002679 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002680 // Avoid performing the look-up in the common case where the specified
2681 // expression has no loop-variant portions.
2682 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2683 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2684 if (OpAtScope != Comm->getOperand(i)) {
2685 if (OpAtScope == UnknownValue) return UnknownValue;
2686 // Okay, at least one of these operands is loop variant but might be
2687 // foldable. Build a new instance of the folded commutative expression.
2688 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2689 NewOps.push_back(OpAtScope);
2690
2691 for (++i; i != e; ++i) {
2692 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2693 if (OpAtScope == UnknownValue) return UnknownValue;
2694 NewOps.push_back(OpAtScope);
2695 }
2696 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002697 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002698 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002699 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002700 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002701 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002702 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002703 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002704 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002705 }
2706 }
2707 // If we got here, all operands are loop invariant.
2708 return Comm;
2709 }
2710
Dan Gohmanc76b5452009-05-04 22:02:23 +00002711 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Nick Lewycky35b56022009-01-13 09:18:58 +00002712 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002713 if (LHS == UnknownValue) return LHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002714 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002715 if (RHS == UnknownValue) return RHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002716 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2717 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002718 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002719 }
2720
2721 // If this is a loop recurrence for a loop that does not contain L, then we
2722 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002723 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002724 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2725 // To evaluate this recurrence, we need to know how many times the AddRec
2726 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002727 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2728 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002729
Eli Friedman7489ec92008-08-04 23:49:06 +00002730 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002731 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002732 }
2733 return UnknownValue;
2734 }
2735
Dan Gohmanc76b5452009-05-04 22:02:23 +00002736 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00002737 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2738 if (Op == UnknownValue) return Op;
2739 if (Op == Cast->getOperand())
2740 return Cast; // must be loop invariant
2741 return getZeroExtendExpr(Op, Cast->getType());
2742 }
2743
Dan Gohmanc76b5452009-05-04 22:02:23 +00002744 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00002745 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2746 if (Op == UnknownValue) return Op;
2747 if (Op == Cast->getOperand())
2748 return Cast; // must be loop invariant
2749 return getSignExtendExpr(Op, Cast->getType());
2750 }
2751
Dan Gohmanc76b5452009-05-04 22:02:23 +00002752 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00002753 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2754 if (Op == UnknownValue) return Op;
2755 if (Op == Cast->getOperand())
2756 return Cast; // must be loop invariant
2757 return getTruncateExpr(Op, Cast->getType());
2758 }
2759
2760 assert(0 && "Unknown SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002761}
2762
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002763/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2764/// at the specified scope in the program. The L value specifies a loop
2765/// nest to evaluate the expression at, where null is the top-level or a
2766/// specified loop is immediately inside of the loop.
2767///
2768/// This method can be used to compute the exit value for a variable defined
2769/// in a loop by querying what the value will hold in the parent loop.
2770///
2771/// If this value is not computable at this scope, a SCEVCouldNotCompute
2772/// object is returned.
2773SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2774 return getSCEVAtScope(getSCEV(V), L);
2775}
2776
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002777/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2778/// following equation:
2779///
2780/// A * X = B (mod N)
2781///
2782/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2783/// A and B isn't important.
2784///
2785/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2786static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2787 ScalarEvolution &SE) {
2788 uint32_t BW = A.getBitWidth();
2789 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2790 assert(A != 0 && "A must be non-zero.");
2791
2792 // 1. D = gcd(A, N)
2793 //
2794 // The gcd of A and N may have only one prime factor: 2. The number of
2795 // trailing zeros in A is its multiplicity
2796 uint32_t Mult2 = A.countTrailingZeros();
2797 // D = 2^Mult2
2798
2799 // 2. Check if B is divisible by D.
2800 //
2801 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2802 // is not less than multiplicity of this prime factor for D.
2803 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00002804 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002805
2806 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2807 // modulo (N / D).
2808 //
2809 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2810 // bit width during computations.
2811 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2812 APInt Mod(BW + 1, 0);
2813 Mod.set(BW - Mult2); // Mod = N / D
2814 APInt I = AD.multiplicativeInverse(Mod);
2815
2816 // 4. Compute the minimum unsigned root of the equation:
2817 // I * (B / D) mod (N / D)
2818 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2819
2820 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2821 // bits.
2822 return SE.getConstant(Result.trunc(BW));
2823}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002824
2825/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2826/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2827/// might be the same) or two SCEVCouldNotCompute objects.
2828///
2829static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00002830SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002831 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002832 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2833 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2834 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002835
2836 // We currently can only solve this if the coefficients are constants.
2837 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002838 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002839 return std::make_pair(CNC, CNC);
2840 }
2841
2842 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2843 const APInt &L = LC->getValue()->getValue();
2844 const APInt &M = MC->getValue()->getValue();
2845 const APInt &N = NC->getValue()->getValue();
2846 APInt Two(BitWidth, 2);
2847 APInt Four(BitWidth, 4);
2848
2849 {
2850 using namespace APIntOps;
2851 const APInt& C = L;
2852 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2853 // The B coefficient is M-N/2
2854 APInt B(M);
2855 B -= sdiv(N,Two);
2856
2857 // The A coefficient is N/2
2858 APInt A(N.sdiv(Two));
2859
2860 // Compute the B^2-4ac term.
2861 APInt SqrtTerm(B);
2862 SqrtTerm *= B;
2863 SqrtTerm -= Four * (A * C);
2864
2865 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2866 // integer value or else APInt::sqrt() will assert.
2867 APInt SqrtVal(SqrtTerm.sqrt());
2868
2869 // Compute the two solutions for the quadratic formula.
2870 // The divisions must be performed as signed divisions.
2871 APInt NegB(-B);
2872 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00002873 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002874 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00002875 return std::make_pair(CNC, CNC);
2876 }
2877
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002878 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2879 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2880
Dan Gohman89f85052007-10-22 18:31:58 +00002881 return std::make_pair(SE.getConstant(Solution1),
2882 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002883 } // end APIntOps namespace
2884}
2885
2886/// HowFarToZero - Return the number of times a backedge comparing the specified
2887/// value to zero will execute. If not computable, return UnknownValue
Dan Gohmanbff6b582009-05-04 22:30:44 +00002888SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002889 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00002890 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002891 // If the value is already zero, the branch will execute zero times.
2892 if (C->getValue()->isZero()) return C;
2893 return UnknownValue; // Otherwise it will loop infinitely.
2894 }
2895
Dan Gohmanbff6b582009-05-04 22:30:44 +00002896 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002897 if (!AddRec || AddRec->getLoop() != L)
2898 return UnknownValue;
2899
2900 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002901 // If this is an affine expression, the execution count of this branch is
2902 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002903 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002904 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002905 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002906 // equivalent to:
2907 //
2908 // Step*N = -Start (mod 2^BW)
2909 //
2910 // where BW is the common bit width of Start and Step.
2911
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002912 // Get the initial value for the loop.
2913 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2914 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002915
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002916 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002917
Dan Gohmanc76b5452009-05-04 22:02:23 +00002918 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002919 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002920
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002921 // First, handle unitary steps.
2922 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002923 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002924 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2925 return Start; // N = Start (as unsigned)
2926
2927 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002928 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002929 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002930 -StartC->getValue()->getValue(),
2931 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002932 }
2933 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2934 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2935 // the quadratic equation to solve it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002936 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
2937 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00002938 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2939 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002940 if (R1) {
2941#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002942 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
2943 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002944#endif
2945 // Pick the smallest positive root value.
2946 if (ConstantInt *CB =
2947 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2948 R1->getValue(), R2->getValue()))) {
2949 if (CB->getZExtValue() == false)
2950 std::swap(R1, R2); // R1 is the minimum root now.
2951
2952 // We can only use this value if the chrec ends up with an exact zero
2953 // value at this index. When solving for "X*X != 5", for example, we
2954 // should not accept a root of 2.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002955 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00002956 if (Val->isZero())
2957 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002958 }
2959 }
2960 }
2961
2962 return UnknownValue;
2963}
2964
2965/// HowFarToNonZero - Return the number of times a backedge checking the
2966/// specified value for nonzero will execute. If not computable, return
2967/// UnknownValue
Dan Gohmanbff6b582009-05-04 22:30:44 +00002968SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002969 // Loops that look like: while (X == 0) are very strange indeed. We don't
2970 // handle them yet except for the trivial case. This could be expanded in the
2971 // future as needed.
2972
2973 // If the value is a constant, check to see if it is known to be non-zero
2974 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002975 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00002976 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002977 return getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002978 return UnknownValue; // Otherwise it will loop infinitely.
2979 }
2980
2981 // We could implement others, but I really doubt anyone writes loops like
2982 // this, and if they did, they would already be constant folded.
2983 return UnknownValue;
2984}
2985
Dan Gohman1cddf972008-09-15 22:18:04 +00002986/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2987/// (which may not be an immediate predecessor) which has exactly one
2988/// successor from which BB is reachable, or null if no such block is
2989/// found.
2990///
2991BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002992ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00002993 // If the block has a unique predecessor, then there is no path from the
2994 // predecessor to the block that does not go through the direct edge
2995 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00002996 if (BasicBlock *Pred = BB->getSinglePredecessor())
2997 return Pred;
2998
2999 // A loop's header is defined to be a block that dominates the loop.
3000 // If the loop has a preheader, it must be a block that has exactly
3001 // one successor that can reach BB. This is slightly more strict
3002 // than necessary, but works if critical edges are split.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003003 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman1cddf972008-09-15 22:18:04 +00003004 return L->getLoopPreheader();
3005
3006 return 0;
3007}
3008
Dan Gohmancacd2012009-02-12 22:19:27 +00003009/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman1116ea72009-04-30 20:48:53 +00003010/// a conditional between LHS and RHS. This is used to help avoid max
3011/// expressions in loop trip counts.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003012bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman1116ea72009-04-30 20:48:53 +00003013 ICmpInst::Predicate Pred,
Dan Gohmanbff6b582009-05-04 22:30:44 +00003014 const SCEV *LHS, const SCEV *RHS) {
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003015 BasicBlock *Preheader = L->getLoopPreheader();
3016 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003017
Dan Gohmanab678fb2008-08-12 20:17:31 +00003018 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohman1cddf972008-09-15 22:18:04 +00003019 // there are predecessors that can be found that have unique successors
3020 // leading to the original header.
3021 for (; Preheader;
3022 PreheaderDest = Preheader,
3023 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00003024
3025 BranchInst *LoopEntryPredicate =
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003026 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00003027 if (!LoopEntryPredicate ||
3028 LoopEntryPredicate->isUnconditional())
3029 continue;
3030
3031 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3032 if (!ICI) continue;
3033
3034 // Now that we found a conditional branch that dominates the loop, check to
3035 // see if it is the comparison we are looking for.
3036 Value *PreCondLHS = ICI->getOperand(0);
3037 Value *PreCondRHS = ICI->getOperand(1);
3038 ICmpInst::Predicate Cond;
3039 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3040 Cond = ICI->getPredicate();
3041 else
3042 Cond = ICI->getInversePredicate();
3043
Dan Gohmancacd2012009-02-12 22:19:27 +00003044 if (Cond == Pred)
3045 ; // An exact match.
3046 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3047 ; // The actual condition is beyond sufficient.
3048 else
3049 // Check a few special cases.
3050 switch (Cond) {
3051 case ICmpInst::ICMP_UGT:
3052 if (Pred == ICmpInst::ICMP_ULT) {
3053 std::swap(PreCondLHS, PreCondRHS);
3054 Cond = ICmpInst::ICMP_ULT;
3055 break;
3056 }
3057 continue;
3058 case ICmpInst::ICMP_SGT:
3059 if (Pred == ICmpInst::ICMP_SLT) {
3060 std::swap(PreCondLHS, PreCondRHS);
3061 Cond = ICmpInst::ICMP_SLT;
3062 break;
3063 }
3064 continue;
3065 case ICmpInst::ICMP_NE:
3066 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3067 // so check for this case by checking if the NE is comparing against
3068 // a minimum or maximum constant.
3069 if (!ICmpInst::isTrueWhenEqual(Pred))
3070 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3071 const APInt &A = CI->getValue();
3072 switch (Pred) {
3073 case ICmpInst::ICMP_SLT:
3074 if (A.isMaxSignedValue()) break;
3075 continue;
3076 case ICmpInst::ICMP_SGT:
3077 if (A.isMinSignedValue()) break;
3078 continue;
3079 case ICmpInst::ICMP_ULT:
3080 if (A.isMaxValue()) break;
3081 continue;
3082 case ICmpInst::ICMP_UGT:
3083 if (A.isMinValue()) break;
3084 continue;
3085 default:
3086 continue;
3087 }
3088 Cond = ICmpInst::ICMP_NE;
3089 // NE is symmetric but the original comparison may not be. Swap
3090 // the operands if necessary so that they match below.
3091 if (isa<SCEVConstant>(LHS))
3092 std::swap(PreCondLHS, PreCondRHS);
3093 break;
3094 }
3095 continue;
3096 default:
3097 // We weren't able to reconcile the condition.
3098 continue;
3099 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003100
3101 if (!PreCondLHS->getType()->isInteger()) continue;
3102
3103 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3104 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3105 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003106 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3107 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohmanab678fb2008-08-12 20:17:31 +00003108 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003109 }
3110
Dan Gohmanab678fb2008-08-12 20:17:31 +00003111 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003112}
3113
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003114/// HowManyLessThans - Return the number of times a backedge containing the
3115/// specified less-than comparison will execute. If not computable, return
3116/// UnknownValue.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003117ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Dan Gohmanbff6b582009-05-04 22:30:44 +00003118HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3119 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003120 // Only handle: "ADDREC < LoopInvariant".
3121 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3122
Dan Gohmanbff6b582009-05-04 22:30:44 +00003123 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003124 if (!AddRec || AddRec->getLoop() != L)
3125 return UnknownValue;
3126
3127 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003128 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003129 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3130 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3131 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3132
3133 // TODO: handle non-constant strides.
3134 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3135 if (!CStep || CStep->isZero())
3136 return UnknownValue;
3137 if (CStep->getValue()->getValue() == 1) {
3138 // With unit stride, the iteration never steps past the limit value.
3139 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3140 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3141 // Test whether a positive iteration iteration can step past the limit
3142 // value and past the maximum value for its type in a single step.
3143 if (isSigned) {
3144 APInt Max = APInt::getSignedMaxValue(BitWidth);
3145 if ((Max - CStep->getValue()->getValue())
3146 .slt(CLimit->getValue()->getValue()))
3147 return UnknownValue;
3148 } else {
3149 APInt Max = APInt::getMaxValue(BitWidth);
3150 if ((Max - CStep->getValue()->getValue())
3151 .ult(CLimit->getValue()->getValue()))
3152 return UnknownValue;
3153 }
3154 } else
3155 // TODO: handle non-constant limit values below.
3156 return UnknownValue;
3157 } else
3158 // TODO: handle negative strides below.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003159 return UnknownValue;
3160
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003161 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3162 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3163 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00003164 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003165
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003166 // First, we get the value of the LHS in the first iteration: n
3167 SCEVHandle Start = AddRec->getOperand(0);
3168
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003169 // Determine the minimum constant start value.
3170 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3171 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3172 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003173
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003174 // If we know that the condition is true in order to enter the loop,
3175 // then we know that it will run exactly (m-n)/s times. Otherwise, we
3176 // only know if will execute (max(m,n)-n)/s times. In both cases, the
3177 // division must round up.
3178 SCEVHandle End = RHS;
3179 if (!isLoopGuardedByCond(L,
3180 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3181 getMinusSCEV(Start, Step), RHS))
3182 End = isSigned ? getSMaxExpr(RHS, Start)
3183 : getUMaxExpr(RHS, Start);
3184
3185 // Determine the maximum constant end value.
3186 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3187 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3188 APInt::getMaxValue(BitWidth));
3189
3190 // Finally, we subtract these two values and divide, rounding up, to get
3191 // the number of times the backedge is executed.
3192 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3193 getAddExpr(Step, NegOne)),
3194 Step);
3195
3196 // The maximum backedge count is similar, except using the minimum start
3197 // value and the maximum end value.
3198 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3199 MinStart),
3200 getAddExpr(Step, NegOne)),
3201 Step);
3202
3203 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003204 }
3205
3206 return UnknownValue;
3207}
3208
3209/// getNumIterationsInRange - Return the number of iterations of this loop that
3210/// produce values in the specified constant range. Another way of looking at
3211/// this is that it returns the first iteration number where the value is not in
3212/// the condition, thus computing the exit count. If the iteration count can't
3213/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00003214SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3215 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003216 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003217 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003218
3219 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003220 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003221 if (!SC->getValue()->isZero()) {
3222 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003223 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3224 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00003225 if (const SCEVAddRecExpr *ShiftedAddRec =
3226 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003227 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003228 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003229 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003230 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003231 }
3232
3233 // The only time we can solve this is when we have all constant indices.
3234 // Otherwise, we cannot determine the overflow conditions.
3235 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3236 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003237 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003238
3239
3240 // Okay at this point we know that all elements of the chrec are constants and
3241 // that the start element is zero.
3242
3243 // First check to see if the range contains zero. If not, the first
3244 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003245 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003246 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003247 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003248
3249 if (isAffine()) {
3250 // If this is an affine expression then we have this situation:
3251 // Solve {0,+,A} in Range === Ax in Range
3252
3253 // We know that zero is in the range. If A is positive then we know that
3254 // the upper value of the range must be the first possible exit value.
3255 // If A is negative then the lower of the range is the last possible loop
3256 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003257 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003258 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3259 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3260
3261 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003262 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003263 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3264
3265 // Evaluate at the exit value. If we really did fall out of the valid
3266 // range, then we computed our trip count, otherwise wrap around or other
3267 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003268 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003269 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003270 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003271
3272 // Ensure that the previous value is in the range. This is a sanity check.
3273 assert(Range.contains(
3274 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003275 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003276 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003277 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003278 } else if (isQuadratic()) {
3279 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3280 // quadratic equation to solve it. To do this, we must frame our problem in
3281 // terms of figuring out when zero is crossed, instead of when
3282 // Range.getUpper() is crossed.
3283 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003284 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3285 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003286
3287 // Next, solve the constructed addrec
3288 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003289 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003290 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3291 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003292 if (R1) {
3293 // Pick the smallest positive root value.
3294 if (ConstantInt *CB =
3295 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3296 R1->getValue(), R2->getValue()))) {
3297 if (CB->getZExtValue() == false)
3298 std::swap(R1, R2); // R1 is the minimum root now.
3299
3300 // Make sure the root is not off by one. The returned iteration should
3301 // not be in the range, but the previous one should be. When solving
3302 // for "X*X < 5", for example, we should not return a root of 2.
3303 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003304 R1->getValue(),
3305 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003306 if (Range.contains(R1Val->getValue())) {
3307 // The next iteration must be out of the range...
3308 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3309
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()))
Dan Gohman89f85052007-10-22 18:31:58 +00003312 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003313 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003314 }
3315
3316 // If R1 was not in the range, then it is a good return value. Make
3317 // sure that R1-1 WAS in the range though, just in case.
3318 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003319 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003320 if (Range.contains(R1Val->getValue()))
3321 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003322 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003323 }
3324 }
3325 }
3326
Dan Gohman0ad08b02009-04-18 17:58:19 +00003327 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003328}
3329
3330
3331
3332//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00003333// SCEVCallbackVH Class Implementation
3334//===----------------------------------------------------------------------===//
3335
3336void SCEVCallbackVH::deleted() {
3337 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3338 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3339 SE->ConstantEvolutionLoopExitValue.erase(PN);
3340 SE->Scalars.erase(getValPtr());
3341 // this now dangles!
3342}
3343
3344void SCEVCallbackVH::allUsesReplacedWith(Value *) {
3345 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3346
3347 // Forget all the expressions associated with users of the old value,
3348 // so that future queries will recompute the expressions using the new
3349 // value.
3350 SmallVector<User *, 16> Worklist;
3351 Value *Old = getValPtr();
3352 bool DeleteOld = false;
3353 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3354 UI != UE; ++UI)
3355 Worklist.push_back(*UI);
3356 while (!Worklist.empty()) {
3357 User *U = Worklist.pop_back_val();
3358 // Deleting the Old value will cause this to dangle. Postpone
3359 // that until everything else is done.
3360 if (U == Old) {
3361 DeleteOld = true;
3362 continue;
3363 }
3364 if (PHINode *PN = dyn_cast<PHINode>(U))
3365 SE->ConstantEvolutionLoopExitValue.erase(PN);
3366 if (SE->Scalars.erase(U))
3367 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3368 UI != UE; ++UI)
3369 Worklist.push_back(*UI);
3370 }
3371 if (DeleteOld) {
3372 if (PHINode *PN = dyn_cast<PHINode>(Old))
3373 SE->ConstantEvolutionLoopExitValue.erase(PN);
3374 SE->Scalars.erase(Old);
3375 // this now dangles!
3376 }
3377 // this may dangle!
3378}
3379
3380SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
3381 : CallbackVH(V), SE(se) {}
3382
3383//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003384// ScalarEvolution Class Implementation
3385//===----------------------------------------------------------------------===//
3386
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003387ScalarEvolution::ScalarEvolution()
3388 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3389}
3390
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003391bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003392 this->F = &F;
3393 LI = &getAnalysis<LoopInfo>();
3394 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003395 return false;
3396}
3397
3398void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003399 Scalars.clear();
3400 BackedgeTakenCounts.clear();
3401 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003402}
3403
3404void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3405 AU.setPreservesAll();
3406 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003407}
3408
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003409bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003410 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003411}
3412
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003413static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003414 const Loop *L) {
3415 // Print all inner loops first
3416 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3417 PrintLoopInfo(OS, SE, *I);
3418
Nick Lewyckye5da1912008-01-02 02:49:20 +00003419 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003420
Devang Patel02451fa2007-08-21 00:31:24 +00003421 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003422 L->getExitBlocks(ExitBlocks);
3423 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003424 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003425
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003426 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3427 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003428 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003429 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003430 }
3431
Nick Lewyckye5da1912008-01-02 02:49:20 +00003432 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003433}
3434
Dan Gohman13058cc2009-04-21 00:47:46 +00003435void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003436 // ScalarEvolution's implementaiton of the print method is to print
3437 // out SCEV values of all instructions that are interesting. Doing
3438 // this potentially causes it to create new SCEV objects though,
3439 // which technically conflicts with the const qualifier. This isn't
3440 // observable from outside the class though (the hasSCEV function
3441 // notwithstanding), so casting away the const isn't dangerous.
3442 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003443
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003444 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003445 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00003446 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003447 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003448 OS << " --> ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003449 SCEVHandle SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003450 SV->print(OS);
3451 OS << "\t\t";
3452
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003453 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003454 OS << "Exits: ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003455 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003456 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3457 OS << "<<Unknown>>";
3458 } else {
3459 OS << *ExitValue;
3460 }
3461 }
3462
3463
3464 OS << "\n";
3465 }
3466
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003467 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3468 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3469 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003470}
Dan Gohman13058cc2009-04-21 00:47:46 +00003471
3472void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3473 raw_os_ostream OS(o);
3474 print(OS, M);
3475}