blob: 3ad542cd97ce1b4e07a9dd9897b54072ffa3b876 [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)
Dan Gohman45b3b542009-05-08 21:03:19 +0000751 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
752 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000753 }
754
755 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
756 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
757 return Result;
758}
759
Dan Gohman36d40922009-04-16 19:25:55 +0000760SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
761 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000762 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000763 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000764 assert(isSCEVable(Ty) &&
765 "This is not a conversion to a SCEVable type!");
766 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000767
Dan Gohmanc76b5452009-05-04 22:02:23 +0000768 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000769 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000770 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
771 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
772 return getUnknown(C);
773 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000774
Dan Gohman1a5c4992009-04-22 16:20:48 +0000775 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000776 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000777 return getZeroExtendExpr(SZ->getOperand(), Ty);
778
Dan Gohmana9dba962009-04-27 20:16:15 +0000779 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000780 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000781 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000782 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000783 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000784 if (AR->isAffine()) {
785 // Check whether the backedge-taken count is SCEVCouldNotCompute.
786 // Note that this serves two purposes: It filters out loops that are
787 // simply not analyzable, and it covers the case where this code is
788 // being called from within backedge-taken count analysis, such that
789 // attempting to ask for the backedge-taken count would likely result
790 // in infinite recursion. In the later case, the analysis code will
791 // cope with a conservative value, and it will take care to purge
792 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000793 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
794 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000795 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000796 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000797 SCEVHandle Start = AR->getStart();
798 SCEVHandle Step = AR->getStepRecurrence(*this);
799
800 // Check whether the backedge-taken count can be losslessly casted to
801 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000802 SCEVHandle CastedMaxBECount =
803 getTruncateOrZeroExtend(MaxBECount, Start->getType());
804 if (MaxBECount ==
805 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000806 const Type *WideTy =
807 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000808 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000809 SCEVHandle ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000810 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000811 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000812 SCEVHandle Add = getAddExpr(Start, ZMul);
813 if (getZeroExtendExpr(Add, WideTy) ==
814 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000815 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000816 getZeroExtendExpr(Step, WideTy))))
817 // Return the expression with the addrec on the outside.
818 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
819 getZeroExtendExpr(Step, Ty),
820 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000821
822 // Similar to above, only this time treat the step value as signed.
823 // This covers loops that count down.
824 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000825 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000826 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000827 Add = getAddExpr(Start, SMul);
828 if (getZeroExtendExpr(Add, WideTy) ==
829 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000830 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000831 getSignExtendExpr(Step, WideTy))))
832 // Return the expression with the addrec on the outside.
833 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
834 getSignExtendExpr(Step, Ty),
835 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000836 }
837 }
838 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000839
840 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
841 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
842 return Result;
843}
844
Dan Gohmana9dba962009-04-27 20:16:15 +0000845SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
846 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000847 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000848 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000849 assert(isSCEVable(Ty) &&
850 "This is not a conversion to a SCEVable type!");
851 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000852
Dan Gohmanc76b5452009-05-04 22:02:23 +0000853 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000854 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000855 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
856 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
857 return getUnknown(C);
858 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000859
Dan Gohman1a5c4992009-04-22 16:20:48 +0000860 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000861 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000862 return getSignExtendExpr(SS->getOperand(), Ty);
863
Dan Gohmana9dba962009-04-27 20:16:15 +0000864 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000865 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000866 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000867 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000868 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000869 if (AR->isAffine()) {
870 // Check whether the backedge-taken count is SCEVCouldNotCompute.
871 // Note that this serves two purposes: It filters out loops that are
872 // simply not analyzable, and it covers the case where this code is
873 // being called from within backedge-taken count analysis, such that
874 // attempting to ask for the backedge-taken count would likely result
875 // in infinite recursion. In the later case, the analysis code will
876 // cope with a conservative value, and it will take care to purge
877 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000878 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
879 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000880 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000881 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000882 SCEVHandle Start = AR->getStart();
883 SCEVHandle Step = AR->getStepRecurrence(*this);
884
885 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000886 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000887 SCEVHandle CastedMaxBECount =
888 getTruncateOrZeroExtend(MaxBECount, Start->getType());
889 if (MaxBECount ==
890 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000891 const Type *WideTy =
892 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000893 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000894 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000895 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000896 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000897 SCEVHandle Add = getAddExpr(Start, SMul);
898 if (getSignExtendExpr(Add, WideTy) ==
899 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000900 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000901 getSignExtendExpr(Step, WideTy))))
902 // Return the expression with the addrec on the outside.
903 return getAddRecExpr(getSignExtendExpr(Start, Ty),
904 getSignExtendExpr(Step, Ty),
905 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000906 }
907 }
908 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000909
910 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
911 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
912 return Result;
913}
914
915// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000916SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000917 assert(!Ops.empty() && "Cannot get empty add!");
918 if (Ops.size() == 1) return Ops[0];
919
920 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +0000921 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000922
923 // If there are any constants, fold them together.
924 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +0000925 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000926 ++Idx;
927 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +0000928 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000929 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000930 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
931 RHSC->getValue()->getValue());
932 Ops[0] = getConstant(Fold);
933 Ops.erase(Ops.begin()+1); // Erase the folded element
934 if (Ops.size() == 1) return Ops[0];
935 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000936 }
937
938 // If we are left with a constant zero being added, strip it off.
939 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
940 Ops.erase(Ops.begin());
941 --Idx;
942 }
943 }
944
945 if (Ops.size() == 1) return Ops[0];
946
947 // Okay, check to see if the same value occurs in the operand list twice. If
948 // so, merge them together into an multiply expression. Since we sorted the
949 // list, these values are required to be adjacent.
950 const Type *Ty = Ops[0]->getType();
951 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
952 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
953 // Found a match, merge the two values into a multiply, and add any
954 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000955 SCEVHandle Two = getIntegerSCEV(2, Ty);
956 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000957 if (Ops.size() == 2)
958 return Mul;
959 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
960 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000961 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000962 }
963
Dan Gohman45b3b542009-05-08 21:03:19 +0000964 // Check for truncates. If all the operands are truncated from the same
965 // type, see if factoring out the truncate would permit the result to be
966 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
967 // if the contents of the resulting outer trunc fold to something simple.
968 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
969 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
970 const Type *DstType = Trunc->getType();
971 const Type *SrcType = Trunc->getOperand()->getType();
972 std::vector<SCEVHandle> LargeOps;
973 bool Ok = true;
974 // Check all the operands to see if they can be represented in the
975 // source type of the truncate.
976 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
977 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
978 if (T->getOperand()->getType() != SrcType) {
979 Ok = false;
980 break;
981 }
982 LargeOps.push_back(T->getOperand());
983 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
984 // This could be either sign or zero extension, but sign extension
985 // is much more likely to be foldable here.
986 LargeOps.push_back(getSignExtendExpr(C, SrcType));
987 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
988 std::vector<SCEVHandle> LargeMulOps;
989 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
990 if (const SCEVTruncateExpr *T =
991 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
992 if (T->getOperand()->getType() != SrcType) {
993 Ok = false;
994 break;
995 }
996 LargeMulOps.push_back(T->getOperand());
997 } else if (const SCEVConstant *C =
998 dyn_cast<SCEVConstant>(M->getOperand(j))) {
999 // This could be either sign or zero extension, but sign extension
1000 // is much more likely to be foldable here.
1001 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1002 } else {
1003 Ok = false;
1004 break;
1005 }
1006 }
1007 if (Ok)
1008 LargeOps.push_back(getMulExpr(LargeMulOps));
1009 } else {
1010 Ok = false;
1011 break;
1012 }
1013 }
1014 if (Ok) {
1015 // Evaluate the expression in the larger type.
1016 SCEVHandle Fold = getAddExpr(LargeOps);
1017 // If it folds to something simple, use it. Otherwise, don't.
1018 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1019 return getTruncateExpr(Fold, DstType);
1020 }
1021 }
1022
1023 // Skip past any other cast SCEVs.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001024 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1025 ++Idx;
1026
1027 // If there are add operands they would be next.
1028 if (Idx < Ops.size()) {
1029 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001030 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001031 // If we have an add, expand the add operands onto the end of the operands
1032 // list.
1033 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1034 Ops.erase(Ops.begin()+Idx);
1035 DeletedAdd = true;
1036 }
1037
1038 // If we deleted at least one add, we added operands to the end of the list,
1039 // and they are not necessarily sorted. Recurse to resort and resimplify
1040 // any operands we just aquired.
1041 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +00001042 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043 }
1044
1045 // Skip over the add expression until we get to a multiply.
1046 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1047 ++Idx;
1048
1049 // If we are adding something to a multiply expression, make sure the
1050 // something is not already an operand of the multiply. If so, merge it into
1051 // the multiply.
1052 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001053 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001054 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001055 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001056 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1057 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
1058 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1059 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
1060 if (Mul->getNumOperands() != 2) {
1061 // If the multiply has more than two operands, we must get the
1062 // Y*Z term.
1063 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1064 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001065 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001066 }
Dan Gohman89f85052007-10-22 18:31:58 +00001067 SCEVHandle One = getIntegerSCEV(1, Ty);
1068 SCEVHandle AddOne = getAddExpr(InnerMul, One);
1069 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001070 if (Ops.size() == 2) return OuterMul;
1071 if (AddOp < Idx) {
1072 Ops.erase(Ops.begin()+AddOp);
1073 Ops.erase(Ops.begin()+Idx-1);
1074 } else {
1075 Ops.erase(Ops.begin()+Idx);
1076 Ops.erase(Ops.begin()+AddOp-1);
1077 }
1078 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001079 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001080 }
1081
1082 // Check this multiply against other multiplies being added together.
1083 for (unsigned OtherMulIdx = Idx+1;
1084 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1085 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001086 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001087 // If MulOp occurs in OtherMul, we can fold the two multiplies
1088 // together.
1089 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1090 OMulOp != e; ++OMulOp)
1091 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1092 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1093 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1094 if (Mul->getNumOperands() != 2) {
1095 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1096 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001097 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001098 }
1099 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1100 if (OtherMul->getNumOperands() != 2) {
1101 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
1102 OtherMul->op_end());
1103 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001104 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001105 }
Dan Gohman89f85052007-10-22 18:31:58 +00001106 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1107 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108 if (Ops.size() == 2) return OuterMul;
1109 Ops.erase(Ops.begin()+Idx);
1110 Ops.erase(Ops.begin()+OtherMulIdx-1);
1111 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001112 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001113 }
1114 }
1115 }
1116 }
1117
1118 // If there are any add recurrences in the operands list, see if any other
1119 // added values are loop invariant. If so, we can fold them into the
1120 // recurrence.
1121 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1122 ++Idx;
1123
1124 // Scan over all recurrences, trying to fold loop invariants into them.
1125 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1126 // Scan all of the other operands to this add and add them to the vector if
1127 // they are loop invariant w.r.t. the recurrence.
1128 std::vector<SCEVHandle> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001129 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001130 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1131 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1132 LIOps.push_back(Ops[i]);
1133 Ops.erase(Ops.begin()+i);
1134 --i; --e;
1135 }
1136
1137 // If we found some loop invariants, fold them into the recurrence.
1138 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001139 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001140 LIOps.push_back(AddRec->getStart());
1141
1142 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001143 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001144
Dan Gohman89f85052007-10-22 18:31:58 +00001145 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146 // If all of the other operands were loop invariant, we are done.
1147 if (Ops.size() == 1) return NewRec;
1148
1149 // Otherwise, add the folded AddRec by the non-liv parts.
1150 for (unsigned i = 0;; ++i)
1151 if (Ops[i] == AddRec) {
1152 Ops[i] = NewRec;
1153 break;
1154 }
Dan Gohman89f85052007-10-22 18:31:58 +00001155 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001156 }
1157
1158 // Okay, if there weren't any loop invariants to be folded, check to see if
1159 // there are multiple AddRec's with the same loop induction variable being
1160 // added together. If so, we can fold them.
1161 for (unsigned OtherIdx = Idx+1;
1162 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1163 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001164 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001165 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1166 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1167 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1168 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1169 if (i >= NewOps.size()) {
1170 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1171 OtherAddRec->op_end());
1172 break;
1173 }
Dan Gohman89f85052007-10-22 18:31:58 +00001174 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001175 }
Dan Gohman89f85052007-10-22 18:31:58 +00001176 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001177
1178 if (Ops.size() == 2) return NewAddRec;
1179
1180 Ops.erase(Ops.begin()+Idx);
1181 Ops.erase(Ops.begin()+OtherIdx-1);
1182 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001183 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001184 }
1185 }
1186
1187 // Otherwise couldn't fold anything into this recurrence. Move onto the
1188 // next one.
1189 }
1190
1191 // Okay, it looks like we really DO need an add expr. Check to see if we
1192 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001193 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001194 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1195 SCEVOps)];
1196 if (Result == 0) Result = new SCEVAddExpr(Ops);
1197 return Result;
1198}
1199
1200
Dan Gohman89f85052007-10-22 18:31:58 +00001201SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001202 assert(!Ops.empty() && "Cannot get empty mul!");
1203
1204 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001205 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001206
1207 // If there are any constants, fold them together.
1208 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001209 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001210
1211 // C1*(C2+V) -> C1*C2 + C1*V
1212 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001213 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001214 if (Add->getNumOperands() == 2 &&
1215 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001216 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1217 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001218
1219
1220 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001221 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001222 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001223 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1224 RHSC->getValue()->getValue());
1225 Ops[0] = getConstant(Fold);
1226 Ops.erase(Ops.begin()+1); // Erase the folded element
1227 if (Ops.size() == 1) return Ops[0];
1228 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001229 }
1230
1231 // If we are left with a constant one being multiplied, strip it off.
1232 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1233 Ops.erase(Ops.begin());
1234 --Idx;
1235 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1236 // If we have a multiply of zero, it will always be zero.
1237 return Ops[0];
1238 }
1239 }
1240
1241 // Skip over the add expression until we get to a multiply.
1242 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1243 ++Idx;
1244
1245 if (Ops.size() == 1)
1246 return Ops[0];
1247
1248 // If there are mul operands inline them all into this expression.
1249 if (Idx < Ops.size()) {
1250 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001251 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001252 // If we have an mul, expand the mul operands onto the end of the operands
1253 // list.
1254 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1255 Ops.erase(Ops.begin()+Idx);
1256 DeletedMul = true;
1257 }
1258
1259 // If we deleted at least one mul, we added operands to the end of the list,
1260 // and they are not necessarily sorted. Recurse to resort and resimplify
1261 // any operands we just aquired.
1262 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001263 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264 }
1265
1266 // If there are any add recurrences in the operands list, see if any other
1267 // added values are loop invariant. If so, we can fold them into the
1268 // recurrence.
1269 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1270 ++Idx;
1271
1272 // Scan over all recurrences, trying to fold loop invariants into them.
1273 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1274 // Scan all of the other operands to this mul and add them to the vector if
1275 // they are loop invariant w.r.t. the recurrence.
1276 std::vector<SCEVHandle> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001277 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001278 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1279 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1280 LIOps.push_back(Ops[i]);
1281 Ops.erase(Ops.begin()+i);
1282 --i; --e;
1283 }
1284
1285 // If we found some loop invariants, fold them into the recurrence.
1286 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001287 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001288 std::vector<SCEVHandle> NewOps;
1289 NewOps.reserve(AddRec->getNumOperands());
1290 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001291 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001292 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001293 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001294 } else {
1295 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1296 std::vector<SCEVHandle> MulOps(LIOps);
1297 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001298 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001299 }
1300 }
1301
Dan Gohman89f85052007-10-22 18:31:58 +00001302 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001303
1304 // If all of the other operands were loop invariant, we are done.
1305 if (Ops.size() == 1) return NewRec;
1306
1307 // Otherwise, multiply the folded AddRec by the non-liv parts.
1308 for (unsigned i = 0;; ++i)
1309 if (Ops[i] == AddRec) {
1310 Ops[i] = NewRec;
1311 break;
1312 }
Dan Gohman89f85052007-10-22 18:31:58 +00001313 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001314 }
1315
1316 // Okay, if there weren't any loop invariants to be folded, check to see if
1317 // there are multiple AddRec's with the same loop induction variable being
1318 // multiplied together. If so, we can fold them.
1319 for (unsigned OtherIdx = Idx+1;
1320 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1321 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001322 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001323 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1324 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001325 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001326 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001327 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001328 SCEVHandle B = F->getStepRecurrence(*this);
1329 SCEVHandle D = G->getStepRecurrence(*this);
1330 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1331 getMulExpr(G, B),
1332 getMulExpr(B, D));
1333 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1334 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335 if (Ops.size() == 2) return NewAddRec;
1336
1337 Ops.erase(Ops.begin()+Idx);
1338 Ops.erase(Ops.begin()+OtherIdx-1);
1339 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001340 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001341 }
1342 }
1343
1344 // Otherwise couldn't fold anything into this recurrence. Move onto the
1345 // next one.
1346 }
1347
1348 // Okay, it looks like we really DO need an mul expr. Check to see if we
1349 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001350 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001351 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1352 SCEVOps)];
1353 if (Result == 0)
1354 Result = new SCEVMulExpr(Ops);
1355 return Result;
1356}
1357
Dan Gohman77841cd2009-05-04 22:23:18 +00001358SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1359 const SCEVHandle &RHS) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001360 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001362 return LHS; // X udiv 1 --> x
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001363 if (RHSC->isZero())
1364 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001365
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001366 // Determine if the division can be folded into the operands of
1367 // its operands.
1368 // TODO: Generalize this to non-constants by using known-bits information.
1369 const Type *Ty = LHS->getType();
1370 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1371 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1372 // For non-power-of-two values, effectively round the value up to the
1373 // nearest power of two.
1374 if (!RHSC->getValue()->getValue().isPowerOf2())
1375 ++MaxShiftAmt;
1376 const IntegerType *ExtTy =
1377 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1378 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1379 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1380 if (const SCEVConstant *Step =
1381 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1382 if (!Step->getValue()->getValue()
1383 .urem(RHSC->getValue()->getValue()) &&
1384 getTruncateExpr(getZeroExtendExpr(AR, ExtTy), Ty) == AR) {
1385 std::vector<SCEVHandle> Operands;
1386 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1387 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1388 return getAddRecExpr(Operands, AR->getLoop());
1389 }
1390 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
1391 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS))
1392 if (getTruncateExpr(getZeroExtendExpr(M, ExtTy), Ty) == M)
1393 // Find an operand that's safely divisible.
1394 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1395 SCEVHandle Op = M->getOperand(i);
1396 SCEVHandle Div = getUDivExpr(Op, RHSC);
1397 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
1398 std::vector<SCEVHandle> Operands = M->getOperands();
1399 Operands[i] = Div;
1400 return getMulExpr(Operands);
1401 }
1402 }
1403 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
1404 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS))
1405 if (getTruncateExpr(getZeroExtendExpr(A, ExtTy), Ty) == A) {
1406 std::vector<SCEVHandle> Operands;
1407 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1408 SCEVHandle Op = getUDivExpr(A->getOperand(i), RHS);
1409 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1410 break;
1411 Operands.push_back(Op);
1412 }
1413 if (Operands.size() == A->getNumOperands())
1414 return getAddExpr(Operands);
1415 }
1416
1417 // Fold if both operands are constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001418 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001419 Constant *LHSCV = LHSC->getValue();
1420 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001421 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001422 }
1423 }
1424
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001425 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1426 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001427 return Result;
1428}
1429
1430
1431/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1432/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001433SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001434 const SCEVHandle &Step, const Loop *L) {
1435 std::vector<SCEVHandle> Operands;
1436 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001437 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001438 if (StepChrec->getLoop() == L) {
1439 Operands.insert(Operands.end(), StepChrec->op_begin(),
1440 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001441 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001442 }
1443
1444 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001445 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001446}
1447
1448/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1449/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001450SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Nick Lewycky37d04642009-04-23 05:15:08 +00001451 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001452 if (Operands.size() == 1) return Operands[0];
1453
Dan Gohman7b560c42008-06-18 16:23:07 +00001454 if (Operands.back()->isZero()) {
1455 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001456 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001457 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001458
Dan Gohman42936882008-08-08 18:33:12 +00001459 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001460 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001461 const Loop* NestedLoop = NestedAR->getLoop();
1462 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1463 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1464 NestedAR->op_end());
1465 SCEVHandle NestedARHandle(NestedAR);
1466 Operands[0] = NestedAR->getStart();
1467 NestedOperands[0] = getAddRecExpr(Operands, L);
1468 return getAddRecExpr(NestedOperands, NestedLoop);
1469 }
1470 }
1471
Dan Gohmanbff6b582009-05-04 22:30:44 +00001472 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1473 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001474 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1475 return Result;
1476}
1477
Nick Lewycky711640a2007-11-25 22:41:31 +00001478SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1479 const SCEVHandle &RHS) {
1480 std::vector<SCEVHandle> Ops;
1481 Ops.push_back(LHS);
1482 Ops.push_back(RHS);
1483 return getSMaxExpr(Ops);
1484}
1485
1486SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1487 assert(!Ops.empty() && "Cannot get empty smax!");
1488 if (Ops.size() == 1) return Ops[0];
1489
1490 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001491 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001492
1493 // If there are any constants, fold them together.
1494 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001495 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001496 ++Idx;
1497 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001498 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001499 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001500 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001501 APIntOps::smax(LHSC->getValue()->getValue(),
1502 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001503 Ops[0] = getConstant(Fold);
1504 Ops.erase(Ops.begin()+1); // Erase the folded element
1505 if (Ops.size() == 1) return Ops[0];
1506 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001507 }
1508
1509 // If we are left with a constant -inf, strip it off.
1510 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1511 Ops.erase(Ops.begin());
1512 --Idx;
1513 }
1514 }
1515
1516 if (Ops.size() == 1) return Ops[0];
1517
1518 // Find the first SMax
1519 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1520 ++Idx;
1521
1522 // Check to see if one of the operands is an SMax. If so, expand its operands
1523 // onto our operand list, and recurse to simplify.
1524 if (Idx < Ops.size()) {
1525 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001526 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001527 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1528 Ops.erase(Ops.begin()+Idx);
1529 DeletedSMax = true;
1530 }
1531
1532 if (DeletedSMax)
1533 return getSMaxExpr(Ops);
1534 }
1535
1536 // Okay, check to see if the same value occurs in the operand list twice. If
1537 // so, delete one. Since we sorted the list, these values are required to
1538 // be adjacent.
1539 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1540 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1541 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1542 --i; --e;
1543 }
1544
1545 if (Ops.size() == 1) return Ops[0];
1546
1547 assert(!Ops.empty() && "Reduced smax down to nothing!");
1548
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001549 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001550 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001551 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewycky711640a2007-11-25 22:41:31 +00001552 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1553 SCEVOps)];
1554 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1555 return Result;
1556}
1557
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001558SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1559 const SCEVHandle &RHS) {
1560 std::vector<SCEVHandle> Ops;
1561 Ops.push_back(LHS);
1562 Ops.push_back(RHS);
1563 return getUMaxExpr(Ops);
1564}
1565
1566SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1567 assert(!Ops.empty() && "Cannot get empty umax!");
1568 if (Ops.size() == 1) return Ops[0];
1569
1570 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001571 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001572
1573 // If there are any constants, fold them together.
1574 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001575 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001576 ++Idx;
1577 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001578 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001579 // We found two constants, fold them together!
1580 ConstantInt *Fold = ConstantInt::get(
1581 APIntOps::umax(LHSC->getValue()->getValue(),
1582 RHSC->getValue()->getValue()));
1583 Ops[0] = getConstant(Fold);
1584 Ops.erase(Ops.begin()+1); // Erase the folded element
1585 if (Ops.size() == 1) return Ops[0];
1586 LHSC = cast<SCEVConstant>(Ops[0]);
1587 }
1588
1589 // If we are left with a constant zero, strip it off.
1590 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1591 Ops.erase(Ops.begin());
1592 --Idx;
1593 }
1594 }
1595
1596 if (Ops.size() == 1) return Ops[0];
1597
1598 // Find the first UMax
1599 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1600 ++Idx;
1601
1602 // Check to see if one of the operands is a UMax. If so, expand its operands
1603 // onto our operand list, and recurse to simplify.
1604 if (Idx < Ops.size()) {
1605 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001606 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001607 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1608 Ops.erase(Ops.begin()+Idx);
1609 DeletedUMax = true;
1610 }
1611
1612 if (DeletedUMax)
1613 return getUMaxExpr(Ops);
1614 }
1615
1616 // Okay, check to see if the same value occurs in the operand list twice. If
1617 // so, delete one. Since we sorted the list, these values are required to
1618 // be adjacent.
1619 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1620 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1621 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1622 --i; --e;
1623 }
1624
1625 if (Ops.size() == 1) return Ops[0];
1626
1627 assert(!Ops.empty() && "Reduced umax down to nothing!");
1628
1629 // Okay, it looks like we really DO need a umax expr. Check to see if we
1630 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001631 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001632 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1633 SCEVOps)];
1634 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1635 return Result;
1636}
1637
Dan Gohman89f85052007-10-22 18:31:58 +00001638SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001639 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001640 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001641 if (isa<ConstantPointerNull>(V))
1642 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001643 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1644 if (Result == 0) Result = new SCEVUnknown(V);
1645 return Result;
1646}
1647
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001648//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001649// Basic SCEV Analysis and PHI Idiom Recognition Code
1650//
1651
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001652/// isSCEVable - Test if values of the given type are analyzable within
1653/// the SCEV framework. This primarily includes integer types, and it
1654/// can optionally include pointer types if the ScalarEvolution class
1655/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001656bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001657 // Integers are always SCEVable.
1658 if (Ty->isInteger())
1659 return true;
1660
1661 // Pointers are SCEVable if TargetData information is available
1662 // to provide pointer size information.
1663 if (isa<PointerType>(Ty))
1664 return TD != NULL;
1665
1666 // Otherwise it's not SCEVable.
1667 return false;
1668}
1669
1670/// getTypeSizeInBits - Return the size in bits of the specified type,
1671/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001672uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001673 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1674
1675 // If we have a TargetData, use it!
1676 if (TD)
1677 return TD->getTypeSizeInBits(Ty);
1678
1679 // Otherwise, we support only integer types.
1680 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1681 return Ty->getPrimitiveSizeInBits();
1682}
1683
1684/// getEffectiveSCEVType - Return a type with the same bitwidth as
1685/// the given type and which represents how SCEV will treat the given
1686/// type, for which isSCEVable must return true. For pointer types,
1687/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001688const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001689 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1690
1691 if (Ty->isInteger())
1692 return Ty;
1693
1694 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1695 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001696}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001697
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001698SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman0ad08b02009-04-18 17:58:19 +00001699 return UnknownValue;
1700}
1701
Dan Gohmand83d4af2009-05-04 22:20:30 +00001702/// hasSCEV - Return true if the SCEV for this value has already been
Edwin Török0e828d62009-05-01 08:33:47 +00001703/// computed.
1704bool ScalarEvolution::hasSCEV(Value *V) const {
1705 return Scalars.count(V);
1706}
1707
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001708/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1709/// expression and create a new one.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001710SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001711 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001712
Dan Gohmanbff6b582009-05-04 22:30:44 +00001713 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001714 if (I != Scalars.end()) return I->second;
1715 SCEVHandle S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00001716 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001717 return S;
1718}
1719
Dan Gohman01c2ee72009-04-16 03:18:22 +00001720/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1721/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001722SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1723 Ty = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001724 Constant *C;
1725 if (Val == 0)
1726 C = Constant::getNullValue(Ty);
1727 else if (Ty->isFloatingPoint())
1728 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1729 APFloat::IEEEdouble, Val));
1730 else
1731 C = ConstantInt::get(Ty, Val);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001732 return getUnknown(C);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001733}
1734
1735/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1736///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001737SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001738 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001739 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001740
1741 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001742 Ty = getEffectiveSCEVType(Ty);
1743 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001744}
1745
1746/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001747SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001748 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001749 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001750
1751 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001752 Ty = getEffectiveSCEVType(Ty);
1753 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001754 return getMinusSCEV(AllOnes, V);
1755}
1756
1757/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1758///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001759SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky37d04642009-04-23 05:15:08 +00001760 const SCEVHandle &RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001761 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001762 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001763}
1764
1765/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1766/// input value to the specified type. If the type must be extended, it is zero
1767/// extended.
1768SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001769ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001770 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001771 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001772 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1773 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001774 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001775 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001776 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001777 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001778 return getTruncateExpr(V, Ty);
1779 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001780}
1781
1782/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1783/// input value to the specified type. If the type must be extended, it is sign
1784/// extended.
1785SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001786ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001787 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001788 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001789 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1790 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001791 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001792 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001793 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001794 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001795 return getTruncateExpr(V, Ty);
1796 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001797}
1798
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001799/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1800/// the specified instruction and replaces any references to the symbolic value
1801/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001802void ScalarEvolution::
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001803ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1804 const SCEVHandle &NewVal) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001805 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
1806 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001807 if (SI == Scalars.end()) return;
1808
1809 SCEVHandle NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001810 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001811 if (NV == SI->second) return; // No change.
1812
1813 SI->second = NV; // Update the scalars map!
1814
1815 // Any instruction values that use this instruction might also need to be
1816 // updated!
1817 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1818 UI != E; ++UI)
1819 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1820}
1821
1822/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1823/// a loop header, making it a potential recurrence, or it doesn't.
1824///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001825SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001826 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001827 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001828 if (L->getHeader() == PN->getParent()) {
1829 // If it lives in the loop header, it has two incoming values, one
1830 // from outside the loop, and one from inside.
1831 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1832 unsigned BackEdge = IncomingEdge^1;
1833
1834 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001835 SCEVHandle SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001836 assert(Scalars.find(PN) == Scalars.end() &&
1837 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00001838 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001839
1840 // Using this symbolic name for the PHI, analyze the value coming around
1841 // the back-edge.
1842 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1843
1844 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1845 // has a special value for the first iteration of the loop.
1846
1847 // If the value coming around the backedge is an add with the symbolic
1848 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00001849 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001850 // If there is a single occurrence of the symbolic value, replace it
1851 // with a recurrence.
1852 unsigned FoundIndex = Add->getNumOperands();
1853 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1854 if (Add->getOperand(i) == SymbolicName)
1855 if (FoundIndex == e) {
1856 FoundIndex = i;
1857 break;
1858 }
1859
1860 if (FoundIndex != Add->getNumOperands()) {
1861 // Create an add with everything but the specified operand.
1862 std::vector<SCEVHandle> Ops;
1863 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1864 if (i != FoundIndex)
1865 Ops.push_back(Add->getOperand(i));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001866 SCEVHandle Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001867
1868 // This is not a valid addrec if the step amount is varying each
1869 // loop iteration, but is not itself an addrec in this loop.
1870 if (Accum->isLoopInvariant(L) ||
1871 (isa<SCEVAddRecExpr>(Accum) &&
1872 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1873 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001874 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001875
1876 // Okay, for the entire analysis of this edge we assumed the PHI
1877 // to be symbolic. We now need to go back and update all of the
1878 // entries for the scalars that use the PHI (except for the PHI
1879 // itself) to use the new analyzed value instead of the "symbolic"
1880 // value.
1881 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1882 return PHISCEV;
1883 }
1884 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00001885 } else if (const SCEVAddRecExpr *AddRec =
1886 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001887 // Otherwise, this could be a loop like this:
1888 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1889 // In this case, j = {1,+,1} and BEValue is j.
1890 // Because the other in-value of i (0) fits the evolution of BEValue
1891 // i really is an addrec evolution.
1892 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1893 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1894
1895 // If StartVal = j.start - j.stride, we can use StartVal as the
1896 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001897 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00001898 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001899 SCEVHandle PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001900 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001901
1902 // Okay, for the entire analysis of this edge we assumed the PHI
1903 // to be symbolic. We now need to go back and update all of the
1904 // entries for the scalars that use the PHI (except for the PHI
1905 // itself) to use the new analyzed value instead of the "symbolic"
1906 // value.
1907 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1908 return PHISCEV;
1909 }
1910 }
1911 }
1912
1913 return SymbolicName;
1914 }
1915
1916 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001917 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001918}
1919
Dan Gohman509cf4d2009-05-08 20:26:55 +00001920/// createNodeForGEP - Expand GEP instructions into add and multiply
1921/// operations. This allows them to be analyzed by regular SCEV code.
1922///
Dan Gohmanca5a39e2009-05-08 20:58:38 +00001923SCEVHandle ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman509cf4d2009-05-08 20:26:55 +00001924
1925 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmanc7034fa2009-05-08 20:36:47 +00001926 Value *Base = GEP->getOperand(0);
Dan Gohman509cf4d2009-05-08 20:26:55 +00001927 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmanc7034fa2009-05-08 20:36:47 +00001928 gep_type_iterator GTI = gep_type_begin(GEP);
1929 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
1930 E = GEP->op_end();
Dan Gohman509cf4d2009-05-08 20:26:55 +00001931 I != E; ++I) {
1932 Value *Index = *I;
1933 // Compute the (potentially symbolic) offset in bytes for this index.
1934 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1935 // For a struct, add the member offset.
1936 const StructLayout &SL = *TD->getStructLayout(STy);
1937 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1938 uint64_t Offset = SL.getElementOffset(FieldNo);
1939 TotalOffset = getAddExpr(TotalOffset,
1940 getIntegerSCEV(Offset, IntPtrTy));
1941 } else {
1942 // For an array, add the element offset, explicitly scaled.
1943 SCEVHandle LocalOffset = getSCEV(Index);
1944 if (!isa<PointerType>(LocalOffset->getType()))
1945 // Getelementptr indicies are signed.
1946 LocalOffset = getTruncateOrSignExtend(LocalOffset,
1947 IntPtrTy);
1948 LocalOffset =
1949 getMulExpr(LocalOffset,
1950 getIntegerSCEV(TD->getTypePaddedSize(*GTI),
1951 IntPtrTy));
1952 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
1953 }
1954 }
1955 return getAddExpr(getSCEV(Base), TotalOffset);
1956}
1957
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001958/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1959/// guaranteed to end in (at every loop iteration). It is, at the same time,
1960/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1961/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001962static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001963 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001964 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001965
Dan Gohmanc76b5452009-05-04 22:02:23 +00001966 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001967 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1968 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001969
Dan Gohmanc76b5452009-05-04 22:02:23 +00001970 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001971 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1972 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1973 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001974 }
1975
Dan Gohmanc76b5452009-05-04 22:02:23 +00001976 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001977 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1978 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1979 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001980 }
1981
Dan Gohmanc76b5452009-05-04 22:02:23 +00001982 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001983 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001984 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001985 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001986 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001987 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001988 }
1989
Dan Gohmanc76b5452009-05-04 22:02:23 +00001990 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001991 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001992 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1993 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001994 for (unsigned i = 1, e = M->getNumOperands();
1995 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001996 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001997 BitWidth);
1998 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001999 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002000
Dan Gohmanc76b5452009-05-04 22:02:23 +00002001 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002002 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002003 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002004 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002005 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002006 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002007 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002008
Dan Gohmanc76b5452009-05-04 22:02:23 +00002009 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00002010 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002011 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00002012 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002013 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00002014 return MinOpRes;
2015 }
2016
Dan Gohmanc76b5452009-05-04 22:02:23 +00002017 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002018 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002019 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002020 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002021 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002022 return MinOpRes;
2023 }
2024
Nick Lewycky35b56022009-01-13 09:18:58 +00002025 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002026 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002027}
2028
2029/// createSCEV - We know that there is no SCEV for the specified value.
2030/// Analyze the expression.
2031///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002032SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002033 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002034 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002035
Dan Gohman3996f472008-06-22 19:56:46 +00002036 unsigned Opcode = Instruction::UserOp1;
2037 if (Instruction *I = dyn_cast<Instruction>(V))
2038 Opcode = I->getOpcode();
2039 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2040 Opcode = CE->getOpcode();
2041 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002042 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002043
Dan Gohman3996f472008-06-22 19:56:46 +00002044 User *U = cast<User>(V);
2045 switch (Opcode) {
2046 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002047 return getAddExpr(getSCEV(U->getOperand(0)),
2048 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002049 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002050 return getMulExpr(getSCEV(U->getOperand(0)),
2051 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002052 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002053 return getUDivExpr(getSCEV(U->getOperand(0)),
2054 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002055 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002056 return getMinusSCEV(getSCEV(U->getOperand(0)),
2057 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002058 case Instruction::And:
2059 // For an expression like x&255 that merely masks off the high bits,
2060 // use zext(trunc(x)) as the SCEV expression.
2061 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002062 if (CI->isNullValue())
2063 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00002064 if (CI->isAllOnesValue())
2065 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002066 const APInt &A = CI->getValue();
2067 unsigned Ones = A.countTrailingOnes();
2068 if (APIntOps::isMask(Ones, A))
2069 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002070 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
2071 IntegerType::get(Ones)),
2072 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00002073 }
2074 break;
Dan Gohman3996f472008-06-22 19:56:46 +00002075 case Instruction::Or:
2076 // If the RHS of the Or is a constant, we may have something like:
2077 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2078 // optimizations will transparently handle this case.
2079 //
2080 // In order for this transformation to be safe, the LHS must be of the
2081 // form X*(2^n) and the Or constant must be less than 2^n.
2082 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2083 SCEVHandle LHS = getSCEV(U->getOperand(0));
2084 const APInt &CIVal = CI->getValue();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002085 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman3996f472008-06-22 19:56:46 +00002086 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002087 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002088 }
Dan Gohman3996f472008-06-22 19:56:46 +00002089 break;
2090 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00002091 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00002092 // If the RHS of the xor is a signbit, then this is just an add.
2093 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00002094 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002095 return getAddExpr(getSCEV(U->getOperand(0)),
2096 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002097
2098 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman3996f472008-06-22 19:56:46 +00002099 else if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002100 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman3996f472008-06-22 19:56:46 +00002101 }
2102 break;
2103
2104 case Instruction::Shl:
2105 // Turn shift left of a constant amount into a multiply.
2106 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2107 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2108 Constant *X = ConstantInt::get(
2109 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002110 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00002111 }
2112 break;
2113
Nick Lewycky7fd27892008-07-07 06:15:49 +00002114 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00002115 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00002116 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2117 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2118 Constant *X = ConstantInt::get(
2119 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002120 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002121 }
2122 break;
2123
Dan Gohman53bf64a2009-04-21 02:26:00 +00002124 case Instruction::AShr:
2125 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2126 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2127 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2128 if (L->getOpcode() == Instruction::Shl &&
2129 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002130 unsigned BitWidth = getTypeSizeInBits(U->getType());
2131 uint64_t Amt = BitWidth - CI->getZExtValue();
2132 if (Amt == BitWidth)
2133 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2134 if (Amt > BitWidth)
2135 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00002136 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002137 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00002138 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00002139 U->getType());
2140 }
2141 break;
2142
Dan Gohman3996f472008-06-22 19:56:46 +00002143 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002144 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002145
2146 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002147 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002148
2149 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002150 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002151
2152 case Instruction::BitCast:
2153 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002154 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002155 return getSCEV(U->getOperand(0));
2156 break;
2157
Dan Gohman01c2ee72009-04-16 03:18:22 +00002158 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002159 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002160 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002161 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002162
2163 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002164 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002165 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2166 U->getType());
2167
Dan Gohman509cf4d2009-05-08 20:26:55 +00002168 case Instruction::GetElementPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002169 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002170 return createNodeForGEP(U);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002171
Dan Gohman3996f472008-06-22 19:56:46 +00002172 case Instruction::PHI:
2173 return createNodeForPHI(cast<PHINode>(U));
2174
2175 case Instruction::Select:
2176 // This could be a smax or umax that was lowered earlier.
2177 // Try to recover it.
2178 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2179 Value *LHS = ICI->getOperand(0);
2180 Value *RHS = ICI->getOperand(1);
2181 switch (ICI->getPredicate()) {
2182 case ICmpInst::ICMP_SLT:
2183 case ICmpInst::ICMP_SLE:
2184 std::swap(LHS, RHS);
2185 // fall through
2186 case ICmpInst::ICMP_SGT:
2187 case ICmpInst::ICMP_SGE:
2188 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002189 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002190 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00002191 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002192 return getNotSCEV(getSMaxExpr(
2193 getNotSCEV(getSCEV(LHS)),
2194 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002195 break;
2196 case ICmpInst::ICMP_ULT:
2197 case ICmpInst::ICMP_ULE:
2198 std::swap(LHS, RHS);
2199 // fall through
2200 case ICmpInst::ICMP_UGT:
2201 case ICmpInst::ICMP_UGE:
2202 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002203 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002204 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2205 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002206 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2207 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002208 break;
2209 default:
2210 break;
2211 }
2212 }
2213
2214 default: // We cannot analyze this expression.
2215 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002216 }
2217
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002218 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002219}
2220
2221
2222
2223//===----------------------------------------------------------------------===//
2224// Iteration Count Computation Code
2225//
2226
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002227/// getBackedgeTakenCount - If the specified loop has a predictable
2228/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2229/// object. The backedge-taken count is the number of times the loop header
2230/// will be branched to from within the loop. This is one less than the
2231/// trip count of the loop, since it doesn't count the first iteration,
2232/// when the header is branched to from outside the loop.
2233///
2234/// Note that it is not valid to call this method on a loop without a
2235/// loop-invariant backedge-taken count (see
2236/// hasLoopInvariantBackedgeTakenCount).
2237///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002238SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002239 return getBackedgeTakenInfo(L).Exact;
2240}
2241
2242/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2243/// return the least SCEV value that is known never to be less than the
2244/// actual backedge taken count.
2245SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2246 return getBackedgeTakenInfo(L).Max;
2247}
2248
2249const ScalarEvolution::BackedgeTakenInfo &
2250ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002251 // Initially insert a CouldNotCompute for this loop. If the insertion
2252 // succeeds, procede to actually compute a backedge-taken count and
2253 // update the value. The temporary CouldNotCompute value tells SCEV
2254 // code elsewhere that it shouldn't attempt to request a new
2255 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002256 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002257 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2258 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002259 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2260 if (ItCount.Exact != UnknownValue) {
2261 assert(ItCount.Exact->isLoopInvariant(L) &&
2262 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002263 "Computed trip count isn't loop invariant for loop!");
2264 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002265
Dan Gohmana9dba962009-04-27 20:16:15 +00002266 // Update the value in the map.
2267 Pair.first->second = ItCount;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002268 } else if (isa<PHINode>(L->getHeader()->begin())) {
2269 // Only count loops that have phi nodes as not being computable.
2270 ++NumTripCountsNotComputed;
2271 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002272
2273 // Now that we know more about the trip count for this loop, forget any
2274 // existing SCEV values for PHI nodes in this loop since they are only
2275 // conservative estimates made without the benefit
2276 // of trip count information.
2277 if (ItCount.hasAnyInfo())
Dan Gohman94623022009-05-02 17:43:35 +00002278 forgetLoopPHIs(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002279 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002280 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002281}
2282
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002283/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002284/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002285/// ScalarEvolution's ability to compute a trip count, or if the loop
2286/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002287void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002288 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002289 forgetLoopPHIs(L);
2290}
2291
2292/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2293/// PHI nodes in the given loop. This is used when the trip count of
2294/// the loop may have changed.
2295void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002296 BasicBlock *Header = L->getHeader();
2297
2298 SmallVector<Instruction *, 16> Worklist;
2299 for (BasicBlock::iterator I = Header->begin();
Dan Gohman94623022009-05-02 17:43:35 +00002300 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Dan Gohmanbff6b582009-05-04 22:30:44 +00002301 Worklist.push_back(PN);
2302
2303 while (!Worklist.empty()) {
2304 Instruction *I = Worklist.pop_back_val();
2305 if (Scalars.erase(I))
2306 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2307 UI != UE; ++UI)
2308 Worklist.push_back(cast<Instruction>(UI));
2309 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002310}
2311
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002312/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2313/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002314ScalarEvolution::BackedgeTakenInfo
2315ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002316 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00002317 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002318 L->getExitBlocks(ExitBlocks);
2319 if (ExitBlocks.size() != 1) return UnknownValue;
2320
2321 // Okay, there is one exit block. Try to find the condition that causes the
2322 // loop to be exited.
2323 BasicBlock *ExitBlock = ExitBlocks[0];
2324
2325 BasicBlock *ExitingBlock = 0;
2326 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2327 PI != E; ++PI)
2328 if (L->contains(*PI)) {
2329 if (ExitingBlock == 0)
2330 ExitingBlock = *PI;
2331 else
2332 return UnknownValue; // More than one block exiting!
2333 }
2334 assert(ExitingBlock && "No exits from loop, something is broken!");
2335
2336 // Okay, we've computed the exiting block. See what condition causes us to
2337 // exit.
2338 //
2339 // FIXME: we should be able to handle switch instructions (with a single exit)
2340 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2341 if (ExitBr == 0) return UnknownValue;
2342 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2343
2344 // At this point, we know we have a conditional branch that determines whether
2345 // the loop is exited. However, we don't know if the branch is executed each
2346 // time through the loop. If not, then the execution count of the branch will
2347 // not be equal to the trip count of the loop.
2348 //
2349 // Currently we check for this by checking to see if the Exit branch goes to
2350 // the loop header. If so, we know it will always execute the same number of
2351 // times as the loop. We also handle the case where the exit block *is* the
2352 // loop header. This is common for un-rotated loops. More extensive analysis
2353 // could be done to handle more cases here.
2354 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2355 ExitBr->getSuccessor(1) != L->getHeader() &&
2356 ExitBr->getParent() != L->getHeader())
2357 return UnknownValue;
2358
2359 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2360
Nick Lewyckyb3d24332008-02-21 08:34:02 +00002361 // If it's not an integer comparison then compute it the hard way.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002362 // Note that ICmpInst deals with pointer comparisons too so we must check
2363 // the type of the operand.
2364 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002365 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002366 ExitBr->getSuccessor(0) == ExitBlock);
2367
2368 // If the condition was exit on true, convert the condition to exit on false
2369 ICmpInst::Predicate Cond;
2370 if (ExitBr->getSuccessor(1) == ExitBlock)
2371 Cond = ExitCond->getPredicate();
2372 else
2373 Cond = ExitCond->getInversePredicate();
2374
2375 // Handle common loops like: for (X = "string"; *X; ++X)
2376 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2377 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2378 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002379 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002380 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2381 }
2382
2383 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2384 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2385
2386 // Try to evaluate any dependencies out of the loop.
2387 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2388 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2389 Tmp = getSCEVAtScope(RHS, L);
2390 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2391
2392 // At this point, we would like to compute how many iterations of the
2393 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002394 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2395 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002396 std::swap(LHS, RHS);
2397 Cond = ICmpInst::getSwappedPredicate(Cond);
2398 }
2399
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002400 // If we have a comparison of a chrec against a constant, try to use value
2401 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002402 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2403 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002404 if (AddRec->getLoop() == L) {
2405 // Form the comparison range using the constant of the correct type so
2406 // that the ConstantRange class knows to do a signed or unsigned
2407 // comparison.
2408 ConstantInt *CompVal = RHSC->getValue();
2409 const Type *RealTy = ExitCond->getOperand(0)->getType();
2410 CompVal = dyn_cast<ConstantInt>(
2411 ConstantExpr::getBitCast(CompVal, RealTy));
2412 if (CompVal) {
2413 // Form the constant range.
2414 ConstantRange CompRange(
2415 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2416
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002417 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002418 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2419 }
2420 }
2421
2422 switch (Cond) {
2423 case ICmpInst::ICMP_NE: { // while (X != Y)
2424 // Convert to: while (X-Y != 0)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002425 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002426 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2427 break;
2428 }
2429 case ICmpInst::ICMP_EQ: {
2430 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002431 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002432 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2433 break;
2434 }
2435 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002436 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2437 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002438 break;
2439 }
2440 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002441 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2442 getNotSCEV(RHS), L, true);
2443 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002444 break;
2445 }
2446 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002447 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2448 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002449 break;
2450 }
2451 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002452 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2453 getNotSCEV(RHS), L, false);
2454 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002455 break;
2456 }
2457 default:
2458#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002459 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002460 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002461 errs() << "[unsigned] ";
2462 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002463 << Instruction::getOpcodeName(Instruction::ICmp)
2464 << " " << *RHS << "\n";
2465#endif
2466 break;
2467 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002468 return
2469 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2470 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002471}
2472
2473static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002474EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2475 ScalarEvolution &SE) {
2476 SCEVHandle InVal = SE.getConstant(C);
2477 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002478 assert(isa<SCEVConstant>(Val) &&
2479 "Evaluation of SCEV at constant didn't fold correctly?");
2480 return cast<SCEVConstant>(Val)->getValue();
2481}
2482
2483/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2484/// and a GEP expression (missing the pointer index) indexing into it, return
2485/// the addressed element of the initializer or null if the index expression is
2486/// invalid.
2487static Constant *
2488GetAddressedElementFromGlobal(GlobalVariable *GV,
2489 const std::vector<ConstantInt*> &Indices) {
2490 Constant *Init = GV->getInitializer();
2491 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2492 uint64_t Idx = Indices[i]->getZExtValue();
2493 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2494 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2495 Init = cast<Constant>(CS->getOperand(Idx));
2496 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2497 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2498 Init = cast<Constant>(CA->getOperand(Idx));
2499 } else if (isa<ConstantAggregateZero>(Init)) {
2500 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2501 assert(Idx < STy->getNumElements() && "Bad struct index!");
2502 Init = Constant::getNullValue(STy->getElementType(Idx));
2503 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2504 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2505 Init = Constant::getNullValue(ATy->getElementType());
2506 } else {
2507 assert(0 && "Unknown constant aggregate type!");
2508 }
2509 return 0;
2510 } else {
2511 return 0; // Unknown initializer type
2512 }
2513 }
2514 return Init;
2515}
2516
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002517/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2518/// 'icmp op load X, cst', try to see if we can compute the backedge
2519/// execution count.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002520SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002521ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2522 const Loop *L,
2523 ICmpInst::Predicate predicate) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002524 if (LI->isVolatile()) return UnknownValue;
2525
2526 // Check to see if the loaded pointer is a getelementptr of a global.
2527 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2528 if (!GEP) return UnknownValue;
2529
2530 // Make sure that it is really a constant global we are gepping, with an
2531 // initializer, and make sure the first IDX is really 0.
2532 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2533 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2534 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2535 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2536 return UnknownValue;
2537
2538 // Okay, we allow one non-constant index into the GEP instruction.
2539 Value *VarIdx = 0;
2540 std::vector<ConstantInt*> Indexes;
2541 unsigned VarIdxNum = 0;
2542 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2543 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2544 Indexes.push_back(CI);
2545 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2546 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2547 VarIdx = GEP->getOperand(i);
2548 VarIdxNum = i-2;
2549 Indexes.push_back(0);
2550 }
2551
2552 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2553 // Check to see if X is a loop variant variable value now.
2554 SCEVHandle Idx = getSCEV(VarIdx);
2555 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2556 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2557
2558 // We can only recognize very limited forms of loop index expressions, in
2559 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002560 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002561 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2562 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2563 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2564 return UnknownValue;
2565
2566 unsigned MaxSteps = MaxBruteForceIterations;
2567 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2568 ConstantInt *ItCst =
2569 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002570 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002571
2572 // Form the GEP offset.
2573 Indexes[VarIdxNum] = Val;
2574
2575 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2576 if (Result == 0) break; // Cannot compute!
2577
2578 // Evaluate the condition for this iteration.
2579 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2580 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2581 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2582#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002583 errs() << "\n***\n*** Computed loop count " << *ItCst
2584 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2585 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002586#endif
2587 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002588 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002589 }
2590 }
2591 return UnknownValue;
2592}
2593
2594
2595/// CanConstantFold - Return true if we can constant fold an instruction of the
2596/// specified type, assuming that all operands were constants.
2597static bool CanConstantFold(const Instruction *I) {
2598 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2599 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2600 return true;
2601
2602 if (const CallInst *CI = dyn_cast<CallInst>(I))
2603 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002604 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002605 return false;
2606}
2607
2608/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2609/// in the loop that V is derived from. We allow arbitrary operations along the
2610/// way, but the operands of an operation must either be constants or a value
2611/// derived from a constant PHI. If this expression does not fit with these
2612/// constraints, return null.
2613static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2614 // If this is not an instruction, or if this is an instruction outside of the
2615 // loop, it can't be derived from a loop PHI.
2616 Instruction *I = dyn_cast<Instruction>(V);
2617 if (I == 0 || !L->contains(I->getParent())) return 0;
2618
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002619 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002620 if (L->getHeader() == I->getParent())
2621 return PN;
2622 else
2623 // We don't currently keep track of the control flow needed to evaluate
2624 // PHIs, so we cannot handle PHIs inside of loops.
2625 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002626 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002627
2628 // If we won't be able to constant fold this expression even if the operands
2629 // are constants, return early.
2630 if (!CanConstantFold(I)) return 0;
2631
2632 // Otherwise, we can evaluate this instruction if all of its operands are
2633 // constant or derived from a PHI node themselves.
2634 PHINode *PHI = 0;
2635 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2636 if (!(isa<Constant>(I->getOperand(Op)) ||
2637 isa<GlobalValue>(I->getOperand(Op)))) {
2638 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2639 if (P == 0) return 0; // Not evolving from PHI
2640 if (PHI == 0)
2641 PHI = P;
2642 else if (PHI != P)
2643 return 0; // Evolving from multiple different PHIs.
2644 }
2645
2646 // This is a expression evolving from a constant PHI!
2647 return PHI;
2648}
2649
2650/// EvaluateExpression - Given an expression that passes the
2651/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2652/// in the loop has the value PHIVal. If we can't fold this expression for some
2653/// reason, return null.
2654static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2655 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002656 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002657 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002658 Instruction *I = cast<Instruction>(V);
2659
2660 std::vector<Constant*> Operands;
2661 Operands.resize(I->getNumOperands());
2662
2663 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2664 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2665 if (Operands[i] == 0) return 0;
2666 }
2667
Chris Lattnerd6e56912007-12-10 22:53:04 +00002668 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2669 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2670 &Operands[0], Operands.size());
2671 else
2672 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2673 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002674}
2675
2676/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2677/// in the header of its containing loop, we know the loop executes a
2678/// constant number of times, and the PHI node is just a recurrence
2679/// involving constants, fold it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002680Constant *ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002681getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002682 std::map<PHINode*, Constant*>::iterator I =
2683 ConstantEvolutionLoopExitValue.find(PN);
2684 if (I != ConstantEvolutionLoopExitValue.end())
2685 return I->second;
2686
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002687 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002688 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2689
2690 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2691
2692 // Since the loop is canonicalized, the PHI node must have two entries. One
2693 // entry must be a constant (coming in from outside of the loop), and the
2694 // second must be derived from the same PHI.
2695 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2696 Constant *StartCST =
2697 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2698 if (StartCST == 0)
2699 return RetVal = 0; // Must be a constant.
2700
2701 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2702 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2703 if (PN2 != PN)
2704 return RetVal = 0; // Not derived from same PHI.
2705
2706 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002707 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002708 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2709
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002710 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002711 unsigned IterationNum = 0;
2712 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2713 if (IterationNum == NumIterations)
2714 return RetVal = PHIVal; // Got exit value!
2715
2716 // Compute the value of the PHI node for the next iteration.
2717 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2718 if (NextPHI == PHIVal)
2719 return RetVal = NextPHI; // Stopped evolving!
2720 if (NextPHI == 0)
2721 return 0; // Couldn't evaluate!
2722 PHIVal = NextPHI;
2723 }
2724}
2725
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002726/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002727/// constant number of times (the condition evolves only from constants),
2728/// try to evaluate a few iterations of the loop until we get the exit
2729/// condition gets a value of ExitWhen (true or false). If we cannot
2730/// evaluate the trip count of the loop, return UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002731SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002732ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002733 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2734 if (PN == 0) return UnknownValue;
2735
2736 // Since the loop is canonicalized, the PHI node must have two entries. One
2737 // entry must be a constant (coming in from outside of the loop), and the
2738 // second must be derived from the same PHI.
2739 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2740 Constant *StartCST =
2741 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2742 if (StartCST == 0) return UnknownValue; // Must be a constant.
2743
2744 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2745 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2746 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2747
2748 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2749 // the loop symbolically to determine when the condition gets a value of
2750 // "ExitWhen".
2751 unsigned IterationNum = 0;
2752 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2753 for (Constant *PHIVal = StartCST;
2754 IterationNum != MaxIterations; ++IterationNum) {
2755 ConstantInt *CondVal =
2756 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2757
2758 // Couldn't symbolically evaluate.
2759 if (!CondVal) return UnknownValue;
2760
2761 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2762 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2763 ++NumBruteForceTripCountsComputed;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002764 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002765 }
2766
2767 // Compute the value of the PHI node for the next iteration.
2768 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2769 if (NextPHI == 0 || NextPHI == PHIVal)
2770 return UnknownValue; // Couldn't evaluate or not making progress...
2771 PHIVal = NextPHI;
2772 }
2773
2774 // Too many iterations were needed to evaluate.
2775 return UnknownValue;
2776}
2777
Dan Gohmandd40e9a2009-05-08 20:38:54 +00002778/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2779/// at the specified scope in the program. The L value specifies a loop
2780/// nest to evaluate the expression at, where null is the top-level or a
2781/// specified loop is immediately inside of the loop.
2782///
2783/// This method can be used to compute the exit value for a variable defined
2784/// in a loop by querying what the value will hold in the parent loop.
2785///
2786/// If this value is not computable at this scope, a SCEVCouldNotCompute
2787/// object is returned.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002788SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002789 // FIXME: this should be turned into a virtual method on SCEV!
2790
2791 if (isa<SCEVConstant>(V)) return V;
2792
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002793 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002794 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002795 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002796 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002797 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002798 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2799 if (PHINode *PN = dyn_cast<PHINode>(I))
2800 if (PN->getParent() == LI->getHeader()) {
2801 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002802 // to see if the loop that contains it has a known backedge-taken
2803 // count. If so, we may be able to force computation of the exit
2804 // value.
2805 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002806 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002807 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002808 // Okay, we know how many times the containing loop executes. If
2809 // this is a constant evolving PHI node, get the final value at
2810 // the specified iteration number.
2811 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002812 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002813 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002814 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002815 }
2816 }
2817
2818 // Okay, this is an expression that we cannot symbolically evaluate
2819 // into a SCEV. Check to see if it's possible to symbolically evaluate
2820 // the arguments into constants, and if so, try to constant propagate the
2821 // result. This is particularly useful for computing loop exit values.
2822 if (CanConstantFold(I)) {
Dan Gohmanda0071e2009-05-08 20:47:27 +00002823 // Check to see if we've folded this instruction at this loop before.
2824 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
2825 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
2826 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
2827 if (!Pair.second)
2828 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
2829
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002830 std::vector<Constant*> Operands;
2831 Operands.reserve(I->getNumOperands());
2832 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2833 Value *Op = I->getOperand(i);
2834 if (Constant *C = dyn_cast<Constant>(Op)) {
2835 Operands.push_back(C);
2836 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002837 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00002838 // non-integer and non-pointer, don't even try to analyze them
2839 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00002840 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00002841 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002842
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002843 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002844 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00002845 Constant *C = SC->getValue();
2846 if (C->getType() != Op->getType())
2847 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2848 Op->getType(),
2849 false),
2850 C, Op->getType());
2851 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002852 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00002853 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
2854 if (C->getType() != Op->getType())
2855 C =
2856 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2857 Op->getType(),
2858 false),
2859 C, Op->getType());
2860 Operands.push_back(C);
2861 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002862 return V;
2863 } else {
2864 return V;
2865 }
2866 }
2867 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002868
2869 Constant *C;
2870 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2871 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2872 &Operands[0], Operands.size());
2873 else
2874 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2875 &Operands[0], Operands.size());
Dan Gohmanda0071e2009-05-08 20:47:27 +00002876 Pair.first->second = C;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002877 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002878 }
2879 }
2880
2881 // This is some other type of SCEVUnknown, just return it.
2882 return V;
2883 }
2884
Dan Gohmanc76b5452009-05-04 22:02:23 +00002885 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002886 // Avoid performing the look-up in the common case where the specified
2887 // expression has no loop-variant portions.
2888 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2889 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2890 if (OpAtScope != Comm->getOperand(i)) {
2891 if (OpAtScope == UnknownValue) return UnknownValue;
2892 // Okay, at least one of these operands is loop variant but might be
2893 // foldable. Build a new instance of the folded commutative expression.
2894 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2895 NewOps.push_back(OpAtScope);
2896
2897 for (++i; i != e; ++i) {
2898 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2899 if (OpAtScope == UnknownValue) return UnknownValue;
2900 NewOps.push_back(OpAtScope);
2901 }
2902 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002903 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002904 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002905 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002906 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002907 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002908 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002909 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002910 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002911 }
2912 }
2913 // If we got here, all operands are loop invariant.
2914 return Comm;
2915 }
2916
Dan Gohmanc76b5452009-05-04 22:02:23 +00002917 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Nick Lewycky35b56022009-01-13 09:18:58 +00002918 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002919 if (LHS == UnknownValue) return LHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002920 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002921 if (RHS == UnknownValue) return RHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002922 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2923 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002924 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002925 }
2926
2927 // If this is a loop recurrence for a loop that does not contain L, then we
2928 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002929 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002930 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2931 // To evaluate this recurrence, we need to know how many times the AddRec
2932 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002933 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2934 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002935
Eli Friedman7489ec92008-08-04 23:49:06 +00002936 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002937 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002938 }
2939 return UnknownValue;
2940 }
2941
Dan Gohmanc76b5452009-05-04 22:02:23 +00002942 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00002943 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2944 if (Op == UnknownValue) return Op;
2945 if (Op == Cast->getOperand())
2946 return Cast; // must be loop invariant
2947 return getZeroExtendExpr(Op, Cast->getType());
2948 }
2949
Dan Gohmanc76b5452009-05-04 22:02:23 +00002950 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00002951 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2952 if (Op == UnknownValue) return Op;
2953 if (Op == Cast->getOperand())
2954 return Cast; // must be loop invariant
2955 return getSignExtendExpr(Op, Cast->getType());
2956 }
2957
Dan Gohmanc76b5452009-05-04 22:02:23 +00002958 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00002959 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2960 if (Op == UnknownValue) return Op;
2961 if (Op == Cast->getOperand())
2962 return Cast; // must be loop invariant
2963 return getTruncateExpr(Op, Cast->getType());
2964 }
2965
2966 assert(0 && "Unknown SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002967}
2968
Dan Gohmandd40e9a2009-05-08 20:38:54 +00002969/// getSCEVAtScope - This is a convenience function which does
2970/// getSCEVAtScope(getSCEV(V), L).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002971SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2972 return getSCEVAtScope(getSCEV(V), L);
2973}
2974
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002975/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2976/// following equation:
2977///
2978/// A * X = B (mod N)
2979///
2980/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2981/// A and B isn't important.
2982///
2983/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2984static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2985 ScalarEvolution &SE) {
2986 uint32_t BW = A.getBitWidth();
2987 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2988 assert(A != 0 && "A must be non-zero.");
2989
2990 // 1. D = gcd(A, N)
2991 //
2992 // The gcd of A and N may have only one prime factor: 2. The number of
2993 // trailing zeros in A is its multiplicity
2994 uint32_t Mult2 = A.countTrailingZeros();
2995 // D = 2^Mult2
2996
2997 // 2. Check if B is divisible by D.
2998 //
2999 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3000 // is not less than multiplicity of this prime factor for D.
3001 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00003002 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003003
3004 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3005 // modulo (N / D).
3006 //
3007 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3008 // bit width during computations.
3009 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3010 APInt Mod(BW + 1, 0);
3011 Mod.set(BW - Mult2); // Mod = N / D
3012 APInt I = AD.multiplicativeInverse(Mod);
3013
3014 // 4. Compute the minimum unsigned root of the equation:
3015 // I * (B / D) mod (N / D)
3016 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3017
3018 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3019 // bits.
3020 return SE.getConstant(Result.trunc(BW));
3021}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003022
3023/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3024/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3025/// might be the same) or two SCEVCouldNotCompute objects.
3026///
3027static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00003028SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003029 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00003030 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3031 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3032 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003033
3034 // We currently can only solve this if the coefficients are constants.
3035 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003036 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003037 return std::make_pair(CNC, CNC);
3038 }
3039
3040 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3041 const APInt &L = LC->getValue()->getValue();
3042 const APInt &M = MC->getValue()->getValue();
3043 const APInt &N = NC->getValue()->getValue();
3044 APInt Two(BitWidth, 2);
3045 APInt Four(BitWidth, 4);
3046
3047 {
3048 using namespace APIntOps;
3049 const APInt& C = L;
3050 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3051 // The B coefficient is M-N/2
3052 APInt B(M);
3053 B -= sdiv(N,Two);
3054
3055 // The A coefficient is N/2
3056 APInt A(N.sdiv(Two));
3057
3058 // Compute the B^2-4ac term.
3059 APInt SqrtTerm(B);
3060 SqrtTerm *= B;
3061 SqrtTerm -= Four * (A * C);
3062
3063 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3064 // integer value or else APInt::sqrt() will assert.
3065 APInt SqrtVal(SqrtTerm.sqrt());
3066
3067 // Compute the two solutions for the quadratic formula.
3068 // The divisions must be performed as signed divisions.
3069 APInt NegB(-B);
3070 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00003071 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003072 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00003073 return std::make_pair(CNC, CNC);
3074 }
3075
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003076 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3077 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
3078
Dan Gohman89f85052007-10-22 18:31:58 +00003079 return std::make_pair(SE.getConstant(Solution1),
3080 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003081 } // end APIntOps namespace
3082}
3083
3084/// HowFarToZero - Return the number of times a backedge comparing the specified
3085/// value to zero will execute. If not computable, return UnknownValue
Dan Gohmanbff6b582009-05-04 22:30:44 +00003086SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003087 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00003088 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003089 // If the value is already zero, the branch will execute zero times.
3090 if (C->getValue()->isZero()) return C;
3091 return UnknownValue; // Otherwise it will loop infinitely.
3092 }
3093
Dan Gohmanbff6b582009-05-04 22:30:44 +00003094 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003095 if (!AddRec || AddRec->getLoop() != L)
3096 return UnknownValue;
3097
3098 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003099 // If this is an affine expression, the execution count of this branch is
3100 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003101 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003102 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003103 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003104 // equivalent to:
3105 //
3106 // Step*N = -Start (mod 2^BW)
3107 //
3108 // where BW is the common bit width of Start and Step.
3109
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003110 // Get the initial value for the loop.
3111 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
3112 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003113
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003114 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003115
Dan Gohmanc76b5452009-05-04 22:02:23 +00003116 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003117 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003118
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003119 // First, handle unitary steps.
3120 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003121 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003122 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3123 return Start; // N = Start (as unsigned)
3124
3125 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003126 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003127 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003128 -StartC->getValue()->getValue(),
3129 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003130 }
3131 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3132 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3133 // the quadratic equation to solve it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003134 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
3135 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003136 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3137 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003138 if (R1) {
3139#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003140 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3141 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003142#endif
3143 // Pick the smallest positive root value.
3144 if (ConstantInt *CB =
3145 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3146 R1->getValue(), R2->getValue()))) {
3147 if (CB->getZExtValue() == false)
3148 std::swap(R1, R2); // R1 is the minimum root now.
3149
3150 // We can only use this value if the chrec ends up with an exact zero
3151 // value at this index. When solving for "X*X != 5", for example, we
3152 // should not accept a root of 2.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003153 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00003154 if (Val->isZero())
3155 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003156 }
3157 }
3158 }
3159
3160 return UnknownValue;
3161}
3162
3163/// HowFarToNonZero - Return the number of times a backedge checking the
3164/// specified value for nonzero will execute. If not computable, return
3165/// UnknownValue
Dan Gohmanbff6b582009-05-04 22:30:44 +00003166SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003167 // Loops that look like: while (X == 0) are very strange indeed. We don't
3168 // handle them yet except for the trivial case. This could be expanded in the
3169 // future as needed.
3170
3171 // If the value is a constant, check to see if it is known to be non-zero
3172 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003173 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00003174 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003175 return getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003176 return UnknownValue; // Otherwise it will loop infinitely.
3177 }
3178
3179 // We could implement others, but I really doubt anyone writes loops like
3180 // this, and if they did, they would already be constant folded.
3181 return UnknownValue;
3182}
3183
Dan Gohman1cddf972008-09-15 22:18:04 +00003184/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3185/// (which may not be an immediate predecessor) which has exactly one
3186/// successor from which BB is reachable, or null if no such block is
3187/// found.
3188///
3189BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003190ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00003191 // If the block has a unique predecessor, then there is no path from the
3192 // predecessor to the block that does not go through the direct edge
3193 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00003194 if (BasicBlock *Pred = BB->getSinglePredecessor())
3195 return Pred;
3196
3197 // A loop's header is defined to be a block that dominates the loop.
3198 // If the loop has a preheader, it must be a block that has exactly
3199 // one successor that can reach BB. This is slightly more strict
3200 // than necessary, but works if critical edges are split.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003201 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman1cddf972008-09-15 22:18:04 +00003202 return L->getLoopPreheader();
3203
3204 return 0;
3205}
3206
Dan Gohmancacd2012009-02-12 22:19:27 +00003207/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman1116ea72009-04-30 20:48:53 +00003208/// a conditional between LHS and RHS. This is used to help avoid max
3209/// expressions in loop trip counts.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003210bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman1116ea72009-04-30 20:48:53 +00003211 ICmpInst::Predicate Pred,
Dan Gohmanbff6b582009-05-04 22:30:44 +00003212 const SCEV *LHS, const SCEV *RHS) {
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003213 BasicBlock *Preheader = L->getLoopPreheader();
3214 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003215
Dan Gohmanab678fb2008-08-12 20:17:31 +00003216 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohman1cddf972008-09-15 22:18:04 +00003217 // there are predecessors that can be found that have unique successors
3218 // leading to the original header.
3219 for (; Preheader;
3220 PreheaderDest = Preheader,
3221 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00003222
3223 BranchInst *LoopEntryPredicate =
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003224 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00003225 if (!LoopEntryPredicate ||
3226 LoopEntryPredicate->isUnconditional())
3227 continue;
3228
3229 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3230 if (!ICI) continue;
3231
3232 // Now that we found a conditional branch that dominates the loop, check to
3233 // see if it is the comparison we are looking for.
3234 Value *PreCondLHS = ICI->getOperand(0);
3235 Value *PreCondRHS = ICI->getOperand(1);
3236 ICmpInst::Predicate Cond;
3237 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3238 Cond = ICI->getPredicate();
3239 else
3240 Cond = ICI->getInversePredicate();
3241
Dan Gohmancacd2012009-02-12 22:19:27 +00003242 if (Cond == Pred)
3243 ; // An exact match.
3244 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3245 ; // The actual condition is beyond sufficient.
3246 else
3247 // Check a few special cases.
3248 switch (Cond) {
3249 case ICmpInst::ICMP_UGT:
3250 if (Pred == ICmpInst::ICMP_ULT) {
3251 std::swap(PreCondLHS, PreCondRHS);
3252 Cond = ICmpInst::ICMP_ULT;
3253 break;
3254 }
3255 continue;
3256 case ICmpInst::ICMP_SGT:
3257 if (Pred == ICmpInst::ICMP_SLT) {
3258 std::swap(PreCondLHS, PreCondRHS);
3259 Cond = ICmpInst::ICMP_SLT;
3260 break;
3261 }
3262 continue;
3263 case ICmpInst::ICMP_NE:
3264 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3265 // so check for this case by checking if the NE is comparing against
3266 // a minimum or maximum constant.
3267 if (!ICmpInst::isTrueWhenEqual(Pred))
3268 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3269 const APInt &A = CI->getValue();
3270 switch (Pred) {
3271 case ICmpInst::ICMP_SLT:
3272 if (A.isMaxSignedValue()) break;
3273 continue;
3274 case ICmpInst::ICMP_SGT:
3275 if (A.isMinSignedValue()) break;
3276 continue;
3277 case ICmpInst::ICMP_ULT:
3278 if (A.isMaxValue()) break;
3279 continue;
3280 case ICmpInst::ICMP_UGT:
3281 if (A.isMinValue()) break;
3282 continue;
3283 default:
3284 continue;
3285 }
3286 Cond = ICmpInst::ICMP_NE;
3287 // NE is symmetric but the original comparison may not be. Swap
3288 // the operands if necessary so that they match below.
3289 if (isa<SCEVConstant>(LHS))
3290 std::swap(PreCondLHS, PreCondRHS);
3291 break;
3292 }
3293 continue;
3294 default:
3295 // We weren't able to reconcile the condition.
3296 continue;
3297 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003298
3299 if (!PreCondLHS->getType()->isInteger()) continue;
3300
3301 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3302 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3303 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003304 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3305 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohmanab678fb2008-08-12 20:17:31 +00003306 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003307 }
3308
Dan Gohmanab678fb2008-08-12 20:17:31 +00003309 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003310}
3311
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003312/// HowManyLessThans - Return the number of times a backedge containing the
3313/// specified less-than comparison will execute. If not computable, return
3314/// UnknownValue.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003315ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Dan Gohmanbff6b582009-05-04 22:30:44 +00003316HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3317 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003318 // Only handle: "ADDREC < LoopInvariant".
3319 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3320
Dan Gohmanbff6b582009-05-04 22:30:44 +00003321 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003322 if (!AddRec || AddRec->getLoop() != L)
3323 return UnknownValue;
3324
3325 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003326 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003327 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3328 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3329 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3330
3331 // TODO: handle non-constant strides.
3332 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3333 if (!CStep || CStep->isZero())
3334 return UnknownValue;
3335 if (CStep->getValue()->getValue() == 1) {
3336 // With unit stride, the iteration never steps past the limit value.
3337 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3338 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3339 // Test whether a positive iteration iteration can step past the limit
3340 // value and past the maximum value for its type in a single step.
3341 if (isSigned) {
3342 APInt Max = APInt::getSignedMaxValue(BitWidth);
3343 if ((Max - CStep->getValue()->getValue())
3344 .slt(CLimit->getValue()->getValue()))
3345 return UnknownValue;
3346 } else {
3347 APInt Max = APInt::getMaxValue(BitWidth);
3348 if ((Max - CStep->getValue()->getValue())
3349 .ult(CLimit->getValue()->getValue()))
3350 return UnknownValue;
3351 }
3352 } else
3353 // TODO: handle non-constant limit values below.
3354 return UnknownValue;
3355 } else
3356 // TODO: handle negative strides below.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003357 return UnknownValue;
3358
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003359 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3360 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3361 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00003362 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003363
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003364 // First, we get the value of the LHS in the first iteration: n
3365 SCEVHandle Start = AddRec->getOperand(0);
3366
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003367 // Determine the minimum constant start value.
3368 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3369 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3370 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003371
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003372 // If we know that the condition is true in order to enter the loop,
3373 // then we know that it will run exactly (m-n)/s times. Otherwise, we
3374 // only know if will execute (max(m,n)-n)/s times. In both cases, the
3375 // division must round up.
3376 SCEVHandle End = RHS;
3377 if (!isLoopGuardedByCond(L,
3378 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3379 getMinusSCEV(Start, Step), RHS))
3380 End = isSigned ? getSMaxExpr(RHS, Start)
3381 : getUMaxExpr(RHS, Start);
3382
3383 // Determine the maximum constant end value.
3384 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3385 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3386 APInt::getMaxValue(BitWidth));
3387
3388 // Finally, we subtract these two values and divide, rounding up, to get
3389 // the number of times the backedge is executed.
3390 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3391 getAddExpr(Step, NegOne)),
3392 Step);
3393
3394 // The maximum backedge count is similar, except using the minimum start
3395 // value and the maximum end value.
3396 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3397 MinStart),
3398 getAddExpr(Step, NegOne)),
3399 Step);
3400
3401 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003402 }
3403
3404 return UnknownValue;
3405}
3406
3407/// getNumIterationsInRange - Return the number of iterations of this loop that
3408/// produce values in the specified constant range. Another way of looking at
3409/// this is that it returns the first iteration number where the value is not in
3410/// the condition, thus computing the exit count. If the iteration count can't
3411/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00003412SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3413 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003414 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003415 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003416
3417 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003418 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003419 if (!SC->getValue()->isZero()) {
3420 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003421 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3422 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00003423 if (const SCEVAddRecExpr *ShiftedAddRec =
3424 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003425 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003426 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003427 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003428 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003429 }
3430
3431 // The only time we can solve this is when we have all constant indices.
3432 // Otherwise, we cannot determine the overflow conditions.
3433 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3434 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003435 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003436
3437
3438 // Okay at this point we know that all elements of the chrec are constants and
3439 // that the start element is zero.
3440
3441 // First check to see if the range contains zero. If not, the first
3442 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003443 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003444 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003445 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003446
3447 if (isAffine()) {
3448 // If this is an affine expression then we have this situation:
3449 // Solve {0,+,A} in Range === Ax in Range
3450
3451 // We know that zero is in the range. If A is positive then we know that
3452 // the upper value of the range must be the first possible exit value.
3453 // If A is negative then the lower of the range is the last possible loop
3454 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003455 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003456 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3457 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3458
3459 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003460 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003461 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3462
3463 // Evaluate at the exit value. If we really did fall out of the valid
3464 // range, then we computed our trip count, otherwise wrap around or other
3465 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003466 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003467 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003468 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003469
3470 // Ensure that the previous value is in the range. This is a sanity check.
3471 assert(Range.contains(
3472 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003473 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003474 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003475 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003476 } else if (isQuadratic()) {
3477 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3478 // quadratic equation to solve it. To do this, we must frame our problem in
3479 // terms of figuring out when zero is crossed, instead of when
3480 // Range.getUpper() is crossed.
3481 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003482 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3483 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003484
3485 // Next, solve the constructed addrec
3486 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003487 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003488 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3489 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003490 if (R1) {
3491 // Pick the smallest positive root value.
3492 if (ConstantInt *CB =
3493 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3494 R1->getValue(), R2->getValue()))) {
3495 if (CB->getZExtValue() == false)
3496 std::swap(R1, R2); // R1 is the minimum root now.
3497
3498 // Make sure the root is not off by one. The returned iteration should
3499 // not be in the range, but the previous one should be. When solving
3500 // for "X*X < 5", for example, we should not return a root of 2.
3501 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003502 R1->getValue(),
3503 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003504 if (Range.contains(R1Val->getValue())) {
3505 // The next iteration must be out of the range...
3506 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3507
Dan Gohman89f85052007-10-22 18:31:58 +00003508 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003509 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003510 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003511 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003512 }
3513
3514 // If R1 was not in the range, then it is a good return value. Make
3515 // sure that R1-1 WAS in the range though, just in case.
3516 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003517 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003518 if (Range.contains(R1Val->getValue()))
3519 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003520 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003521 }
3522 }
3523 }
3524
Dan Gohman0ad08b02009-04-18 17:58:19 +00003525 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003526}
3527
3528
3529
3530//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00003531// SCEVCallbackVH Class Implementation
3532//===----------------------------------------------------------------------===//
3533
3534void SCEVCallbackVH::deleted() {
3535 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3536 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3537 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003538 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
3539 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003540 SE->Scalars.erase(getValPtr());
3541 // this now dangles!
3542}
3543
3544void SCEVCallbackVH::allUsesReplacedWith(Value *) {
3545 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3546
3547 // Forget all the expressions associated with users of the old value,
3548 // so that future queries will recompute the expressions using the new
3549 // value.
3550 SmallVector<User *, 16> Worklist;
3551 Value *Old = getValPtr();
3552 bool DeleteOld = false;
3553 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3554 UI != UE; ++UI)
3555 Worklist.push_back(*UI);
3556 while (!Worklist.empty()) {
3557 User *U = Worklist.pop_back_val();
3558 // Deleting the Old value will cause this to dangle. Postpone
3559 // that until everything else is done.
3560 if (U == Old) {
3561 DeleteOld = true;
3562 continue;
3563 }
3564 if (PHINode *PN = dyn_cast<PHINode>(U))
3565 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003566 if (Instruction *I = dyn_cast<Instruction>(U))
3567 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003568 if (SE->Scalars.erase(U))
3569 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3570 UI != UE; ++UI)
3571 Worklist.push_back(*UI);
3572 }
3573 if (DeleteOld) {
3574 if (PHINode *PN = dyn_cast<PHINode>(Old))
3575 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003576 if (Instruction *I = dyn_cast<Instruction>(Old))
3577 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003578 SE->Scalars.erase(Old);
3579 // this now dangles!
3580 }
3581 // this may dangle!
3582}
3583
3584SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
3585 : CallbackVH(V), SE(se) {}
3586
3587//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003588// ScalarEvolution Class Implementation
3589//===----------------------------------------------------------------------===//
3590
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003591ScalarEvolution::ScalarEvolution()
3592 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3593}
3594
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003595bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003596 this->F = &F;
3597 LI = &getAnalysis<LoopInfo>();
3598 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003599 return false;
3600}
3601
3602void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003603 Scalars.clear();
3604 BackedgeTakenCounts.clear();
3605 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanda0071e2009-05-08 20:47:27 +00003606 ValuesAtScopes.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003607}
3608
3609void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3610 AU.setPreservesAll();
3611 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003612}
3613
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003614bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003615 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003616}
3617
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003618static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003619 const Loop *L) {
3620 // Print all inner loops first
3621 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3622 PrintLoopInfo(OS, SE, *I);
3623
Nick Lewyckye5da1912008-01-02 02:49:20 +00003624 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003625
Devang Patel02451fa2007-08-21 00:31:24 +00003626 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003627 L->getExitBlocks(ExitBlocks);
3628 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003629 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003630
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003631 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3632 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003633 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003634 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003635 }
3636
Nick Lewyckye5da1912008-01-02 02:49:20 +00003637 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003638}
3639
Dan Gohman13058cc2009-04-21 00:47:46 +00003640void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003641 // ScalarEvolution's implementaiton of the print method is to print
3642 // out SCEV values of all instructions that are interesting. Doing
3643 // this potentially causes it to create new SCEV objects though,
3644 // which technically conflicts with the const qualifier. This isn't
3645 // observable from outside the class though (the hasSCEV function
3646 // notwithstanding), so casting away the const isn't dangerous.
3647 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003648
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003649 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003650 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00003651 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003652 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003653 OS << " --> ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003654 SCEVHandle SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003655 SV->print(OS);
3656 OS << "\t\t";
3657
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003658 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003659 OS << "Exits: ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003660 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003661 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3662 OS << "<<Unknown>>";
3663 } else {
3664 OS << *ExitValue;
3665 }
3666 }
3667
3668
3669 OS << "\n";
3670 }
3671
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003672 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3673 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3674 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003675}
Dan Gohman13058cc2009-04-21 00:47:46 +00003676
3677void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3678 raw_os_ostream OS(o);
3679 print(OS, M);
3680}