blob: d34b898dbdf6757df453d9d21e5297a2c0780122 [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/Support/CommandLine.h"
74#include "llvm/Support/Compiler.h"
75#include "llvm/Support/ConstantRange.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000076#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000077#include "llvm/Support/InstIterator.h"
78#include "llvm/Support/ManagedStatic.h"
79#include "llvm/Support/MathExtras.h"
Dan Gohman13058cc2009-04-21 00:47:46 +000080#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081#include "llvm/ADT/Statistic.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000082#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083#include <ostream>
84#include <algorithm>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085using namespace llvm;
86
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087STATISTIC(NumArrayLenItCounts,
88 "Number of trip counts computed with array length");
89STATISTIC(NumTripCountsComputed,
90 "Number of loops with predictable loop counts");
91STATISTIC(NumTripCountsNotComputed,
92 "Number of loops without predictable loop counts");
93STATISTIC(NumBruteForceTripCountsComputed,
94 "Number of loops with trip counts computed by force");
95
Dan Gohman089efff2008-05-13 00:00:25 +000096static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000097MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
98 cl::desc("Maximum number of iterations SCEV will "
99 "symbolically execute a constant derived loop"),
100 cl::init(100));
101
Dan Gohman089efff2008-05-13 00:00:25 +0000102static RegisterPass<ScalarEvolution>
103R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000104char ScalarEvolution::ID = 0;
105
106//===----------------------------------------------------------------------===//
107// SCEV class definitions
108//===----------------------------------------------------------------------===//
109
110//===----------------------------------------------------------------------===//
111// Implementation of the SCEV class.
112//
113SCEV::~SCEV() {}
114void SCEV::dump() const {
Dan Gohman13058cc2009-04-21 00:47:46 +0000115 print(errs());
116 errs() << '\n';
117}
118
119void SCEV::print(std::ostream &o) const {
120 raw_os_ostream OS(o);
121 print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122}
123
Dan Gohman7b560c42008-06-18 16:23:07 +0000124bool SCEV::isZero() const {
125 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
126 return SC->getValue()->isZero();
127 return false;
128}
129
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000130
131SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
Dan Gohmanffd36ba2009-04-21 23:15:49 +0000132SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133
134bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
135 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
136 return false;
137}
138
139const Type *SCEVCouldNotCompute::getType() const {
140 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
141 return 0;
142}
143
144bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
145 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
146 return false;
147}
148
149SCEVHandle SCEVCouldNotCompute::
150replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000151 const SCEVHandle &Conc,
152 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153 return this;
154}
155
Dan Gohman13058cc2009-04-21 00:47:46 +0000156void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157 OS << "***COULDNOTCOMPUTE***";
158}
159
160bool SCEVCouldNotCompute::classof(const SCEV *S) {
161 return S->getSCEVType() == scCouldNotCompute;
162}
163
164
165// SCEVConstants - Only allow the creation of one SCEVConstant for any
166// particular value. Don't use a SCEVHandle here, or else the object will
167// never be deleted!
168static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
169
170
171SCEVConstant::~SCEVConstant() {
172 SCEVConstants->erase(V);
173}
174
Dan Gohman89f85052007-10-22 18:31:58 +0000175SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176 SCEVConstant *&R = (*SCEVConstants)[V];
177 if (R == 0) R = new SCEVConstant(V);
178 return R;
179}
180
Dan Gohman89f85052007-10-22 18:31:58 +0000181SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
182 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000183}
184
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185const Type *SCEVConstant::getType() const { return V->getType(); }
186
Dan Gohman13058cc2009-04-21 00:47:46 +0000187void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188 WriteAsOperand(OS, V, false);
189}
190
Dan Gohman2a381532009-04-21 01:25:57 +0000191SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
192 const SCEVHandle &op, const Type *ty)
193 : SCEV(SCEVTy), Op(op), Ty(ty) {}
194
195SCEVCastExpr::~SCEVCastExpr() {}
196
197bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
198 return Op->dominates(BB, DT);
199}
200
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000201// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
202// particular input. Don't use a SCEVHandle here, or else the object will
203// never be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000204static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205 SCEVTruncateExpr*> > SCEVTruncates;
206
207SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000208 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000209 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
210 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212}
213
214SCEVTruncateExpr::~SCEVTruncateExpr() {
215 SCEVTruncates->erase(std::make_pair(Op, Ty));
216}
217
Dan Gohman13058cc2009-04-21 00:47:46 +0000218void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000219 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220}
221
222// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
223// particular input. Don't use a SCEVHandle here, or else the object will never
224// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000225static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000226 SCEVZeroExtendExpr*> > SCEVZeroExtends;
227
228SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000229 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000230 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
231 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233}
234
235SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
236 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
237}
238
Dan Gohman13058cc2009-04-21 00:47:46 +0000239void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000240 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000241}
242
243// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
244// particular input. Don't use a SCEVHandle here, or else the object will never
245// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000246static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247 SCEVSignExtendExpr*> > SCEVSignExtends;
248
249SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000250 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000251 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
252 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254}
255
256SCEVSignExtendExpr::~SCEVSignExtendExpr() {
257 SCEVSignExtends->erase(std::make_pair(Op, Ty));
258}
259
Dan Gohman13058cc2009-04-21 00:47:46 +0000260void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000261 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262}
263
264// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
265// particular input. Don't use a SCEVHandle here, or else the object will never
266// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000267static ManagedStatic<std::map<std::pair<unsigned, std::vector<const SCEV*> >,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000268 SCEVCommutativeExpr*> > SCEVCommExprs;
269
270SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000271 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
272 SCEVCommExprs->erase(std::make_pair(getSCEVType(), SCEVOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273}
274
Dan Gohman13058cc2009-04-21 00:47:46 +0000275void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
277 const char *OpStr = getOperationStr();
278 OS << "(" << *Operands[0];
279 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
280 OS << OpStr << *Operands[i];
281 OS << ")";
282}
283
284SCEVHandle SCEVCommutativeExpr::
285replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000286 const SCEVHandle &Conc,
287 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000289 SCEVHandle H =
290 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000291 if (H != getOperand(i)) {
292 std::vector<SCEVHandle> NewOps;
293 NewOps.reserve(getNumOperands());
294 for (unsigned j = 0; j != i; ++j)
295 NewOps.push_back(getOperand(j));
296 NewOps.push_back(H);
297 for (++i; i != e; ++i)
298 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000299 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000300
301 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000302 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000303 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000304 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000305 else if (isa<SCEVSMaxExpr>(this))
306 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000307 else if (isa<SCEVUMaxExpr>(this))
308 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309 else
310 assert(0 && "Unknown commutative expr!");
311 }
312 }
313 return this;
314}
315
Dan Gohman72a8a022009-05-07 14:00:19 +0000316bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng98c073b2009-02-17 00:13:06 +0000317 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
318 if (!getOperand(i)->dominates(BB, DT))
319 return false;
320 }
321 return true;
322}
323
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000324
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000325// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000326// input. Don't use a SCEVHandle here, or else the object will never be
327// deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000328static ManagedStatic<std::map<std::pair<const SCEV*, const SCEV*>,
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000329 SCEVUDivExpr*> > SCEVUDivs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000331SCEVUDivExpr::~SCEVUDivExpr() {
332 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000333}
334
Evan Cheng98c073b2009-02-17 00:13:06 +0000335bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
336 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
337}
338
Dan Gohman13058cc2009-04-21 00:47:46 +0000339void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000340 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341}
342
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000343const Type *SCEVUDivExpr::getType() const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344 return LHS->getType();
345}
346
347// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
348// particular input. Don't use a SCEVHandle here, or else the object will never
349// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000350static ManagedStatic<std::map<std::pair<const Loop *,
351 std::vector<const SCEV*> >,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000352 SCEVAddRecExpr*> > SCEVAddRecExprs;
353
354SCEVAddRecExpr::~SCEVAddRecExpr() {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000355 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
356 SCEVAddRecExprs->erase(std::make_pair(L, SCEVOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357}
358
359SCEVHandle SCEVAddRecExpr::
360replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000361 const SCEVHandle &Conc,
362 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000364 SCEVHandle H =
365 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000366 if (H != getOperand(i)) {
367 std::vector<SCEVHandle> NewOps;
368 NewOps.reserve(getNumOperands());
369 for (unsigned j = 0; j != i; ++j)
370 NewOps.push_back(getOperand(j));
371 NewOps.push_back(H);
372 for (++i; i != e; ++i)
373 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000374 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375
Dan Gohman89f85052007-10-22 18:31:58 +0000376 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377 }
378 }
379 return this;
380}
381
382
383bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
384 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
385 // contain L and if the start is invariant.
386 return !QueryLoop->contains(L->getHeader()) &&
387 getOperand(0)->isLoopInvariant(QueryLoop);
388}
389
390
Dan Gohman13058cc2009-04-21 00:47:46 +0000391void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000392 OS << "{" << *Operands[0];
393 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
394 OS << ",+," << *Operands[i];
395 OS << "}<" << L->getHeader()->getName() + ">";
396}
397
398// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
399// value. Don't use a SCEVHandle here, or else the object will never be
400// deleted!
401static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
402
403SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
404
405bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
406 // All non-instruction values are loop invariant. All instructions are loop
407 // invariant if they are not contained in the specified loop.
408 if (Instruction *I = dyn_cast<Instruction>(V))
409 return !L->contains(I->getParent());
410 return true;
411}
412
Evan Cheng98c073b2009-02-17 00:13:06 +0000413bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
414 if (Instruction *I = dyn_cast<Instruction>(getValue()))
415 return DT->dominates(I->getParent(), BB);
416 return true;
417}
418
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000419const Type *SCEVUnknown::getType() const {
420 return V->getType();
421}
422
Dan Gohman13058cc2009-04-21 00:47:46 +0000423void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000424 WriteAsOperand(OS, V, false);
425}
426
427//===----------------------------------------------------------------------===//
428// SCEV Utilities
429//===----------------------------------------------------------------------===//
430
431namespace {
432 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
433 /// than the complexity of the RHS. This comparator is used to canonicalize
434 /// expressions.
Dan Gohman5d486452009-05-07 14:39:04 +0000435 class VISIBILITY_HIDDEN SCEVComplexityCompare {
436 LoopInfo *LI;
437 public:
438 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
439
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000440 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman5d486452009-05-07 14:39:04 +0000441 // Primarily, sort the SCEVs by their getSCEVType().
442 if (LHS->getSCEVType() != RHS->getSCEVType())
443 return LHS->getSCEVType() < RHS->getSCEVType();
444
445 // Aside from the getSCEVType() ordering, the particular ordering
446 // isn't very important except that it's beneficial to be consistent,
447 // so that (a + b) and (b + a) don't end up as different expressions.
448
449 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
450 // not as complete as it could be.
451 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
452 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
453
454 // Compare getValueID values.
455 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
456 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
457
458 // Sort arguments by their position.
459 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
460 const Argument *RA = cast<Argument>(RU->getValue());
461 return LA->getArgNo() < RA->getArgNo();
462 }
463
464 // For instructions, compare their loop depth, and their opcode.
465 // This is pretty loose.
466 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
467 Instruction *RV = cast<Instruction>(RU->getValue());
468
469 // Compare loop depths.
470 if (LI->getLoopDepth(LV->getParent()) !=
471 LI->getLoopDepth(RV->getParent()))
472 return LI->getLoopDepth(LV->getParent()) <
473 LI->getLoopDepth(RV->getParent());
474
475 // Compare opcodes.
476 if (LV->getOpcode() != RV->getOpcode())
477 return LV->getOpcode() < RV->getOpcode();
478
479 // Compare the number of operands.
480 if (LV->getNumOperands() != RV->getNumOperands())
481 return LV->getNumOperands() < RV->getNumOperands();
482 }
483
484 return false;
485 }
486
487 // Constant sorting doesn't matter since they'll be folded.
488 if (isa<SCEVConstant>(LHS))
489 return false;
490
491 // Lexicographically compare n-ary expressions.
492 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
493 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
494 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
495 if (i >= RC->getNumOperands())
496 return false;
497 if (operator()(LC->getOperand(i), RC->getOperand(i)))
498 return true;
499 if (operator()(RC->getOperand(i), LC->getOperand(i)))
500 return false;
501 }
502 return LC->getNumOperands() < RC->getNumOperands();
503 }
504
Dan Gohman6e10db12009-05-07 19:23:21 +0000505 // Lexicographically compare udiv expressions.
506 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
507 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
508 if (operator()(LC->getLHS(), RC->getLHS()))
509 return true;
510 if (operator()(RC->getLHS(), LC->getLHS()))
511 return false;
512 if (operator()(LC->getRHS(), RC->getRHS()))
513 return true;
514 if (operator()(RC->getRHS(), LC->getRHS()))
515 return false;
516 return false;
517 }
518
Dan Gohman5d486452009-05-07 14:39:04 +0000519 // Compare cast expressions by operand.
520 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
521 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
522 return operator()(LC->getOperand(), RC->getOperand());
523 }
524
525 assert(0 && "Unknown SCEV kind!");
526 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000527 }
528 };
529}
530
531/// GroupByComplexity - Given a list of SCEV objects, order them by their
532/// complexity, and group objects of the same complexity together by value.
533/// When this routine is finished, we know that any duplicates in the vector are
534/// consecutive and that complexity is monotonically increasing.
535///
536/// Note that we go take special precautions to ensure that we get determinstic
537/// results from this routine. In other words, we don't want the results of
538/// this to depend on where the addresses of various SCEV objects happened to
539/// land in memory.
540///
Dan Gohman5d486452009-05-07 14:39:04 +0000541static void GroupByComplexity(std::vector<SCEVHandle> &Ops,
542 LoopInfo *LI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000543 if (Ops.size() < 2) return; // Noop
544 if (Ops.size() == 2) {
545 // This is the common case, which also happens to be trivially simple.
546 // Special case it.
Dan Gohman5d486452009-05-07 14:39:04 +0000547 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000548 std::swap(Ops[0], Ops[1]);
549 return;
550 }
551
552 // Do the rough sort by complexity.
Dan Gohman5d486452009-05-07 14:39:04 +0000553 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000554
555 // Now that we are sorted by complexity, group elements of the same
556 // complexity. Note that this is, at worst, N^2, but the vector is likely to
557 // be extremely short in practice. Note that we take this approach because we
558 // do not want to depend on the addresses of the objects we are grouping.
559 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000560 const SCEV *S = Ops[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000561 unsigned Complexity = S->getSCEVType();
562
563 // If there are any objects of the same complexity and same value as this
564 // one, group them.
565 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
566 if (Ops[j] == S) { // Found a duplicate.
567 // Move it to immediately after i'th element.
568 std::swap(Ops[i+1], Ops[j]);
569 ++i; // no need to rescan it.
570 if (i == e-2) return; // Done!
571 }
572 }
573 }
574}
575
576
577
578//===----------------------------------------------------------------------===//
579// Simple SCEV method implementations
580//===----------------------------------------------------------------------===//
581
Eli Friedman7489ec92008-08-04 23:49:06 +0000582/// BinomialCoefficient - Compute BC(It, K). The result has width W.
583// Assume, K > 0.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000584static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000585 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000586 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000587 // Handle the simplest case efficiently.
588 if (K == 1)
589 return SE.getTruncateOrZeroExtend(It, ResultTy);
590
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000591 // We are using the following formula for BC(It, K):
592 //
593 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
594 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000595 // Suppose, W is the bitwidth of the return value. We must be prepared for
596 // overflow. Hence, we must assure that the result of our computation is
597 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
598 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000599 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000600 // However, this code doesn't use exactly that formula; the formula it uses
601 // is something like the following, where T is the number of factors of 2 in
602 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
603 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000604 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000605 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000606 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000607 // This formula is trivially equivalent to the previous formula. However,
608 // this formula can be implemented much more efficiently. The trick is that
609 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
610 // arithmetic. To do exact division in modular arithmetic, all we have
611 // to do is multiply by the inverse. Therefore, this step can be done at
612 // width W.
613 //
614 // The next issue is how to safely do the division by 2^T. The way this
615 // is done is by doing the multiplication step at a width of at least W + T
616 // bits. This way, the bottom W+T bits of the product are accurate. Then,
617 // when we perform the division by 2^T (which is equivalent to a right shift
618 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
619 // truncated out after the division by 2^T.
620 //
621 // In comparison to just directly using the first formula, this technique
622 // is much more efficient; using the first formula requires W * K bits,
623 // but this formula less than W + K bits. Also, the first formula requires
624 // a division step, whereas this formula only requires multiplies and shifts.
625 //
626 // It doesn't matter whether the subtraction step is done in the calculation
627 // width or the input iteration count's width; if the subtraction overflows,
628 // the result must be zero anyway. We prefer here to do it in the width of
629 // the induction variable because it helps a lot for certain cases; CodeGen
630 // isn't smart enough to ignore the overflow, which leads to much less
631 // efficient code if the width of the subtraction is wider than the native
632 // register width.
633 //
634 // (It's possible to not widen at all by pulling out factors of 2 before
635 // the multiplication; for example, K=2 can be calculated as
636 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
637 // extra arithmetic, so it's not an obvious win, and it gets
638 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000639
Eli Friedman7489ec92008-08-04 23:49:06 +0000640 // Protection from insane SCEVs; this bound is conservative,
641 // but it probably doesn't matter.
642 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000643 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000644
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000645 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000646
Eli Friedman7489ec92008-08-04 23:49:06 +0000647 // Calculate K! / 2^T and T; we divide out the factors of two before
648 // multiplying for calculating K! / 2^T to avoid overflow.
649 // Other overflow doesn't matter because we only care about the bottom
650 // W bits of the result.
651 APInt OddFactorial(W, 1);
652 unsigned T = 1;
653 for (unsigned i = 3; i <= K; ++i) {
654 APInt Mult(W, i);
655 unsigned TwoFactors = Mult.countTrailingZeros();
656 T += TwoFactors;
657 Mult = Mult.lshr(TwoFactors);
658 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000659 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000660
Eli Friedman7489ec92008-08-04 23:49:06 +0000661 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000662 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000663
664 // Calcuate 2^T, at width T+W.
665 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
666
667 // Calculate the multiplicative inverse of K! / 2^T;
668 // this multiplication factor will perform the exact division by
669 // K! / 2^T.
670 APInt Mod = APInt::getSignedMinValue(W+1);
671 APInt MultiplyFactor = OddFactorial.zext(W+1);
672 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
673 MultiplyFactor = MultiplyFactor.trunc(W);
674
675 // Calculate the product, at width T+W
676 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
677 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
678 for (unsigned i = 1; i != K; ++i) {
679 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
680 Dividend = SE.getMulExpr(Dividend,
681 SE.getTruncateOrZeroExtend(S, CalculationTy));
682 }
683
684 // Divide by 2^T
685 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
686
687 // Truncate the result, and divide by K! / 2^T.
688
689 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
690 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000691}
692
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000693/// evaluateAtIteration - Return the value of this chain of recurrences at
694/// the specified iteration number. We can evaluate this recurrence by
695/// multiplying each element in the chain by the binomial coefficient
696/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
697///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000698/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000699///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000700/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000701///
Dan Gohman89f85052007-10-22 18:31:58 +0000702SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
703 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000704 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000705 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000706 // The computation is correct in the face of overflow provided that the
707 // multiplication is performed _after_ the evaluation of the binomial
708 // coefficient.
Dan Gohman01c2ee72009-04-16 03:18:22 +0000709 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000710 if (isa<SCEVCouldNotCompute>(Coeff))
711 return Coeff;
712
713 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000714 }
715 return Result;
716}
717
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000718//===----------------------------------------------------------------------===//
719// SCEV Expression folder implementations
720//===----------------------------------------------------------------------===//
721
Dan Gohman9c8abcc2009-05-01 16:44:56 +0000722SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
723 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000724 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000725 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000726 assert(isSCEVable(Ty) &&
727 "This is not a conversion to a SCEVable type!");
728 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000729
Dan Gohmanc76b5452009-05-04 22:02:23 +0000730 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000731 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000732 ConstantExpr::getTrunc(SC->getValue(), Ty));
733
Dan Gohman1a5c4992009-04-22 16:20:48 +0000734 // trunc(trunc(x)) --> trunc(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000735 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000736 return getTruncateExpr(ST->getOperand(), Ty);
737
Nick Lewycky37d04642009-04-23 05:15:08 +0000738 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000739 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000740 return getTruncateOrSignExtend(SS->getOperand(), Ty);
741
742 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000743 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000744 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
745
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000746 // If the input value is a chrec scev made out of constants, truncate
747 // all of the constants.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000748 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000749 std::vector<SCEVHandle> Operands;
750 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
751 // FIXME: This should allow truncation of other expression types!
752 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman89f85052007-10-22 18:31:58 +0000753 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000754 else
755 break;
756 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman89f85052007-10-22 18:31:58 +0000757 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000758 }
759
760 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
761 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
762 return Result;
763}
764
Dan Gohman36d40922009-04-16 19:25:55 +0000765SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
766 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000767 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000768 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000769 assert(isSCEVable(Ty) &&
770 "This is not a conversion to a SCEVable type!");
771 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000772
Dan Gohmanc76b5452009-05-04 22:02:23 +0000773 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000774 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000775 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
776 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
777 return getUnknown(C);
778 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000779
Dan Gohman1a5c4992009-04-22 16:20:48 +0000780 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000781 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000782 return getZeroExtendExpr(SZ->getOperand(), Ty);
783
Dan Gohmana9dba962009-04-27 20:16:15 +0000784 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000786 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000788 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000789 if (AR->isAffine()) {
790 // Check whether the backedge-taken count is SCEVCouldNotCompute.
791 // Note that this serves two purposes: It filters out loops that are
792 // simply not analyzable, and it covers the case where this code is
793 // being called from within backedge-taken count analysis, such that
794 // attempting to ask for the backedge-taken count would likely result
795 // in infinite recursion. In the later case, the analysis code will
796 // cope with a conservative value, and it will take care to purge
797 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000798 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
799 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000800 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000801 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000802 SCEVHandle Start = AR->getStart();
803 SCEVHandle Step = AR->getStepRecurrence(*this);
804
805 // Check whether the backedge-taken count can be losslessly casted to
806 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000807 SCEVHandle CastedMaxBECount =
808 getTruncateOrZeroExtend(MaxBECount, Start->getType());
809 if (MaxBECount ==
810 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000811 const Type *WideTy =
812 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000813 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000814 SCEVHandle ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000815 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000816 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000817 SCEVHandle Add = getAddExpr(Start, ZMul);
818 if (getZeroExtendExpr(Add, WideTy) ==
819 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000820 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000821 getZeroExtendExpr(Step, WideTy))))
822 // Return the expression with the addrec on the outside.
823 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
824 getZeroExtendExpr(Step, Ty),
825 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000826
827 // Similar to above, only this time treat the step value as signed.
828 // This covers loops that count down.
829 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000830 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000831 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000832 Add = getAddExpr(Start, SMul);
833 if (getZeroExtendExpr(Add, WideTy) ==
834 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000835 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000836 getSignExtendExpr(Step, WideTy))))
837 // Return the expression with the addrec on the outside.
838 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
839 getSignExtendExpr(Step, Ty),
840 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000841 }
842 }
843 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000844
845 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
846 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
847 return Result;
848}
849
Dan Gohmana9dba962009-04-27 20:16:15 +0000850SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
851 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000852 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000853 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000854 assert(isSCEVable(Ty) &&
855 "This is not a conversion to a SCEVable type!");
856 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000857
Dan Gohmanc76b5452009-05-04 22:02:23 +0000858 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000859 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000860 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
861 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
862 return getUnknown(C);
863 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000864
Dan Gohman1a5c4992009-04-22 16:20:48 +0000865 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000866 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000867 return getSignExtendExpr(SS->getOperand(), Ty);
868
Dan Gohmana9dba962009-04-27 20:16:15 +0000869 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000870 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000871 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000872 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000873 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000874 if (AR->isAffine()) {
875 // Check whether the backedge-taken count is SCEVCouldNotCompute.
876 // Note that this serves two purposes: It filters out loops that are
877 // simply not analyzable, and it covers the case where this code is
878 // being called from within backedge-taken count analysis, such that
879 // attempting to ask for the backedge-taken count would likely result
880 // in infinite recursion. In the later case, the analysis code will
881 // cope with a conservative value, and it will take care to purge
882 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000883 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
884 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000885 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000886 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000887 SCEVHandle Start = AR->getStart();
888 SCEVHandle Step = AR->getStepRecurrence(*this);
889
890 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000891 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000892 SCEVHandle CastedMaxBECount =
893 getTruncateOrZeroExtend(MaxBECount, Start->getType());
894 if (MaxBECount ==
895 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000896 const Type *WideTy =
897 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000898 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000899 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000900 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000901 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000902 SCEVHandle Add = getAddExpr(Start, SMul);
903 if (getSignExtendExpr(Add, WideTy) ==
904 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000905 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000906 getSignExtendExpr(Step, WideTy))))
907 // Return the expression with the addrec on the outside.
908 return getAddRecExpr(getSignExtendExpr(Start, Ty),
909 getSignExtendExpr(Step, Ty),
910 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000911 }
912 }
913 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000914
915 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
916 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
917 return Result;
918}
919
920// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000921SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000922 assert(!Ops.empty() && "Cannot get empty add!");
923 if (Ops.size() == 1) return Ops[0];
924
925 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +0000926 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000927
928 // If there are any constants, fold them together.
929 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +0000930 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000931 ++Idx;
932 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +0000933 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000935 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
936 RHSC->getValue()->getValue());
937 Ops[0] = getConstant(Fold);
938 Ops.erase(Ops.begin()+1); // Erase the folded element
939 if (Ops.size() == 1) return Ops[0];
940 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000941 }
942
943 // If we are left with a constant zero being added, strip it off.
944 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
945 Ops.erase(Ops.begin());
946 --Idx;
947 }
948 }
949
950 if (Ops.size() == 1) return Ops[0];
951
952 // Okay, check to see if the same value occurs in the operand list twice. If
953 // so, merge them together into an multiply expression. Since we sorted the
954 // list, these values are required to be adjacent.
955 const Type *Ty = Ops[0]->getType();
956 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
957 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
958 // Found a match, merge the two values into a multiply, and add any
959 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000960 SCEVHandle Two = getIntegerSCEV(2, Ty);
961 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000962 if (Ops.size() == 2)
963 return Mul;
964 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
965 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000966 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000967 }
968
969 // Now we know the first non-constant operand. Skip past any cast SCEVs.
970 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
971 ++Idx;
972
973 // If there are add operands they would be next.
974 if (Idx < Ops.size()) {
975 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +0000976 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000977 // If we have an add, expand the add operands onto the end of the operands
978 // list.
979 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
980 Ops.erase(Ops.begin()+Idx);
981 DeletedAdd = true;
982 }
983
984 // If we deleted at least one add, we added operands to the end of the list,
985 // and they are not necessarily sorted. Recurse to resort and resimplify
986 // any operands we just aquired.
987 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +0000988 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000989 }
990
991 // Skip over the add expression until we get to a multiply.
992 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
993 ++Idx;
994
995 // If we are adding something to a multiply expression, make sure the
996 // something is not already an operand of the multiply. If so, merge it into
997 // the multiply.
998 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000999 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001000 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001001 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1003 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
1004 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1005 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
1006 if (Mul->getNumOperands() != 2) {
1007 // If the multiply has more than two operands, we must get the
1008 // Y*Z term.
1009 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1010 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001011 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012 }
Dan Gohman89f85052007-10-22 18:31:58 +00001013 SCEVHandle One = getIntegerSCEV(1, Ty);
1014 SCEVHandle AddOne = getAddExpr(InnerMul, One);
1015 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001016 if (Ops.size() == 2) return OuterMul;
1017 if (AddOp < Idx) {
1018 Ops.erase(Ops.begin()+AddOp);
1019 Ops.erase(Ops.begin()+Idx-1);
1020 } else {
1021 Ops.erase(Ops.begin()+Idx);
1022 Ops.erase(Ops.begin()+AddOp-1);
1023 }
1024 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001025 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001026 }
1027
1028 // Check this multiply against other multiplies being added together.
1029 for (unsigned OtherMulIdx = Idx+1;
1030 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1031 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001032 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001033 // If MulOp occurs in OtherMul, we can fold the two multiplies
1034 // together.
1035 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1036 OMulOp != e; ++OMulOp)
1037 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1038 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1039 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1040 if (Mul->getNumOperands() != 2) {
1041 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1042 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001043 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001044 }
1045 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1046 if (OtherMul->getNumOperands() != 2) {
1047 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
1048 OtherMul->op_end());
1049 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001050 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001051 }
Dan Gohman89f85052007-10-22 18:31:58 +00001052 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1053 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001054 if (Ops.size() == 2) return OuterMul;
1055 Ops.erase(Ops.begin()+Idx);
1056 Ops.erase(Ops.begin()+OtherMulIdx-1);
1057 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001058 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059 }
1060 }
1061 }
1062 }
1063
1064 // If there are any add recurrences in the operands list, see if any other
1065 // added values are loop invariant. If so, we can fold them into the
1066 // recurrence.
1067 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1068 ++Idx;
1069
1070 // Scan over all recurrences, trying to fold loop invariants into them.
1071 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1072 // Scan all of the other operands to this add and add them to the vector if
1073 // they are loop invariant w.r.t. the recurrence.
1074 std::vector<SCEVHandle> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001075 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001076 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1077 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1078 LIOps.push_back(Ops[i]);
1079 Ops.erase(Ops.begin()+i);
1080 --i; --e;
1081 }
1082
1083 // If we found some loop invariants, fold them into the recurrence.
1084 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001085 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001086 LIOps.push_back(AddRec->getStart());
1087
1088 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001089 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001090
Dan Gohman89f85052007-10-22 18:31:58 +00001091 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001092 // If all of the other operands were loop invariant, we are done.
1093 if (Ops.size() == 1) return NewRec;
1094
1095 // Otherwise, add the folded AddRec by the non-liv parts.
1096 for (unsigned i = 0;; ++i)
1097 if (Ops[i] == AddRec) {
1098 Ops[i] = NewRec;
1099 break;
1100 }
Dan Gohman89f85052007-10-22 18:31:58 +00001101 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001102 }
1103
1104 // Okay, if there weren't any loop invariants to be folded, check to see if
1105 // there are multiple AddRec's with the same loop induction variable being
1106 // added together. If so, we can fold them.
1107 for (unsigned OtherIdx = Idx+1;
1108 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1109 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001110 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001111 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1112 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1113 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1114 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1115 if (i >= NewOps.size()) {
1116 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1117 OtherAddRec->op_end());
1118 break;
1119 }
Dan Gohman89f85052007-10-22 18:31:58 +00001120 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001121 }
Dan Gohman89f85052007-10-22 18:31:58 +00001122 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001123
1124 if (Ops.size() == 2) return NewAddRec;
1125
1126 Ops.erase(Ops.begin()+Idx);
1127 Ops.erase(Ops.begin()+OtherIdx-1);
1128 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001129 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001130 }
1131 }
1132
1133 // Otherwise couldn't fold anything into this recurrence. Move onto the
1134 // next one.
1135 }
1136
1137 // Okay, it looks like we really DO need an add expr. Check to see if we
1138 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001139 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1141 SCEVOps)];
1142 if (Result == 0) Result = new SCEVAddExpr(Ops);
1143 return Result;
1144}
1145
1146
Dan Gohman89f85052007-10-22 18:31:58 +00001147SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001148 assert(!Ops.empty() && "Cannot get empty mul!");
1149
1150 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001151 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001152
1153 // If there are any constants, fold them together.
1154 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001155 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001156
1157 // C1*(C2+V) -> C1*C2 + C1*V
1158 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001159 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001160 if (Add->getNumOperands() == 2 &&
1161 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001162 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1163 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001164
1165
1166 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001167 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001168 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001169 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1170 RHSC->getValue()->getValue());
1171 Ops[0] = getConstant(Fold);
1172 Ops.erase(Ops.begin()+1); // Erase the folded element
1173 if (Ops.size() == 1) return Ops[0];
1174 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001175 }
1176
1177 // If we are left with a constant one being multiplied, strip it off.
1178 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1179 Ops.erase(Ops.begin());
1180 --Idx;
1181 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1182 // If we have a multiply of zero, it will always be zero.
1183 return Ops[0];
1184 }
1185 }
1186
1187 // Skip over the add expression until we get to a multiply.
1188 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1189 ++Idx;
1190
1191 if (Ops.size() == 1)
1192 return Ops[0];
1193
1194 // If there are mul operands inline them all into this expression.
1195 if (Idx < Ops.size()) {
1196 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001197 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001198 // If we have an mul, expand the mul operands onto the end of the operands
1199 // list.
1200 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1201 Ops.erase(Ops.begin()+Idx);
1202 DeletedMul = true;
1203 }
1204
1205 // If we deleted at least one mul, we added operands to the end of the list,
1206 // and they are not necessarily sorted. Recurse to resort and resimplify
1207 // any operands we just aquired.
1208 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001209 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001210 }
1211
1212 // If there are any add recurrences in the operands list, see if any other
1213 // added values are loop invariant. If so, we can fold them into the
1214 // recurrence.
1215 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1216 ++Idx;
1217
1218 // Scan over all recurrences, trying to fold loop invariants into them.
1219 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1220 // Scan all of the other operands to this mul and add them to the vector if
1221 // they are loop invariant w.r.t. the recurrence.
1222 std::vector<SCEVHandle> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001223 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001224 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1225 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1226 LIOps.push_back(Ops[i]);
1227 Ops.erase(Ops.begin()+i);
1228 --i; --e;
1229 }
1230
1231 // If we found some loop invariants, fold them into the recurrence.
1232 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001233 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001234 std::vector<SCEVHandle> NewOps;
1235 NewOps.reserve(AddRec->getNumOperands());
1236 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001237 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001238 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001239 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001240 } else {
1241 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1242 std::vector<SCEVHandle> MulOps(LIOps);
1243 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001244 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001245 }
1246 }
1247
Dan Gohman89f85052007-10-22 18:31:58 +00001248 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001249
1250 // If all of the other operands were loop invariant, we are done.
1251 if (Ops.size() == 1) return NewRec;
1252
1253 // Otherwise, multiply the folded AddRec by the non-liv parts.
1254 for (unsigned i = 0;; ++i)
1255 if (Ops[i] == AddRec) {
1256 Ops[i] = NewRec;
1257 break;
1258 }
Dan Gohman89f85052007-10-22 18:31:58 +00001259 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001260 }
1261
1262 // Okay, if there weren't any loop invariants to be folded, check to see if
1263 // there are multiple AddRec's with the same loop induction variable being
1264 // multiplied together. If so, we can fold them.
1265 for (unsigned OtherIdx = Idx+1;
1266 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1267 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001268 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001269 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1270 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001271 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001272 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001273 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001274 SCEVHandle B = F->getStepRecurrence(*this);
1275 SCEVHandle D = G->getStepRecurrence(*this);
1276 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1277 getMulExpr(G, B),
1278 getMulExpr(B, D));
1279 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1280 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001281 if (Ops.size() == 2) return NewAddRec;
1282
1283 Ops.erase(Ops.begin()+Idx);
1284 Ops.erase(Ops.begin()+OtherIdx-1);
1285 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001286 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001287 }
1288 }
1289
1290 // Otherwise couldn't fold anything into this recurrence. Move onto the
1291 // next one.
1292 }
1293
1294 // Okay, it looks like we really DO need an mul expr. Check to see if we
1295 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001296 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001297 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1298 SCEVOps)];
1299 if (Result == 0)
1300 Result = new SCEVMulExpr(Ops);
1301 return Result;
1302}
1303
Dan Gohman77841cd2009-05-04 22:23:18 +00001304SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1305 const SCEVHandle &RHS) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001306 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001307 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001308 return LHS; // X udiv 1 --> x
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001309
Dan Gohmanc76b5452009-05-04 22:02:23 +00001310 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001311 Constant *LHSCV = LHSC->getValue();
1312 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001313 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001314 }
1315 }
1316
Nick Lewycky35b56022009-01-13 09:18:58 +00001317 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1318
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001319 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1320 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321 return Result;
1322}
1323
1324
1325/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1326/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001327SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001328 const SCEVHandle &Step, const Loop *L) {
1329 std::vector<SCEVHandle> Operands;
1330 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001331 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001332 if (StepChrec->getLoop() == L) {
1333 Operands.insert(Operands.end(), StepChrec->op_begin(),
1334 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001335 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001336 }
1337
1338 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001339 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001340}
1341
1342/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1343/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001344SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Nick Lewycky37d04642009-04-23 05:15:08 +00001345 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001346 if (Operands.size() == 1) return Operands[0];
1347
Dan Gohman7b560c42008-06-18 16:23:07 +00001348 if (Operands.back()->isZero()) {
1349 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001350 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001351 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001352
Dan Gohman42936882008-08-08 18:33:12 +00001353 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001354 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001355 const Loop* NestedLoop = NestedAR->getLoop();
1356 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1357 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1358 NestedAR->op_end());
1359 SCEVHandle NestedARHandle(NestedAR);
1360 Operands[0] = NestedAR->getStart();
1361 NestedOperands[0] = getAddRecExpr(Operands, L);
1362 return getAddRecExpr(NestedOperands, NestedLoop);
1363 }
1364 }
1365
Dan Gohmanbff6b582009-05-04 22:30:44 +00001366 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1367 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001368 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1369 return Result;
1370}
1371
Nick Lewycky711640a2007-11-25 22:41:31 +00001372SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1373 const SCEVHandle &RHS) {
1374 std::vector<SCEVHandle> Ops;
1375 Ops.push_back(LHS);
1376 Ops.push_back(RHS);
1377 return getSMaxExpr(Ops);
1378}
1379
1380SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1381 assert(!Ops.empty() && "Cannot get empty smax!");
1382 if (Ops.size() == 1) return Ops[0];
1383
1384 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001385 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001386
1387 // If there are any constants, fold them together.
1388 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001389 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001390 ++Idx;
1391 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001392 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001393 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001394 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001395 APIntOps::smax(LHSC->getValue()->getValue(),
1396 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001397 Ops[0] = getConstant(Fold);
1398 Ops.erase(Ops.begin()+1); // Erase the folded element
1399 if (Ops.size() == 1) return Ops[0];
1400 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001401 }
1402
1403 // If we are left with a constant -inf, strip it off.
1404 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1405 Ops.erase(Ops.begin());
1406 --Idx;
1407 }
1408 }
1409
1410 if (Ops.size() == 1) return Ops[0];
1411
1412 // Find the first SMax
1413 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1414 ++Idx;
1415
1416 // Check to see if one of the operands is an SMax. If so, expand its operands
1417 // onto our operand list, and recurse to simplify.
1418 if (Idx < Ops.size()) {
1419 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001420 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001421 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1422 Ops.erase(Ops.begin()+Idx);
1423 DeletedSMax = true;
1424 }
1425
1426 if (DeletedSMax)
1427 return getSMaxExpr(Ops);
1428 }
1429
1430 // Okay, check to see if the same value occurs in the operand list twice. If
1431 // so, delete one. Since we sorted the list, these values are required to
1432 // be adjacent.
1433 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1434 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1435 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1436 --i; --e;
1437 }
1438
1439 if (Ops.size() == 1) return Ops[0];
1440
1441 assert(!Ops.empty() && "Reduced smax down to nothing!");
1442
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001443 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001444 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001445 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewycky711640a2007-11-25 22:41:31 +00001446 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1447 SCEVOps)];
1448 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1449 return Result;
1450}
1451
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001452SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1453 const SCEVHandle &RHS) {
1454 std::vector<SCEVHandle> Ops;
1455 Ops.push_back(LHS);
1456 Ops.push_back(RHS);
1457 return getUMaxExpr(Ops);
1458}
1459
1460SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1461 assert(!Ops.empty() && "Cannot get empty umax!");
1462 if (Ops.size() == 1) return Ops[0];
1463
1464 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001465 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001466
1467 // If there are any constants, fold them together.
1468 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001469 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001470 ++Idx;
1471 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001472 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001473 // We found two constants, fold them together!
1474 ConstantInt *Fold = ConstantInt::get(
1475 APIntOps::umax(LHSC->getValue()->getValue(),
1476 RHSC->getValue()->getValue()));
1477 Ops[0] = getConstant(Fold);
1478 Ops.erase(Ops.begin()+1); // Erase the folded element
1479 if (Ops.size() == 1) return Ops[0];
1480 LHSC = cast<SCEVConstant>(Ops[0]);
1481 }
1482
1483 // If we are left with a constant zero, strip it off.
1484 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1485 Ops.erase(Ops.begin());
1486 --Idx;
1487 }
1488 }
1489
1490 if (Ops.size() == 1) return Ops[0];
1491
1492 // Find the first UMax
1493 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1494 ++Idx;
1495
1496 // Check to see if one of the operands is a UMax. If so, expand its operands
1497 // onto our operand list, and recurse to simplify.
1498 if (Idx < Ops.size()) {
1499 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001500 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001501 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1502 Ops.erase(Ops.begin()+Idx);
1503 DeletedUMax = true;
1504 }
1505
1506 if (DeletedUMax)
1507 return getUMaxExpr(Ops);
1508 }
1509
1510 // Okay, check to see if the same value occurs in the operand list twice. If
1511 // so, delete one. Since we sorted the list, these values are required to
1512 // be adjacent.
1513 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1514 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1515 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1516 --i; --e;
1517 }
1518
1519 if (Ops.size() == 1) return Ops[0];
1520
1521 assert(!Ops.empty() && "Reduced umax down to nothing!");
1522
1523 // Okay, it looks like we really DO need a umax expr. Check to see if we
1524 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001525 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001526 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1527 SCEVOps)];
1528 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1529 return Result;
1530}
1531
Dan Gohman89f85052007-10-22 18:31:58 +00001532SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001533 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001534 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001535 if (isa<ConstantPointerNull>(V))
1536 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001537 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1538 if (Result == 0) Result = new SCEVUnknown(V);
1539 return Result;
1540}
1541
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001542//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001543// Basic SCEV Analysis and PHI Idiom Recognition Code
1544//
1545
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001546/// isSCEVable - Test if values of the given type are analyzable within
1547/// the SCEV framework. This primarily includes integer types, and it
1548/// can optionally include pointer types if the ScalarEvolution class
1549/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001550bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001551 // Integers are always SCEVable.
1552 if (Ty->isInteger())
1553 return true;
1554
1555 // Pointers are SCEVable if TargetData information is available
1556 // to provide pointer size information.
1557 if (isa<PointerType>(Ty))
1558 return TD != NULL;
1559
1560 // Otherwise it's not SCEVable.
1561 return false;
1562}
1563
1564/// getTypeSizeInBits - Return the size in bits of the specified type,
1565/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001566uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001567 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1568
1569 // If we have a TargetData, use it!
1570 if (TD)
1571 return TD->getTypeSizeInBits(Ty);
1572
1573 // Otherwise, we support only integer types.
1574 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1575 return Ty->getPrimitiveSizeInBits();
1576}
1577
1578/// getEffectiveSCEVType - Return a type with the same bitwidth as
1579/// the given type and which represents how SCEV will treat the given
1580/// type, for which isSCEVable must return true. For pointer types,
1581/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001582const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001583 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1584
1585 if (Ty->isInteger())
1586 return Ty;
1587
1588 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1589 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001590}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001591
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001592SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman0ad08b02009-04-18 17:58:19 +00001593 return UnknownValue;
1594}
1595
Dan Gohmand83d4af2009-05-04 22:20:30 +00001596/// hasSCEV - Return true if the SCEV for this value has already been
Edwin Török0e828d62009-05-01 08:33:47 +00001597/// computed.
1598bool ScalarEvolution::hasSCEV(Value *V) const {
1599 return Scalars.count(V);
1600}
1601
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001602/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1603/// expression and create a new one.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001604SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001605 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001606
Dan Gohmanbff6b582009-05-04 22:30:44 +00001607 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001608 if (I != Scalars.end()) return I->second;
1609 SCEVHandle S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00001610 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001611 return S;
1612}
1613
Dan Gohman01c2ee72009-04-16 03:18:22 +00001614/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1615/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001616SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1617 Ty = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001618 Constant *C;
1619 if (Val == 0)
1620 C = Constant::getNullValue(Ty);
1621 else if (Ty->isFloatingPoint())
1622 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1623 APFloat::IEEEdouble, Val));
1624 else
1625 C = ConstantInt::get(Ty, Val);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001626 return getUnknown(C);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001627}
1628
1629/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1630///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001631SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001632 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001633 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001634
1635 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001636 Ty = getEffectiveSCEVType(Ty);
1637 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001638}
1639
1640/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001641SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001642 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001643 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001644
1645 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001646 Ty = getEffectiveSCEVType(Ty);
1647 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001648 return getMinusSCEV(AllOnes, V);
1649}
1650
1651/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1652///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001653SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky37d04642009-04-23 05:15:08 +00001654 const SCEVHandle &RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001655 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001656 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001657}
1658
1659/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1660/// input value to the specified type. If the type must be extended, it is zero
1661/// extended.
1662SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001663ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001664 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001665 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001666 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1667 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001668 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001669 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001670 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001671 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001672 return getTruncateExpr(V, Ty);
1673 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001674}
1675
1676/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1677/// input value to the specified type. If the type must be extended, it is sign
1678/// extended.
1679SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001680ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001681 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001682 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001683 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1684 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001685 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001686 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001687 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001688 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001689 return getTruncateExpr(V, Ty);
1690 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001691}
1692
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001693/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1694/// the specified instruction and replaces any references to the symbolic value
1695/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001696void ScalarEvolution::
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001697ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1698 const SCEVHandle &NewVal) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001699 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
1700 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001701 if (SI == Scalars.end()) return;
1702
1703 SCEVHandle NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001704 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001705 if (NV == SI->second) return; // No change.
1706
1707 SI->second = NV; // Update the scalars map!
1708
1709 // Any instruction values that use this instruction might also need to be
1710 // updated!
1711 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1712 UI != E; ++UI)
1713 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1714}
1715
1716/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1717/// a loop header, making it a potential recurrence, or it doesn't.
1718///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001719SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001720 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001721 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001722 if (L->getHeader() == PN->getParent()) {
1723 // If it lives in the loop header, it has two incoming values, one
1724 // from outside the loop, and one from inside.
1725 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1726 unsigned BackEdge = IncomingEdge^1;
1727
1728 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001729 SCEVHandle SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001730 assert(Scalars.find(PN) == Scalars.end() &&
1731 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00001732 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001733
1734 // Using this symbolic name for the PHI, analyze the value coming around
1735 // the back-edge.
1736 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1737
1738 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1739 // has a special value for the first iteration of the loop.
1740
1741 // If the value coming around the backedge is an add with the symbolic
1742 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00001743 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001744 // If there is a single occurrence of the symbolic value, replace it
1745 // with a recurrence.
1746 unsigned FoundIndex = Add->getNumOperands();
1747 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1748 if (Add->getOperand(i) == SymbolicName)
1749 if (FoundIndex == e) {
1750 FoundIndex = i;
1751 break;
1752 }
1753
1754 if (FoundIndex != Add->getNumOperands()) {
1755 // Create an add with everything but the specified operand.
1756 std::vector<SCEVHandle> Ops;
1757 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1758 if (i != FoundIndex)
1759 Ops.push_back(Add->getOperand(i));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001760 SCEVHandle Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001761
1762 // This is not a valid addrec if the step amount is varying each
1763 // loop iteration, but is not itself an addrec in this loop.
1764 if (Accum->isLoopInvariant(L) ||
1765 (isa<SCEVAddRecExpr>(Accum) &&
1766 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1767 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001768 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001769
1770 // Okay, for the entire analysis of this edge we assumed the PHI
1771 // to be symbolic. We now need to go back and update all of the
1772 // entries for the scalars that use the PHI (except for the PHI
1773 // itself) to use the new analyzed value instead of the "symbolic"
1774 // value.
1775 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1776 return PHISCEV;
1777 }
1778 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00001779 } else if (const SCEVAddRecExpr *AddRec =
1780 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001781 // Otherwise, this could be a loop like this:
1782 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1783 // In this case, j = {1,+,1} and BEValue is j.
1784 // Because the other in-value of i (0) fits the evolution of BEValue
1785 // i really is an addrec evolution.
1786 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1787 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1788
1789 // If StartVal = j.start - j.stride, we can use StartVal as the
1790 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001791 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00001792 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001793 SCEVHandle PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001794 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001795
1796 // Okay, for the entire analysis of this edge we assumed the PHI
1797 // to be symbolic. We now need to go back and update all of the
1798 // entries for the scalars that use the PHI (except for the PHI
1799 // itself) to use the new analyzed value instead of the "symbolic"
1800 // value.
1801 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1802 return PHISCEV;
1803 }
1804 }
1805 }
1806
1807 return SymbolicName;
1808 }
1809
1810 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001811 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001812}
1813
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001814/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1815/// guaranteed to end in (at every loop iteration). It is, at the same time,
1816/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1817/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001818static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001819 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001820 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001821
Dan Gohmanc76b5452009-05-04 22:02:23 +00001822 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001823 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1824 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001825
Dan Gohmanc76b5452009-05-04 22:02:23 +00001826 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001827 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1828 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1829 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001830 }
1831
Dan Gohmanc76b5452009-05-04 22:02:23 +00001832 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001833 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1834 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1835 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001836 }
1837
Dan Gohmanc76b5452009-05-04 22:02:23 +00001838 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001839 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001840 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001841 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001842 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001843 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001844 }
1845
Dan Gohmanc76b5452009-05-04 22:02:23 +00001846 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001847 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001848 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1849 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001850 for (unsigned i = 1, e = M->getNumOperands();
1851 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001852 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001853 BitWidth);
1854 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001855 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001856
Dan Gohmanc76b5452009-05-04 22:02:23 +00001857 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001858 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001859 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001860 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001861 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001862 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001863 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001864
Dan Gohmanc76b5452009-05-04 22:02:23 +00001865 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001866 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001867 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00001868 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001869 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00001870 return MinOpRes;
1871 }
1872
Dan Gohmanc76b5452009-05-04 22:02:23 +00001873 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001874 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001875 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001876 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001877 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001878 return MinOpRes;
1879 }
1880
Nick Lewycky35b56022009-01-13 09:18:58 +00001881 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001882 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001883}
1884
1885/// createSCEV - We know that there is no SCEV for the specified value.
1886/// Analyze the expression.
1887///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001888SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001889 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001890 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001891
Dan Gohman3996f472008-06-22 19:56:46 +00001892 unsigned Opcode = Instruction::UserOp1;
1893 if (Instruction *I = dyn_cast<Instruction>(V))
1894 Opcode = I->getOpcode();
1895 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1896 Opcode = CE->getOpcode();
1897 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001898 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001899
Dan Gohman3996f472008-06-22 19:56:46 +00001900 User *U = cast<User>(V);
1901 switch (Opcode) {
1902 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001903 return getAddExpr(getSCEV(U->getOperand(0)),
1904 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001905 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001906 return getMulExpr(getSCEV(U->getOperand(0)),
1907 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001908 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001909 return getUDivExpr(getSCEV(U->getOperand(0)),
1910 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001911 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001912 return getMinusSCEV(getSCEV(U->getOperand(0)),
1913 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00001914 case Instruction::And:
1915 // For an expression like x&255 that merely masks off the high bits,
1916 // use zext(trunc(x)) as the SCEV expression.
1917 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00001918 if (CI->isNullValue())
1919 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00001920 if (CI->isAllOnesValue())
1921 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00001922 const APInt &A = CI->getValue();
1923 unsigned Ones = A.countTrailingOnes();
1924 if (APIntOps::isMask(Ones, A))
1925 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001926 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
1927 IntegerType::get(Ones)),
1928 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00001929 }
1930 break;
Dan Gohman3996f472008-06-22 19:56:46 +00001931 case Instruction::Or:
1932 // If the RHS of the Or is a constant, we may have something like:
1933 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1934 // optimizations will transparently handle this case.
1935 //
1936 // In order for this transformation to be safe, the LHS must be of the
1937 // form X*(2^n) and the Or constant must be less than 2^n.
1938 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1939 SCEVHandle LHS = getSCEV(U->getOperand(0));
1940 const APInt &CIVal = CI->getValue();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001941 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman3996f472008-06-22 19:56:46 +00001942 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001943 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001944 }
Dan Gohman3996f472008-06-22 19:56:46 +00001945 break;
1946 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00001947 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00001948 // If the RHS of the xor is a signbit, then this is just an add.
1949 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00001950 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001951 return getAddExpr(getSCEV(U->getOperand(0)),
1952 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001953
1954 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman3996f472008-06-22 19:56:46 +00001955 else if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001956 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman3996f472008-06-22 19:56:46 +00001957 }
1958 break;
1959
1960 case Instruction::Shl:
1961 // Turn shift left of a constant amount into a multiply.
1962 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1963 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1964 Constant *X = ConstantInt::get(
1965 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001966 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00001967 }
1968 break;
1969
Nick Lewycky7fd27892008-07-07 06:15:49 +00001970 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00001971 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00001972 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1973 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1974 Constant *X = ConstantInt::get(
1975 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001976 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001977 }
1978 break;
1979
Dan Gohman53bf64a2009-04-21 02:26:00 +00001980 case Instruction::AShr:
1981 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
1982 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
1983 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
1984 if (L->getOpcode() == Instruction::Shl &&
1985 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00001986 unsigned BitWidth = getTypeSizeInBits(U->getType());
1987 uint64_t Amt = BitWidth - CI->getZExtValue();
1988 if (Amt == BitWidth)
1989 return getSCEV(L->getOperand(0)); // shift by zero --> noop
1990 if (Amt > BitWidth)
1991 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00001992 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001993 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00001994 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00001995 U->getType());
1996 }
1997 break;
1998
Dan Gohman3996f472008-06-22 19:56:46 +00001999 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002000 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002001
2002 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002003 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002004
2005 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002006 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002007
2008 case Instruction::BitCast:
2009 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002010 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002011 return getSCEV(U->getOperand(0));
2012 break;
2013
Dan Gohman01c2ee72009-04-16 03:18:22 +00002014 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002015 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002016 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002017 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002018
2019 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002020 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002021 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2022 U->getType());
2023
2024 case Instruction::GetElementPtr: {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002025 if (!TD) break; // Without TD we can't analyze pointers.
2026 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00002027 Value *Base = U->getOperand(0);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002028 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002029 gep_type_iterator GTI = gep_type_begin(U);
2030 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
2031 E = U->op_end();
2032 I != E; ++I) {
2033 Value *Index = *I;
2034 // Compute the (potentially symbolic) offset in bytes for this index.
2035 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2036 // For a struct, add the member offset.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002037 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002038 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2039 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002040 TotalOffset = getAddExpr(TotalOffset,
2041 getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002042 } else {
2043 // For an array, add the element offset, explicitly scaled.
2044 SCEVHandle LocalOffset = getSCEV(Index);
2045 if (!isa<PointerType>(LocalOffset->getType()))
2046 // Getelementptr indicies are signed.
2047 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2048 IntPtrTy);
2049 LocalOffset =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002050 getMulExpr(LocalOffset,
2051 getIntegerSCEV(TD->getTypePaddedSize(*GTI),
2052 IntPtrTy));
2053 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002054 }
2055 }
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002056 return getAddExpr(getSCEV(Base), TotalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002057 }
2058
Dan Gohman3996f472008-06-22 19:56:46 +00002059 case Instruction::PHI:
2060 return createNodeForPHI(cast<PHINode>(U));
2061
2062 case Instruction::Select:
2063 // This could be a smax or umax that was lowered earlier.
2064 // Try to recover it.
2065 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2066 Value *LHS = ICI->getOperand(0);
2067 Value *RHS = ICI->getOperand(1);
2068 switch (ICI->getPredicate()) {
2069 case ICmpInst::ICMP_SLT:
2070 case ICmpInst::ICMP_SLE:
2071 std::swap(LHS, RHS);
2072 // fall through
2073 case ICmpInst::ICMP_SGT:
2074 case ICmpInst::ICMP_SGE:
2075 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002076 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002077 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00002078 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002079 return getNotSCEV(getSMaxExpr(
2080 getNotSCEV(getSCEV(LHS)),
2081 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002082 break;
2083 case ICmpInst::ICMP_ULT:
2084 case ICmpInst::ICMP_ULE:
2085 std::swap(LHS, RHS);
2086 // fall through
2087 case ICmpInst::ICMP_UGT:
2088 case ICmpInst::ICMP_UGE:
2089 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002090 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002091 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2092 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002093 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2094 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002095 break;
2096 default:
2097 break;
2098 }
2099 }
2100
2101 default: // We cannot analyze this expression.
2102 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002103 }
2104
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002105 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002106}
2107
2108
2109
2110//===----------------------------------------------------------------------===//
2111// Iteration Count Computation Code
2112//
2113
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002114/// getBackedgeTakenCount - If the specified loop has a predictable
2115/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2116/// object. The backedge-taken count is the number of times the loop header
2117/// will be branched to from within the loop. This is one less than the
2118/// trip count of the loop, since it doesn't count the first iteration,
2119/// when the header is branched to from outside the loop.
2120///
2121/// Note that it is not valid to call this method on a loop without a
2122/// loop-invariant backedge-taken count (see
2123/// hasLoopInvariantBackedgeTakenCount).
2124///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002125SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002126 return getBackedgeTakenInfo(L).Exact;
2127}
2128
2129/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2130/// return the least SCEV value that is known never to be less than the
2131/// actual backedge taken count.
2132SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2133 return getBackedgeTakenInfo(L).Max;
2134}
2135
2136const ScalarEvolution::BackedgeTakenInfo &
2137ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002138 // Initially insert a CouldNotCompute for this loop. If the insertion
2139 // succeeds, procede to actually compute a backedge-taken count and
2140 // update the value. The temporary CouldNotCompute value tells SCEV
2141 // code elsewhere that it shouldn't attempt to request a new
2142 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002143 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002144 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2145 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002146 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2147 if (ItCount.Exact != UnknownValue) {
2148 assert(ItCount.Exact->isLoopInvariant(L) &&
2149 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002150 "Computed trip count isn't loop invariant for loop!");
2151 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002152
Dan Gohmana9dba962009-04-27 20:16:15 +00002153 // Update the value in the map.
2154 Pair.first->second = ItCount;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002155 } else if (isa<PHINode>(L->getHeader()->begin())) {
2156 // Only count loops that have phi nodes as not being computable.
2157 ++NumTripCountsNotComputed;
2158 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002159
2160 // Now that we know more about the trip count for this loop, forget any
2161 // existing SCEV values for PHI nodes in this loop since they are only
2162 // conservative estimates made without the benefit
2163 // of trip count information.
2164 if (ItCount.hasAnyInfo())
Dan Gohman94623022009-05-02 17:43:35 +00002165 forgetLoopPHIs(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002166 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002167 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002168}
2169
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002170/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002171/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002172/// ScalarEvolution's ability to compute a trip count, or if the loop
2173/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002174void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002175 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002176 forgetLoopPHIs(L);
2177}
2178
2179/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2180/// PHI nodes in the given loop. This is used when the trip count of
2181/// the loop may have changed.
2182void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002183 BasicBlock *Header = L->getHeader();
2184
2185 SmallVector<Instruction *, 16> Worklist;
2186 for (BasicBlock::iterator I = Header->begin();
Dan Gohman94623022009-05-02 17:43:35 +00002187 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Dan Gohmanbff6b582009-05-04 22:30:44 +00002188 Worklist.push_back(PN);
2189
2190 while (!Worklist.empty()) {
2191 Instruction *I = Worklist.pop_back_val();
2192 if (Scalars.erase(I))
2193 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2194 UI != UE; ++UI)
2195 Worklist.push_back(cast<Instruction>(UI));
2196 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002197}
2198
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002199/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2200/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002201ScalarEvolution::BackedgeTakenInfo
2202ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002203 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00002204 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002205 L->getExitBlocks(ExitBlocks);
2206 if (ExitBlocks.size() != 1) return UnknownValue;
2207
2208 // Okay, there is one exit block. Try to find the condition that causes the
2209 // loop to be exited.
2210 BasicBlock *ExitBlock = ExitBlocks[0];
2211
2212 BasicBlock *ExitingBlock = 0;
2213 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2214 PI != E; ++PI)
2215 if (L->contains(*PI)) {
2216 if (ExitingBlock == 0)
2217 ExitingBlock = *PI;
2218 else
2219 return UnknownValue; // More than one block exiting!
2220 }
2221 assert(ExitingBlock && "No exits from loop, something is broken!");
2222
2223 // Okay, we've computed the exiting block. See what condition causes us to
2224 // exit.
2225 //
2226 // FIXME: we should be able to handle switch instructions (with a single exit)
2227 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2228 if (ExitBr == 0) return UnknownValue;
2229 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2230
2231 // At this point, we know we have a conditional branch that determines whether
2232 // the loop is exited. However, we don't know if the branch is executed each
2233 // time through the loop. If not, then the execution count of the branch will
2234 // not be equal to the trip count of the loop.
2235 //
2236 // Currently we check for this by checking to see if the Exit branch goes to
2237 // the loop header. If so, we know it will always execute the same number of
2238 // times as the loop. We also handle the case where the exit block *is* the
2239 // loop header. This is common for un-rotated loops. More extensive analysis
2240 // could be done to handle more cases here.
2241 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2242 ExitBr->getSuccessor(1) != L->getHeader() &&
2243 ExitBr->getParent() != L->getHeader())
2244 return UnknownValue;
2245
2246 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2247
Nick Lewyckyb3d24332008-02-21 08:34:02 +00002248 // If it's not an integer comparison then compute it the hard way.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002249 // Note that ICmpInst deals with pointer comparisons too so we must check
2250 // the type of the operand.
2251 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002252 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002253 ExitBr->getSuccessor(0) == ExitBlock);
2254
2255 // If the condition was exit on true, convert the condition to exit on false
2256 ICmpInst::Predicate Cond;
2257 if (ExitBr->getSuccessor(1) == ExitBlock)
2258 Cond = ExitCond->getPredicate();
2259 else
2260 Cond = ExitCond->getInversePredicate();
2261
2262 // Handle common loops like: for (X = "string"; *X; ++X)
2263 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2264 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2265 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002266 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002267 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2268 }
2269
2270 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2271 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2272
2273 // Try to evaluate any dependencies out of the loop.
2274 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2275 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2276 Tmp = getSCEVAtScope(RHS, L);
2277 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2278
2279 // At this point, we would like to compute how many iterations of the
2280 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002281 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2282 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002283 std::swap(LHS, RHS);
2284 Cond = ICmpInst::getSwappedPredicate(Cond);
2285 }
2286
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002287 // If we have a comparison of a chrec against a constant, try to use value
2288 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002289 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2290 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002291 if (AddRec->getLoop() == L) {
2292 // Form the comparison range using the constant of the correct type so
2293 // that the ConstantRange class knows to do a signed or unsigned
2294 // comparison.
2295 ConstantInt *CompVal = RHSC->getValue();
2296 const Type *RealTy = ExitCond->getOperand(0)->getType();
2297 CompVal = dyn_cast<ConstantInt>(
2298 ConstantExpr::getBitCast(CompVal, RealTy));
2299 if (CompVal) {
2300 // Form the constant range.
2301 ConstantRange CompRange(
2302 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2303
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002304 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002305 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2306 }
2307 }
2308
2309 switch (Cond) {
2310 case ICmpInst::ICMP_NE: { // while (X != Y)
2311 // Convert to: while (X-Y != 0)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002312 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002313 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2314 break;
2315 }
2316 case ICmpInst::ICMP_EQ: {
2317 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002318 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002319 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2320 break;
2321 }
2322 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002323 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2324 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002325 break;
2326 }
2327 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002328 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2329 getNotSCEV(RHS), L, true);
2330 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002331 break;
2332 }
2333 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002334 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2335 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002336 break;
2337 }
2338 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002339 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2340 getNotSCEV(RHS), L, false);
2341 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002342 break;
2343 }
2344 default:
2345#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002346 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002347 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002348 errs() << "[unsigned] ";
2349 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002350 << Instruction::getOpcodeName(Instruction::ICmp)
2351 << " " << *RHS << "\n";
2352#endif
2353 break;
2354 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002355 return
2356 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2357 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002358}
2359
2360static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002361EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2362 ScalarEvolution &SE) {
2363 SCEVHandle InVal = SE.getConstant(C);
2364 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002365 assert(isa<SCEVConstant>(Val) &&
2366 "Evaluation of SCEV at constant didn't fold correctly?");
2367 return cast<SCEVConstant>(Val)->getValue();
2368}
2369
2370/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2371/// and a GEP expression (missing the pointer index) indexing into it, return
2372/// the addressed element of the initializer or null if the index expression is
2373/// invalid.
2374static Constant *
2375GetAddressedElementFromGlobal(GlobalVariable *GV,
2376 const std::vector<ConstantInt*> &Indices) {
2377 Constant *Init = GV->getInitializer();
2378 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2379 uint64_t Idx = Indices[i]->getZExtValue();
2380 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2381 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2382 Init = cast<Constant>(CS->getOperand(Idx));
2383 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2384 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2385 Init = cast<Constant>(CA->getOperand(Idx));
2386 } else if (isa<ConstantAggregateZero>(Init)) {
2387 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2388 assert(Idx < STy->getNumElements() && "Bad struct index!");
2389 Init = Constant::getNullValue(STy->getElementType(Idx));
2390 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2391 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2392 Init = Constant::getNullValue(ATy->getElementType());
2393 } else {
2394 assert(0 && "Unknown constant aggregate type!");
2395 }
2396 return 0;
2397 } else {
2398 return 0; // Unknown initializer type
2399 }
2400 }
2401 return Init;
2402}
2403
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002404/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2405/// 'icmp op load X, cst', try to see if we can compute the backedge
2406/// execution count.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002407SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002408ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2409 const Loop *L,
2410 ICmpInst::Predicate predicate) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002411 if (LI->isVolatile()) return UnknownValue;
2412
2413 // Check to see if the loaded pointer is a getelementptr of a global.
2414 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2415 if (!GEP) return UnknownValue;
2416
2417 // Make sure that it is really a constant global we are gepping, with an
2418 // initializer, and make sure the first IDX is really 0.
2419 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2420 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2421 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2422 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2423 return UnknownValue;
2424
2425 // Okay, we allow one non-constant index into the GEP instruction.
2426 Value *VarIdx = 0;
2427 std::vector<ConstantInt*> Indexes;
2428 unsigned VarIdxNum = 0;
2429 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2430 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2431 Indexes.push_back(CI);
2432 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2433 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2434 VarIdx = GEP->getOperand(i);
2435 VarIdxNum = i-2;
2436 Indexes.push_back(0);
2437 }
2438
2439 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2440 // Check to see if X is a loop variant variable value now.
2441 SCEVHandle Idx = getSCEV(VarIdx);
2442 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2443 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2444
2445 // We can only recognize very limited forms of loop index expressions, in
2446 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002447 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002448 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2449 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2450 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2451 return UnknownValue;
2452
2453 unsigned MaxSteps = MaxBruteForceIterations;
2454 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2455 ConstantInt *ItCst =
2456 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002457 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002458
2459 // Form the GEP offset.
2460 Indexes[VarIdxNum] = Val;
2461
2462 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2463 if (Result == 0) break; // Cannot compute!
2464
2465 // Evaluate the condition for this iteration.
2466 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2467 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2468 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2469#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002470 errs() << "\n***\n*** Computed loop count " << *ItCst
2471 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2472 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002473#endif
2474 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002475 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002476 }
2477 }
2478 return UnknownValue;
2479}
2480
2481
2482/// CanConstantFold - Return true if we can constant fold an instruction of the
2483/// specified type, assuming that all operands were constants.
2484static bool CanConstantFold(const Instruction *I) {
2485 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2486 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2487 return true;
2488
2489 if (const CallInst *CI = dyn_cast<CallInst>(I))
2490 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002491 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002492 return false;
2493}
2494
2495/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2496/// in the loop that V is derived from. We allow arbitrary operations along the
2497/// way, but the operands of an operation must either be constants or a value
2498/// derived from a constant PHI. If this expression does not fit with these
2499/// constraints, return null.
2500static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2501 // If this is not an instruction, or if this is an instruction outside of the
2502 // loop, it can't be derived from a loop PHI.
2503 Instruction *I = dyn_cast<Instruction>(V);
2504 if (I == 0 || !L->contains(I->getParent())) return 0;
2505
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002506 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002507 if (L->getHeader() == I->getParent())
2508 return PN;
2509 else
2510 // We don't currently keep track of the control flow needed to evaluate
2511 // PHIs, so we cannot handle PHIs inside of loops.
2512 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002513 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002514
2515 // If we won't be able to constant fold this expression even if the operands
2516 // are constants, return early.
2517 if (!CanConstantFold(I)) return 0;
2518
2519 // Otherwise, we can evaluate this instruction if all of its operands are
2520 // constant or derived from a PHI node themselves.
2521 PHINode *PHI = 0;
2522 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2523 if (!(isa<Constant>(I->getOperand(Op)) ||
2524 isa<GlobalValue>(I->getOperand(Op)))) {
2525 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2526 if (P == 0) return 0; // Not evolving from PHI
2527 if (PHI == 0)
2528 PHI = P;
2529 else if (PHI != P)
2530 return 0; // Evolving from multiple different PHIs.
2531 }
2532
2533 // This is a expression evolving from a constant PHI!
2534 return PHI;
2535}
2536
2537/// EvaluateExpression - Given an expression that passes the
2538/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2539/// in the loop has the value PHIVal. If we can't fold this expression for some
2540/// reason, return null.
2541static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2542 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002543 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002544 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002545 Instruction *I = cast<Instruction>(V);
2546
2547 std::vector<Constant*> Operands;
2548 Operands.resize(I->getNumOperands());
2549
2550 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2551 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2552 if (Operands[i] == 0) return 0;
2553 }
2554
Chris Lattnerd6e56912007-12-10 22:53:04 +00002555 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2556 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2557 &Operands[0], Operands.size());
2558 else
2559 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2560 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002561}
2562
2563/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2564/// in the header of its containing loop, we know the loop executes a
2565/// constant number of times, and the PHI node is just a recurrence
2566/// involving constants, fold it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002567Constant *ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002568getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002569 std::map<PHINode*, Constant*>::iterator I =
2570 ConstantEvolutionLoopExitValue.find(PN);
2571 if (I != ConstantEvolutionLoopExitValue.end())
2572 return I->second;
2573
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002574 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002575 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2576
2577 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2578
2579 // Since the loop is canonicalized, the PHI node must have two entries. One
2580 // entry must be a constant (coming in from outside of the loop), and the
2581 // second must be derived from the same PHI.
2582 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2583 Constant *StartCST =
2584 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2585 if (StartCST == 0)
2586 return RetVal = 0; // Must be a constant.
2587
2588 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2589 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2590 if (PN2 != PN)
2591 return RetVal = 0; // Not derived from same PHI.
2592
2593 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002594 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002595 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2596
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002597 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002598 unsigned IterationNum = 0;
2599 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2600 if (IterationNum == NumIterations)
2601 return RetVal = PHIVal; // Got exit value!
2602
2603 // Compute the value of the PHI node for the next iteration.
2604 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2605 if (NextPHI == PHIVal)
2606 return RetVal = NextPHI; // Stopped evolving!
2607 if (NextPHI == 0)
2608 return 0; // Couldn't evaluate!
2609 PHIVal = NextPHI;
2610 }
2611}
2612
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002613/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002614/// constant number of times (the condition evolves only from constants),
2615/// try to evaluate a few iterations of the loop until we get the exit
2616/// condition gets a value of ExitWhen (true or false). If we cannot
2617/// evaluate the trip count of the loop, return UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002618SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002619ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002620 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2621 if (PN == 0) return UnknownValue;
2622
2623 // Since the loop is canonicalized, the PHI node must have two entries. One
2624 // entry must be a constant (coming in from outside of the loop), and the
2625 // second must be derived from the same PHI.
2626 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2627 Constant *StartCST =
2628 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2629 if (StartCST == 0) return UnknownValue; // Must be a constant.
2630
2631 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2632 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2633 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2634
2635 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2636 // the loop symbolically to determine when the condition gets a value of
2637 // "ExitWhen".
2638 unsigned IterationNum = 0;
2639 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2640 for (Constant *PHIVal = StartCST;
2641 IterationNum != MaxIterations; ++IterationNum) {
2642 ConstantInt *CondVal =
2643 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2644
2645 // Couldn't symbolically evaluate.
2646 if (!CondVal) return UnknownValue;
2647
2648 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2649 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2650 ++NumBruteForceTripCountsComputed;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002651 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002652 }
2653
2654 // Compute the value of the PHI node for the next iteration.
2655 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2656 if (NextPHI == 0 || NextPHI == PHIVal)
2657 return UnknownValue; // Couldn't evaluate or not making progress...
2658 PHIVal = NextPHI;
2659 }
2660
2661 // Too many iterations were needed to evaluate.
2662 return UnknownValue;
2663}
2664
2665/// getSCEVAtScope - Compute the value of the specified expression within the
2666/// indicated loop (which may be null to indicate in no loop). If the
2667/// expression cannot be evaluated, return UnknownValue.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002668SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002669 // FIXME: this should be turned into a virtual method on SCEV!
2670
2671 if (isa<SCEVConstant>(V)) return V;
2672
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002673 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002674 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002675 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002676 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002677 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002678 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2679 if (PHINode *PN = dyn_cast<PHINode>(I))
2680 if (PN->getParent() == LI->getHeader()) {
2681 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002682 // to see if the loop that contains it has a known backedge-taken
2683 // count. If so, we may be able to force computation of the exit
2684 // value.
2685 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002686 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002687 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002688 // Okay, we know how many times the containing loop executes. If
2689 // this is a constant evolving PHI node, get the final value at
2690 // the specified iteration number.
2691 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002692 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002693 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002694 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002695 }
2696 }
2697
2698 // Okay, this is an expression that we cannot symbolically evaluate
2699 // into a SCEV. Check to see if it's possible to symbolically evaluate
2700 // the arguments into constants, and if so, try to constant propagate the
2701 // result. This is particularly useful for computing loop exit values.
2702 if (CanConstantFold(I)) {
2703 std::vector<Constant*> Operands;
2704 Operands.reserve(I->getNumOperands());
2705 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2706 Value *Op = I->getOperand(i);
2707 if (Constant *C = dyn_cast<Constant>(Op)) {
2708 Operands.push_back(C);
2709 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002710 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00002711 // non-integer and non-pointer, don't even try to analyze them
2712 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00002713 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00002714 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002715
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002716 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002717 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00002718 Constant *C = SC->getValue();
2719 if (C->getType() != Op->getType())
2720 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2721 Op->getType(),
2722 false),
2723 C, Op->getType());
2724 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002725 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00002726 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
2727 if (C->getType() != Op->getType())
2728 C =
2729 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2730 Op->getType(),
2731 false),
2732 C, Op->getType());
2733 Operands.push_back(C);
2734 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002735 return V;
2736 } else {
2737 return V;
2738 }
2739 }
2740 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002741
2742 Constant *C;
2743 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2744 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2745 &Operands[0], Operands.size());
2746 else
2747 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2748 &Operands[0], Operands.size());
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002749 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002750 }
2751 }
2752
2753 // This is some other type of SCEVUnknown, just return it.
2754 return V;
2755 }
2756
Dan Gohmanc76b5452009-05-04 22:02:23 +00002757 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002758 // Avoid performing the look-up in the common case where the specified
2759 // expression has no loop-variant portions.
2760 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2761 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2762 if (OpAtScope != Comm->getOperand(i)) {
2763 if (OpAtScope == UnknownValue) return UnknownValue;
2764 // Okay, at least one of these operands is loop variant but might be
2765 // foldable. Build a new instance of the folded commutative expression.
2766 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2767 NewOps.push_back(OpAtScope);
2768
2769 for (++i; i != e; ++i) {
2770 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2771 if (OpAtScope == UnknownValue) return UnknownValue;
2772 NewOps.push_back(OpAtScope);
2773 }
2774 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002775 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002776 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002777 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002778 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002779 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002780 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002781 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002782 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002783 }
2784 }
2785 // If we got here, all operands are loop invariant.
2786 return Comm;
2787 }
2788
Dan Gohmanc76b5452009-05-04 22:02:23 +00002789 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Nick Lewycky35b56022009-01-13 09:18:58 +00002790 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002791 if (LHS == UnknownValue) return LHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002792 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002793 if (RHS == UnknownValue) return RHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002794 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2795 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002796 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002797 }
2798
2799 // If this is a loop recurrence for a loop that does not contain L, then we
2800 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002801 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002802 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2803 // To evaluate this recurrence, we need to know how many times the AddRec
2804 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002805 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2806 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002807
Eli Friedman7489ec92008-08-04 23:49:06 +00002808 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002809 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002810 }
2811 return UnknownValue;
2812 }
2813
Dan Gohmanc76b5452009-05-04 22:02:23 +00002814 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00002815 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2816 if (Op == UnknownValue) return Op;
2817 if (Op == Cast->getOperand())
2818 return Cast; // must be loop invariant
2819 return getZeroExtendExpr(Op, Cast->getType());
2820 }
2821
Dan Gohmanc76b5452009-05-04 22:02:23 +00002822 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00002823 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2824 if (Op == UnknownValue) return Op;
2825 if (Op == Cast->getOperand())
2826 return Cast; // must be loop invariant
2827 return getSignExtendExpr(Op, Cast->getType());
2828 }
2829
Dan Gohmanc76b5452009-05-04 22:02:23 +00002830 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00002831 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2832 if (Op == UnknownValue) return Op;
2833 if (Op == Cast->getOperand())
2834 return Cast; // must be loop invariant
2835 return getTruncateExpr(Op, Cast->getType());
2836 }
2837
2838 assert(0 && "Unknown SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002839}
2840
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002841/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2842/// at the specified scope in the program. The L value specifies a loop
2843/// nest to evaluate the expression at, where null is the top-level or a
2844/// specified loop is immediately inside of the loop.
2845///
2846/// This method can be used to compute the exit value for a variable defined
2847/// in a loop by querying what the value will hold in the parent loop.
2848///
2849/// If this value is not computable at this scope, a SCEVCouldNotCompute
2850/// object is returned.
2851SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2852 return getSCEVAtScope(getSCEV(V), L);
2853}
2854
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002855/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2856/// following equation:
2857///
2858/// A * X = B (mod N)
2859///
2860/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2861/// A and B isn't important.
2862///
2863/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2864static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2865 ScalarEvolution &SE) {
2866 uint32_t BW = A.getBitWidth();
2867 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2868 assert(A != 0 && "A must be non-zero.");
2869
2870 // 1. D = gcd(A, N)
2871 //
2872 // The gcd of A and N may have only one prime factor: 2. The number of
2873 // trailing zeros in A is its multiplicity
2874 uint32_t Mult2 = A.countTrailingZeros();
2875 // D = 2^Mult2
2876
2877 // 2. Check if B is divisible by D.
2878 //
2879 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2880 // is not less than multiplicity of this prime factor for D.
2881 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00002882 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002883
2884 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2885 // modulo (N / D).
2886 //
2887 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2888 // bit width during computations.
2889 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2890 APInt Mod(BW + 1, 0);
2891 Mod.set(BW - Mult2); // Mod = N / D
2892 APInt I = AD.multiplicativeInverse(Mod);
2893
2894 // 4. Compute the minimum unsigned root of the equation:
2895 // I * (B / D) mod (N / D)
2896 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2897
2898 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2899 // bits.
2900 return SE.getConstant(Result.trunc(BW));
2901}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002902
2903/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2904/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2905/// might be the same) or two SCEVCouldNotCompute objects.
2906///
2907static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00002908SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002909 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002910 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2911 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2912 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002913
2914 // We currently can only solve this if the coefficients are constants.
2915 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002916 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002917 return std::make_pair(CNC, CNC);
2918 }
2919
2920 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2921 const APInt &L = LC->getValue()->getValue();
2922 const APInt &M = MC->getValue()->getValue();
2923 const APInt &N = NC->getValue()->getValue();
2924 APInt Two(BitWidth, 2);
2925 APInt Four(BitWidth, 4);
2926
2927 {
2928 using namespace APIntOps;
2929 const APInt& C = L;
2930 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2931 // The B coefficient is M-N/2
2932 APInt B(M);
2933 B -= sdiv(N,Two);
2934
2935 // The A coefficient is N/2
2936 APInt A(N.sdiv(Two));
2937
2938 // Compute the B^2-4ac term.
2939 APInt SqrtTerm(B);
2940 SqrtTerm *= B;
2941 SqrtTerm -= Four * (A * C);
2942
2943 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2944 // integer value or else APInt::sqrt() will assert.
2945 APInt SqrtVal(SqrtTerm.sqrt());
2946
2947 // Compute the two solutions for the quadratic formula.
2948 // The divisions must be performed as signed divisions.
2949 APInt NegB(-B);
2950 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00002951 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002952 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00002953 return std::make_pair(CNC, CNC);
2954 }
2955
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002956 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2957 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2958
Dan Gohman89f85052007-10-22 18:31:58 +00002959 return std::make_pair(SE.getConstant(Solution1),
2960 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002961 } // end APIntOps namespace
2962}
2963
2964/// HowFarToZero - Return the number of times a backedge comparing the specified
2965/// value to zero will execute. If not computable, return UnknownValue
Dan Gohmanbff6b582009-05-04 22:30:44 +00002966SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002967 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00002968 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002969 // If the value is already zero, the branch will execute zero times.
2970 if (C->getValue()->isZero()) return C;
2971 return UnknownValue; // Otherwise it will loop infinitely.
2972 }
2973
Dan Gohmanbff6b582009-05-04 22:30:44 +00002974 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002975 if (!AddRec || AddRec->getLoop() != L)
2976 return UnknownValue;
2977
2978 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002979 // If this is an affine expression, the execution count of this branch is
2980 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002981 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002982 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002983 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002984 // equivalent to:
2985 //
2986 // Step*N = -Start (mod 2^BW)
2987 //
2988 // where BW is the common bit width of Start and Step.
2989
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002990 // Get the initial value for the loop.
2991 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2992 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002993
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002994 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002995
Dan Gohmanc76b5452009-05-04 22:02:23 +00002996 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002997 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002998
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002999 // First, handle unitary steps.
3000 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003001 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003002 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3003 return Start; // N = Start (as unsigned)
3004
3005 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003006 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003007 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003008 -StartC->getValue()->getValue(),
3009 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003010 }
3011 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3012 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3013 // the quadratic equation to solve it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003014 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
3015 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003016 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3017 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003018 if (R1) {
3019#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003020 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3021 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003022#endif
3023 // Pick the smallest positive root value.
3024 if (ConstantInt *CB =
3025 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3026 R1->getValue(), R2->getValue()))) {
3027 if (CB->getZExtValue() == false)
3028 std::swap(R1, R2); // R1 is the minimum root now.
3029
3030 // We can only use this value if the chrec ends up with an exact zero
3031 // value at this index. When solving for "X*X != 5", for example, we
3032 // should not accept a root of 2.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003033 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00003034 if (Val->isZero())
3035 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003036 }
3037 }
3038 }
3039
3040 return UnknownValue;
3041}
3042
3043/// HowFarToNonZero - Return the number of times a backedge checking the
3044/// specified value for nonzero will execute. If not computable, return
3045/// UnknownValue
Dan Gohmanbff6b582009-05-04 22:30:44 +00003046SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003047 // Loops that look like: while (X == 0) are very strange indeed. We don't
3048 // handle them yet except for the trivial case. This could be expanded in the
3049 // future as needed.
3050
3051 // If the value is a constant, check to see if it is known to be non-zero
3052 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003053 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00003054 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003055 return getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003056 return UnknownValue; // Otherwise it will loop infinitely.
3057 }
3058
3059 // We could implement others, but I really doubt anyone writes loops like
3060 // this, and if they did, they would already be constant folded.
3061 return UnknownValue;
3062}
3063
Dan Gohman1cddf972008-09-15 22:18:04 +00003064/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3065/// (which may not be an immediate predecessor) which has exactly one
3066/// successor from which BB is reachable, or null if no such block is
3067/// found.
3068///
3069BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003070ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00003071 // If the block has a unique predecessor, then there is no path from the
3072 // predecessor to the block that does not go through the direct edge
3073 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00003074 if (BasicBlock *Pred = BB->getSinglePredecessor())
3075 return Pred;
3076
3077 // A loop's header is defined to be a block that dominates the loop.
3078 // If the loop has a preheader, it must be a block that has exactly
3079 // one successor that can reach BB. This is slightly more strict
3080 // than necessary, but works if critical edges are split.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003081 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman1cddf972008-09-15 22:18:04 +00003082 return L->getLoopPreheader();
3083
3084 return 0;
3085}
3086
Dan Gohmancacd2012009-02-12 22:19:27 +00003087/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman1116ea72009-04-30 20:48:53 +00003088/// a conditional between LHS and RHS. This is used to help avoid max
3089/// expressions in loop trip counts.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003090bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman1116ea72009-04-30 20:48:53 +00003091 ICmpInst::Predicate Pred,
Dan Gohmanbff6b582009-05-04 22:30:44 +00003092 const SCEV *LHS, const SCEV *RHS) {
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003093 BasicBlock *Preheader = L->getLoopPreheader();
3094 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003095
Dan Gohmanab678fb2008-08-12 20:17:31 +00003096 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohman1cddf972008-09-15 22:18:04 +00003097 // there are predecessors that can be found that have unique successors
3098 // leading to the original header.
3099 for (; Preheader;
3100 PreheaderDest = Preheader,
3101 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00003102
3103 BranchInst *LoopEntryPredicate =
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003104 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00003105 if (!LoopEntryPredicate ||
3106 LoopEntryPredicate->isUnconditional())
3107 continue;
3108
3109 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3110 if (!ICI) continue;
3111
3112 // Now that we found a conditional branch that dominates the loop, check to
3113 // see if it is the comparison we are looking for.
3114 Value *PreCondLHS = ICI->getOperand(0);
3115 Value *PreCondRHS = ICI->getOperand(1);
3116 ICmpInst::Predicate Cond;
3117 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3118 Cond = ICI->getPredicate();
3119 else
3120 Cond = ICI->getInversePredicate();
3121
Dan Gohmancacd2012009-02-12 22:19:27 +00003122 if (Cond == Pred)
3123 ; // An exact match.
3124 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3125 ; // The actual condition is beyond sufficient.
3126 else
3127 // Check a few special cases.
3128 switch (Cond) {
3129 case ICmpInst::ICMP_UGT:
3130 if (Pred == ICmpInst::ICMP_ULT) {
3131 std::swap(PreCondLHS, PreCondRHS);
3132 Cond = ICmpInst::ICMP_ULT;
3133 break;
3134 }
3135 continue;
3136 case ICmpInst::ICMP_SGT:
3137 if (Pred == ICmpInst::ICMP_SLT) {
3138 std::swap(PreCondLHS, PreCondRHS);
3139 Cond = ICmpInst::ICMP_SLT;
3140 break;
3141 }
3142 continue;
3143 case ICmpInst::ICMP_NE:
3144 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3145 // so check for this case by checking if the NE is comparing against
3146 // a minimum or maximum constant.
3147 if (!ICmpInst::isTrueWhenEqual(Pred))
3148 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3149 const APInt &A = CI->getValue();
3150 switch (Pred) {
3151 case ICmpInst::ICMP_SLT:
3152 if (A.isMaxSignedValue()) break;
3153 continue;
3154 case ICmpInst::ICMP_SGT:
3155 if (A.isMinSignedValue()) break;
3156 continue;
3157 case ICmpInst::ICMP_ULT:
3158 if (A.isMaxValue()) break;
3159 continue;
3160 case ICmpInst::ICMP_UGT:
3161 if (A.isMinValue()) break;
3162 continue;
3163 default:
3164 continue;
3165 }
3166 Cond = ICmpInst::ICMP_NE;
3167 // NE is symmetric but the original comparison may not be. Swap
3168 // the operands if necessary so that they match below.
3169 if (isa<SCEVConstant>(LHS))
3170 std::swap(PreCondLHS, PreCondRHS);
3171 break;
3172 }
3173 continue;
3174 default:
3175 // We weren't able to reconcile the condition.
3176 continue;
3177 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003178
3179 if (!PreCondLHS->getType()->isInteger()) continue;
3180
3181 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3182 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3183 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003184 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3185 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohmanab678fb2008-08-12 20:17:31 +00003186 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003187 }
3188
Dan Gohmanab678fb2008-08-12 20:17:31 +00003189 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003190}
3191
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003192/// HowManyLessThans - Return the number of times a backedge containing the
3193/// specified less-than comparison will execute. If not computable, return
3194/// UnknownValue.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003195ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Dan Gohmanbff6b582009-05-04 22:30:44 +00003196HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3197 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003198 // Only handle: "ADDREC < LoopInvariant".
3199 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3200
Dan Gohmanbff6b582009-05-04 22:30:44 +00003201 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003202 if (!AddRec || AddRec->getLoop() != L)
3203 return UnknownValue;
3204
3205 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003206 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003207 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3208 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3209 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3210
3211 // TODO: handle non-constant strides.
3212 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3213 if (!CStep || CStep->isZero())
3214 return UnknownValue;
3215 if (CStep->getValue()->getValue() == 1) {
3216 // With unit stride, the iteration never steps past the limit value.
3217 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3218 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3219 // Test whether a positive iteration iteration can step past the limit
3220 // value and past the maximum value for its type in a single step.
3221 if (isSigned) {
3222 APInt Max = APInt::getSignedMaxValue(BitWidth);
3223 if ((Max - CStep->getValue()->getValue())
3224 .slt(CLimit->getValue()->getValue()))
3225 return UnknownValue;
3226 } else {
3227 APInt Max = APInt::getMaxValue(BitWidth);
3228 if ((Max - CStep->getValue()->getValue())
3229 .ult(CLimit->getValue()->getValue()))
3230 return UnknownValue;
3231 }
3232 } else
3233 // TODO: handle non-constant limit values below.
3234 return UnknownValue;
3235 } else
3236 // TODO: handle negative strides below.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003237 return UnknownValue;
3238
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003239 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3240 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3241 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00003242 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003243
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003244 // First, we get the value of the LHS in the first iteration: n
3245 SCEVHandle Start = AddRec->getOperand(0);
3246
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003247 // Determine the minimum constant start value.
3248 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3249 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3250 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003251
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003252 // If we know that the condition is true in order to enter the loop,
3253 // then we know that it will run exactly (m-n)/s times. Otherwise, we
3254 // only know if will execute (max(m,n)-n)/s times. In both cases, the
3255 // division must round up.
3256 SCEVHandle End = RHS;
3257 if (!isLoopGuardedByCond(L,
3258 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3259 getMinusSCEV(Start, Step), RHS))
3260 End = isSigned ? getSMaxExpr(RHS, Start)
3261 : getUMaxExpr(RHS, Start);
3262
3263 // Determine the maximum constant end value.
3264 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3265 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3266 APInt::getMaxValue(BitWidth));
3267
3268 // Finally, we subtract these two values and divide, rounding up, to get
3269 // the number of times the backedge is executed.
3270 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3271 getAddExpr(Step, NegOne)),
3272 Step);
3273
3274 // The maximum backedge count is similar, except using the minimum start
3275 // value and the maximum end value.
3276 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3277 MinStart),
3278 getAddExpr(Step, NegOne)),
3279 Step);
3280
3281 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003282 }
3283
3284 return UnknownValue;
3285}
3286
3287/// getNumIterationsInRange - Return the number of iterations of this loop that
3288/// produce values in the specified constant range. Another way of looking at
3289/// this is that it returns the first iteration number where the value is not in
3290/// the condition, thus computing the exit count. If the iteration count can't
3291/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00003292SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3293 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003294 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003295 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003296
3297 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003298 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003299 if (!SC->getValue()->isZero()) {
3300 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003301 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3302 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00003303 if (const SCEVAddRecExpr *ShiftedAddRec =
3304 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003305 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003306 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003307 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003308 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003309 }
3310
3311 // The only time we can solve this is when we have all constant indices.
3312 // Otherwise, we cannot determine the overflow conditions.
3313 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3314 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003315 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003316
3317
3318 // Okay at this point we know that all elements of the chrec are constants and
3319 // that the start element is zero.
3320
3321 // First check to see if the range contains zero. If not, the first
3322 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003323 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003324 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003325 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003326
3327 if (isAffine()) {
3328 // If this is an affine expression then we have this situation:
3329 // Solve {0,+,A} in Range === Ax in Range
3330
3331 // We know that zero is in the range. If A is positive then we know that
3332 // the upper value of the range must be the first possible exit value.
3333 // If A is negative then the lower of the range is the last possible loop
3334 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003335 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003336 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3337 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3338
3339 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003340 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003341 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3342
3343 // Evaluate at the exit value. If we really did fall out of the valid
3344 // range, then we computed our trip count, otherwise wrap around or other
3345 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003346 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003347 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003348 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003349
3350 // Ensure that the previous value is in the range. This is a sanity check.
3351 assert(Range.contains(
3352 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003353 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003354 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003355 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003356 } else if (isQuadratic()) {
3357 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3358 // quadratic equation to solve it. To do this, we must frame our problem in
3359 // terms of figuring out when zero is crossed, instead of when
3360 // Range.getUpper() is crossed.
3361 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003362 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3363 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003364
3365 // Next, solve the constructed addrec
3366 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003367 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003368 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3369 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003370 if (R1) {
3371 // Pick the smallest positive root value.
3372 if (ConstantInt *CB =
3373 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3374 R1->getValue(), R2->getValue()))) {
3375 if (CB->getZExtValue() == false)
3376 std::swap(R1, R2); // R1 is the minimum root now.
3377
3378 // Make sure the root is not off by one. The returned iteration should
3379 // not be in the range, but the previous one should be. When solving
3380 // for "X*X < 5", for example, we should not return a root of 2.
3381 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003382 R1->getValue(),
3383 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003384 if (Range.contains(R1Val->getValue())) {
3385 // The next iteration must be out of the range...
3386 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3387
Dan Gohman89f85052007-10-22 18:31:58 +00003388 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003389 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003390 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003391 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003392 }
3393
3394 // If R1 was not in the range, then it is a good return value. Make
3395 // sure that R1-1 WAS in the range though, just in case.
3396 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003397 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003398 if (Range.contains(R1Val->getValue()))
3399 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003400 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003401 }
3402 }
3403 }
3404
Dan Gohman0ad08b02009-04-18 17:58:19 +00003405 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003406}
3407
3408
3409
3410//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00003411// SCEVCallbackVH Class Implementation
3412//===----------------------------------------------------------------------===//
3413
3414void SCEVCallbackVH::deleted() {
3415 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3416 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3417 SE->ConstantEvolutionLoopExitValue.erase(PN);
3418 SE->Scalars.erase(getValPtr());
3419 // this now dangles!
3420}
3421
3422void SCEVCallbackVH::allUsesReplacedWith(Value *) {
3423 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3424
3425 // Forget all the expressions associated with users of the old value,
3426 // so that future queries will recompute the expressions using the new
3427 // value.
3428 SmallVector<User *, 16> Worklist;
3429 Value *Old = getValPtr();
3430 bool DeleteOld = false;
3431 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3432 UI != UE; ++UI)
3433 Worklist.push_back(*UI);
3434 while (!Worklist.empty()) {
3435 User *U = Worklist.pop_back_val();
3436 // Deleting the Old value will cause this to dangle. Postpone
3437 // that until everything else is done.
3438 if (U == Old) {
3439 DeleteOld = true;
3440 continue;
3441 }
3442 if (PHINode *PN = dyn_cast<PHINode>(U))
3443 SE->ConstantEvolutionLoopExitValue.erase(PN);
3444 if (SE->Scalars.erase(U))
3445 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3446 UI != UE; ++UI)
3447 Worklist.push_back(*UI);
3448 }
3449 if (DeleteOld) {
3450 if (PHINode *PN = dyn_cast<PHINode>(Old))
3451 SE->ConstantEvolutionLoopExitValue.erase(PN);
3452 SE->Scalars.erase(Old);
3453 // this now dangles!
3454 }
3455 // this may dangle!
3456}
3457
3458SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
3459 : CallbackVH(V), SE(se) {}
3460
3461//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003462// ScalarEvolution Class Implementation
3463//===----------------------------------------------------------------------===//
3464
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003465ScalarEvolution::ScalarEvolution()
3466 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3467}
3468
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003469bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003470 this->F = &F;
3471 LI = &getAnalysis<LoopInfo>();
3472 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003473 return false;
3474}
3475
3476void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003477 Scalars.clear();
3478 BackedgeTakenCounts.clear();
3479 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003480}
3481
3482void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3483 AU.setPreservesAll();
3484 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003485}
3486
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003487bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003488 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003489}
3490
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003491static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003492 const Loop *L) {
3493 // Print all inner loops first
3494 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3495 PrintLoopInfo(OS, SE, *I);
3496
Nick Lewyckye5da1912008-01-02 02:49:20 +00003497 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003498
Devang Patel02451fa2007-08-21 00:31:24 +00003499 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003500 L->getExitBlocks(ExitBlocks);
3501 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003502 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003503
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003504 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3505 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003506 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003507 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003508 }
3509
Nick Lewyckye5da1912008-01-02 02:49:20 +00003510 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003511}
3512
Dan Gohman13058cc2009-04-21 00:47:46 +00003513void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003514 // ScalarEvolution's implementaiton of the print method is to print
3515 // out SCEV values of all instructions that are interesting. Doing
3516 // this potentially causes it to create new SCEV objects though,
3517 // which technically conflicts with the const qualifier. This isn't
3518 // observable from outside the class though (the hasSCEV function
3519 // notwithstanding), so casting away the const isn't dangerous.
3520 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003521
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003522 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003523 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00003524 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003525 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003526 OS << " --> ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003527 SCEVHandle SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003528 SV->print(OS);
3529 OS << "\t\t";
3530
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003531 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003532 OS << "Exits: ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003533 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003534 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3535 OS << "<<Unknown>>";
3536 } else {
3537 OS << *ExitValue;
3538 }
3539 }
3540
3541
3542 OS << "\n";
3543 }
3544
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003545 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3546 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3547 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003548}
Dan Gohman13058cc2009-04-21 00:47:46 +00003549
3550void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3551 raw_os_ostream OS(o);
3552 print(OS, M);
3553}