blob: 94fb871dc31b2dd2ef06ed6b6e77b95dfa9d43d1 [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"
Dan Gohmana7726c32009-06-16 19:52:01 +000071#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000072#include "llvm/Assembly/Writer.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000073#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000074#include "llvm/Support/CommandLine.h"
75#include "llvm/Support/Compiler.h"
76#include "llvm/Support/ConstantRange.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000077#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000078#include "llvm/Support/InstIterator.h"
79#include "llvm/Support/ManagedStatic.h"
80#include "llvm/Support/MathExtras.h"
Dan Gohman13058cc2009-04-21 00:47:46 +000081#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000082#include "llvm/ADT/Statistic.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000083#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084#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 Gohmanf8bc8e82009-05-18 15:22:39 +0000130bool SCEV::isOne() const {
131 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
132 return SC->getValue()->isOne();
133 return false;
134}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000135
136SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
Dan Gohmanffd36ba2009-04-21 23:15:49 +0000137SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138
139bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
140 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
141 return false;
142}
143
144const Type *SCEVCouldNotCompute::getType() const {
145 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
146 return 0;
147}
148
149bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
150 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
151 return false;
152}
153
154SCEVHandle SCEVCouldNotCompute::
155replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000156 const SCEVHandle &Conc,
157 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000158 return this;
159}
160
Dan Gohman13058cc2009-04-21 00:47:46 +0000161void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162 OS << "***COULDNOTCOMPUTE***";
163}
164
165bool SCEVCouldNotCompute::classof(const SCEV *S) {
166 return S->getSCEVType() == scCouldNotCompute;
167}
168
169
170// SCEVConstants - Only allow the creation of one SCEVConstant for any
171// particular value. Don't use a SCEVHandle here, or else the object will
172// never be deleted!
173static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
174
175
176SCEVConstant::~SCEVConstant() {
177 SCEVConstants->erase(V);
178}
179
Dan Gohman89f85052007-10-22 18:31:58 +0000180SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181 SCEVConstant *&R = (*SCEVConstants)[V];
182 if (R == 0) R = new SCEVConstant(V);
183 return R;
184}
185
Dan Gohman89f85052007-10-22 18:31:58 +0000186SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
187 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188}
189
Dan Gohman8fd520a2009-06-15 22:12:54 +0000190SCEVHandle
191ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
192 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
193}
194
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195const Type *SCEVConstant::getType() const { return V->getType(); }
196
Dan Gohman13058cc2009-04-21 00:47:46 +0000197void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198 WriteAsOperand(OS, V, false);
199}
200
Dan Gohman2a381532009-04-21 01:25:57 +0000201SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
202 const SCEVHandle &op, const Type *ty)
203 : SCEV(SCEVTy), Op(op), Ty(ty) {}
204
205SCEVCastExpr::~SCEVCastExpr() {}
206
207bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
208 return Op->dominates(BB, DT);
209}
210
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
212// particular input. Don't use a SCEVHandle here, or else the object will
213// never be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000214static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 SCEVTruncateExpr*> > SCEVTruncates;
216
217SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000218 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000219 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
220 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000221 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222}
223
224SCEVTruncateExpr::~SCEVTruncateExpr() {
225 SCEVTruncates->erase(std::make_pair(Op, Ty));
226}
227
Dan Gohman13058cc2009-04-21 00:47:46 +0000228void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000229 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230}
231
232// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
233// particular input. Don't use a SCEVHandle here, or else the object will never
234// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000235static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 SCEVZeroExtendExpr*> > SCEVZeroExtends;
237
238SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000239 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000240 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
241 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000243}
244
245SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
246 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
247}
248
Dan Gohman13058cc2009-04-21 00:47:46 +0000249void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000250 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251}
252
253// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
254// particular input. Don't use a SCEVHandle here, or else the object will never
255// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000256static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 SCEVSignExtendExpr*> > SCEVSignExtends;
258
259SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000260 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000261 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
262 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000263 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264}
265
266SCEVSignExtendExpr::~SCEVSignExtendExpr() {
267 SCEVSignExtends->erase(std::make_pair(Op, Ty));
268}
269
Dan Gohman13058cc2009-04-21 00:47:46 +0000270void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000271 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272}
273
274// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
275// particular input. Don't use a SCEVHandle here, or else the object will never
276// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000277static ManagedStatic<std::map<std::pair<unsigned, std::vector<const SCEV*> >,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000278 SCEVCommutativeExpr*> > SCEVCommExprs;
279
280SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000281 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
282 SCEVCommExprs->erase(std::make_pair(getSCEVType(), SCEVOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283}
284
Dan Gohman13058cc2009-04-21 00:47:46 +0000285void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
287 const char *OpStr = getOperationStr();
288 OS << "(" << *Operands[0];
289 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
290 OS << OpStr << *Operands[i];
291 OS << ")";
292}
293
294SCEVHandle SCEVCommutativeExpr::
295replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000296 const SCEVHandle &Conc,
297 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000298 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000299 SCEVHandle H =
300 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000301 if (H != getOperand(i)) {
Dan Gohman02ff9392009-06-14 22:47:23 +0000302 SmallVector<SCEVHandle, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000303 NewOps.reserve(getNumOperands());
304 for (unsigned j = 0; j != i; ++j)
305 NewOps.push_back(getOperand(j));
306 NewOps.push_back(H);
307 for (++i; i != e; ++i)
308 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000309 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000310
311 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000312 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000314 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000315 else if (isa<SCEVSMaxExpr>(this))
316 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000317 else if (isa<SCEVUMaxExpr>(this))
318 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000319 else
320 assert(0 && "Unknown commutative expr!");
321 }
322 }
323 return this;
324}
325
Dan Gohman72a8a022009-05-07 14:00:19 +0000326bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng98c073b2009-02-17 00:13:06 +0000327 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
328 if (!getOperand(i)->dominates(BB, DT))
329 return false;
330 }
331 return true;
332}
333
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000335// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336// input. Don't use a SCEVHandle here, or else the object will never be
337// deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000338static ManagedStatic<std::map<std::pair<const SCEV*, const SCEV*>,
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000339 SCEVUDivExpr*> > SCEVUDivs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000340
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000341SCEVUDivExpr::~SCEVUDivExpr() {
342 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000343}
344
Evan Cheng98c073b2009-02-17 00:13:06 +0000345bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
346 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
347}
348
Dan Gohman13058cc2009-04-21 00:47:46 +0000349void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000350 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000351}
352
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000353const Type *SCEVUDivExpr::getType() const {
Dan Gohman140f08f2009-05-26 17:44:05 +0000354 // In most cases the types of LHS and RHS will be the same, but in some
355 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
356 // depend on the type for correctness, but handling types carefully can
357 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
358 // a pointer type than the RHS, so use the RHS' type here.
359 return RHS->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000360}
361
362// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
363// particular input. Don't use a SCEVHandle here, or else the object will never
364// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000365static ManagedStatic<std::map<std::pair<const Loop *,
366 std::vector<const SCEV*> >,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000367 SCEVAddRecExpr*> > SCEVAddRecExprs;
368
369SCEVAddRecExpr::~SCEVAddRecExpr() {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000370 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
371 SCEVAddRecExprs->erase(std::make_pair(L, SCEVOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372}
373
374SCEVHandle SCEVAddRecExpr::
375replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000376 const SCEVHandle &Conc,
377 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000379 SCEVHandle H =
380 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000381 if (H != getOperand(i)) {
Dan Gohman02ff9392009-06-14 22:47:23 +0000382 SmallVector<SCEVHandle, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000383 NewOps.reserve(getNumOperands());
384 for (unsigned j = 0; j != i; ++j)
385 NewOps.push_back(getOperand(j));
386 NewOps.push_back(H);
387 for (++i; i != e; ++i)
388 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000389 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000390
Dan Gohman89f85052007-10-22 18:31:58 +0000391 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000392 }
393 }
394 return this;
395}
396
397
398bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
399 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
400 // contain L and if the start is invariant.
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000401 // Add recurrences are never invariant in the function-body (null loop).
402 return QueryLoop &&
403 !QueryLoop->contains(L->getHeader()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404 getOperand(0)->isLoopInvariant(QueryLoop);
405}
406
407
Dan Gohman13058cc2009-04-21 00:47:46 +0000408void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000409 OS << "{" << *Operands[0];
410 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
411 OS << ",+," << *Operands[i];
412 OS << "}<" << L->getHeader()->getName() + ">";
413}
414
415// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
416// value. Don't use a SCEVHandle here, or else the object will never be
417// deleted!
418static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
419
420SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
421
422bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
423 // All non-instruction values are loop invariant. All instructions are loop
424 // invariant if they are not contained in the specified loop.
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000425 // Instructions are never considered invariant in the function body
426 // (null loop) because they are defined within the "loop".
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000427 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000428 return L && !L->contains(I->getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000429 return true;
430}
431
Evan Cheng98c073b2009-02-17 00:13:06 +0000432bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
433 if (Instruction *I = dyn_cast<Instruction>(getValue()))
434 return DT->dominates(I->getParent(), BB);
435 return true;
436}
437
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000438const Type *SCEVUnknown::getType() const {
439 return V->getType();
440}
441
Dan Gohman13058cc2009-04-21 00:47:46 +0000442void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000443 WriteAsOperand(OS, V, false);
444}
445
446//===----------------------------------------------------------------------===//
447// SCEV Utilities
448//===----------------------------------------------------------------------===//
449
450namespace {
451 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
452 /// than the complexity of the RHS. This comparator is used to canonicalize
453 /// expressions.
Dan Gohman5d486452009-05-07 14:39:04 +0000454 class VISIBILITY_HIDDEN SCEVComplexityCompare {
455 LoopInfo *LI;
456 public:
457 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
458
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000459 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman5d486452009-05-07 14:39:04 +0000460 // Primarily, sort the SCEVs by their getSCEVType().
461 if (LHS->getSCEVType() != RHS->getSCEVType())
462 return LHS->getSCEVType() < RHS->getSCEVType();
463
464 // Aside from the getSCEVType() ordering, the particular ordering
465 // isn't very important except that it's beneficial to be consistent,
466 // so that (a + b) and (b + a) don't end up as different expressions.
467
468 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
469 // not as complete as it could be.
470 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
471 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
472
Dan Gohmand0c01232009-05-19 02:15:55 +0000473 // Order pointer values after integer values. This helps SCEVExpander
474 // form GEPs.
475 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
476 return false;
477 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
478 return true;
479
Dan Gohman5d486452009-05-07 14:39:04 +0000480 // Compare getValueID values.
481 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
482 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
483
484 // Sort arguments by their position.
485 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
486 const Argument *RA = cast<Argument>(RU->getValue());
487 return LA->getArgNo() < RA->getArgNo();
488 }
489
490 // For instructions, compare their loop depth, and their opcode.
491 // This is pretty loose.
492 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
493 Instruction *RV = cast<Instruction>(RU->getValue());
494
495 // Compare loop depths.
496 if (LI->getLoopDepth(LV->getParent()) !=
497 LI->getLoopDepth(RV->getParent()))
498 return LI->getLoopDepth(LV->getParent()) <
499 LI->getLoopDepth(RV->getParent());
500
501 // Compare opcodes.
502 if (LV->getOpcode() != RV->getOpcode())
503 return LV->getOpcode() < RV->getOpcode();
504
505 // Compare the number of operands.
506 if (LV->getNumOperands() != RV->getNumOperands())
507 return LV->getNumOperands() < RV->getNumOperands();
508 }
509
510 return false;
511 }
512
Dan Gohman56fc8f12009-06-14 22:51:25 +0000513 // Compare constant values.
514 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
515 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
516 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
517 }
518
519 // Compare addrec loop depths.
520 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
521 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
522 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
523 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
524 }
Dan Gohman5d486452009-05-07 14:39:04 +0000525
526 // Lexicographically compare n-ary expressions.
527 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
528 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
529 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
530 if (i >= RC->getNumOperands())
531 return false;
532 if (operator()(LC->getOperand(i), RC->getOperand(i)))
533 return true;
534 if (operator()(RC->getOperand(i), LC->getOperand(i)))
535 return false;
536 }
537 return LC->getNumOperands() < RC->getNumOperands();
538 }
539
Dan Gohman6e10db12009-05-07 19:23:21 +0000540 // Lexicographically compare udiv expressions.
541 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
542 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
543 if (operator()(LC->getLHS(), RC->getLHS()))
544 return true;
545 if (operator()(RC->getLHS(), LC->getLHS()))
546 return false;
547 if (operator()(LC->getRHS(), RC->getRHS()))
548 return true;
549 if (operator()(RC->getRHS(), LC->getRHS()))
550 return false;
551 return false;
552 }
553
Dan Gohman5d486452009-05-07 14:39:04 +0000554 // Compare cast expressions by operand.
555 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
556 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
557 return operator()(LC->getOperand(), RC->getOperand());
558 }
559
560 assert(0 && "Unknown SCEV kind!");
561 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000562 }
563 };
564}
565
566/// GroupByComplexity - Given a list of SCEV objects, order them by their
567/// complexity, and group objects of the same complexity together by value.
568/// When this routine is finished, we know that any duplicates in the vector are
569/// consecutive and that complexity is monotonically increasing.
570///
571/// Note that we go take special precautions to ensure that we get determinstic
572/// results from this routine. In other words, we don't want the results of
573/// this to depend on where the addresses of various SCEV objects happened to
574/// land in memory.
575///
Dan Gohman02ff9392009-06-14 22:47:23 +0000576static void GroupByComplexity(SmallVectorImpl<SCEVHandle> &Ops,
Dan Gohman5d486452009-05-07 14:39:04 +0000577 LoopInfo *LI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000578 if (Ops.size() < 2) return; // Noop
579 if (Ops.size() == 2) {
580 // This is the common case, which also happens to be trivially simple.
581 // Special case it.
Dan Gohman5d486452009-05-07 14:39:04 +0000582 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583 std::swap(Ops[0], Ops[1]);
584 return;
585 }
586
587 // Do the rough sort by complexity.
Dan Gohman5d486452009-05-07 14:39:04 +0000588 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000589
590 // Now that we are sorted by complexity, group elements of the same
591 // complexity. Note that this is, at worst, N^2, but the vector is likely to
592 // be extremely short in practice. Note that we take this approach because we
593 // do not want to depend on the addresses of the objects we are grouping.
594 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000595 const SCEV *S = Ops[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000596 unsigned Complexity = S->getSCEVType();
597
598 // If there are any objects of the same complexity and same value as this
599 // one, group them.
600 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
601 if (Ops[j] == S) { // Found a duplicate.
602 // Move it to immediately after i'th element.
603 std::swap(Ops[i+1], Ops[j]);
604 ++i; // no need to rescan it.
605 if (i == e-2) return; // Done!
606 }
607 }
608 }
609}
610
611
612
613//===----------------------------------------------------------------------===//
614// Simple SCEV method implementations
615//===----------------------------------------------------------------------===//
616
Eli Friedman7489ec92008-08-04 23:49:06 +0000617/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohmanc8a29272009-05-24 23:45:28 +0000618/// Assume, K > 0.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000619static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000620 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000621 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000622 // Handle the simplest case efficiently.
623 if (K == 1)
624 return SE.getTruncateOrZeroExtend(It, ResultTy);
625
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000626 // We are using the following formula for BC(It, K):
627 //
628 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
629 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000630 // Suppose, W is the bitwidth of the return value. We must be prepared for
631 // overflow. Hence, we must assure that the result of our computation is
632 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
633 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000634 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000635 // However, this code doesn't use exactly that formula; the formula it uses
636 // is something like the following, where T is the number of factors of 2 in
637 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
638 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000639 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000640 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000641 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000642 // This formula is trivially equivalent to the previous formula. However,
643 // this formula can be implemented much more efficiently. The trick is that
644 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
645 // arithmetic. To do exact division in modular arithmetic, all we have
646 // to do is multiply by the inverse. Therefore, this step can be done at
647 // width W.
648 //
649 // The next issue is how to safely do the division by 2^T. The way this
650 // is done is by doing the multiplication step at a width of at least W + T
651 // bits. This way, the bottom W+T bits of the product are accurate. Then,
652 // when we perform the division by 2^T (which is equivalent to a right shift
653 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
654 // truncated out after the division by 2^T.
655 //
656 // In comparison to just directly using the first formula, this technique
657 // is much more efficient; using the first formula requires W * K bits,
658 // but this formula less than W + K bits. Also, the first formula requires
659 // a division step, whereas this formula only requires multiplies and shifts.
660 //
661 // It doesn't matter whether the subtraction step is done in the calculation
662 // width or the input iteration count's width; if the subtraction overflows,
663 // the result must be zero anyway. We prefer here to do it in the width of
664 // the induction variable because it helps a lot for certain cases; CodeGen
665 // isn't smart enough to ignore the overflow, which leads to much less
666 // efficient code if the width of the subtraction is wider than the native
667 // register width.
668 //
669 // (It's possible to not widen at all by pulling out factors of 2 before
670 // the multiplication; for example, K=2 can be calculated as
671 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
672 // extra arithmetic, so it's not an obvious win, and it gets
673 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000674
Eli Friedman7489ec92008-08-04 23:49:06 +0000675 // Protection from insane SCEVs; this bound is conservative,
676 // but it probably doesn't matter.
677 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000678 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000679
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000680 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000681
Eli Friedman7489ec92008-08-04 23:49:06 +0000682 // Calculate K! / 2^T and T; we divide out the factors of two before
683 // multiplying for calculating K! / 2^T to avoid overflow.
684 // Other overflow doesn't matter because we only care about the bottom
685 // W bits of the result.
686 APInt OddFactorial(W, 1);
687 unsigned T = 1;
688 for (unsigned i = 3; i <= K; ++i) {
689 APInt Mult(W, i);
690 unsigned TwoFactors = Mult.countTrailingZeros();
691 T += TwoFactors;
692 Mult = Mult.lshr(TwoFactors);
693 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000694 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000695
Eli Friedman7489ec92008-08-04 23:49:06 +0000696 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000697 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000698
699 // Calcuate 2^T, at width T+W.
700 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
701
702 // Calculate the multiplicative inverse of K! / 2^T;
703 // this multiplication factor will perform the exact division by
704 // K! / 2^T.
705 APInt Mod = APInt::getSignedMinValue(W+1);
706 APInt MultiplyFactor = OddFactorial.zext(W+1);
707 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
708 MultiplyFactor = MultiplyFactor.trunc(W);
709
710 // Calculate the product, at width T+W
711 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
712 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
713 for (unsigned i = 1; i != K; ++i) {
714 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
715 Dividend = SE.getMulExpr(Dividend,
716 SE.getTruncateOrZeroExtend(S, CalculationTy));
717 }
718
719 // Divide by 2^T
720 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
721
722 // Truncate the result, and divide by K! / 2^T.
723
724 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
725 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000726}
727
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000728/// evaluateAtIteration - Return the value of this chain of recurrences at
729/// the specified iteration number. We can evaluate this recurrence by
730/// multiplying each element in the chain by the binomial coefficient
731/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
732///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000733/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000734///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000735/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000736///
Dan Gohman89f85052007-10-22 18:31:58 +0000737SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
738 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000740 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000741 // The computation is correct in the face of overflow provided that the
742 // multiplication is performed _after_ the evaluation of the binomial
743 // coefficient.
Dan Gohman01c2ee72009-04-16 03:18:22 +0000744 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000745 if (isa<SCEVCouldNotCompute>(Coeff))
746 return Coeff;
747
748 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000749 }
750 return Result;
751}
752
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000753//===----------------------------------------------------------------------===//
754// SCEV Expression folder implementations
755//===----------------------------------------------------------------------===//
756
Dan Gohman9c8abcc2009-05-01 16:44:56 +0000757SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
758 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000759 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000760 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000761 assert(isSCEVable(Ty) &&
762 "This is not a conversion to a SCEVable type!");
763 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000764
Dan Gohmanc76b5452009-05-04 22:02:23 +0000765 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000766 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000767 ConstantExpr::getTrunc(SC->getValue(), Ty));
768
Dan Gohman1a5c4992009-04-22 16:20:48 +0000769 // trunc(trunc(x)) --> trunc(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000770 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000771 return getTruncateExpr(ST->getOperand(), Ty);
772
Nick Lewycky37d04642009-04-23 05:15:08 +0000773 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000774 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000775 return getTruncateOrSignExtend(SS->getOperand(), Ty);
776
777 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000778 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000779 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
780
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000781 // If the input value is a chrec scev made out of constants, truncate
782 // all of the constants.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000783 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman02ff9392009-06-14 22:47:23 +0000784 SmallVector<SCEVHandle, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman45b3b542009-05-08 21:03:19 +0000786 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
787 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788 }
789
790 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
791 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
792 return Result;
793}
794
Dan Gohman36d40922009-04-16 19:25:55 +0000795SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
796 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000797 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000798 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000799 assert(isSCEVable(Ty) &&
800 "This is not a conversion to a SCEVable type!");
801 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000802
Dan Gohmanc76b5452009-05-04 22:02:23 +0000803 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000804 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000805 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
806 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
807 return getUnknown(C);
808 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000809
Dan Gohman1a5c4992009-04-22 16:20:48 +0000810 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000811 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000812 return getZeroExtendExpr(SZ->getOperand(), Ty);
813
Dan Gohmana9dba962009-04-27 20:16:15 +0000814 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000815 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000816 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000817 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000818 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000819 if (AR->isAffine()) {
820 // Check whether the backedge-taken count is SCEVCouldNotCompute.
821 // Note that this serves two purposes: It filters out loops that are
822 // simply not analyzable, and it covers the case where this code is
823 // being called from within backedge-taken count analysis, such that
824 // attempting to ask for the backedge-taken count would likely result
825 // in infinite recursion. In the later case, the analysis code will
826 // cope with a conservative value, and it will take care to purge
827 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000828 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
829 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000830 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000831 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000832 SCEVHandle Start = AR->getStart();
833 SCEVHandle Step = AR->getStepRecurrence(*this);
834
835 // Check whether the backedge-taken count can be losslessly casted to
836 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000837 SCEVHandle CastedMaxBECount =
838 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman3bb37f52009-05-18 15:58:39 +0000839 SCEVHandle RecastedMaxBECount =
840 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
841 if (MaxBECount == RecastedMaxBECount) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000842 const Type *WideTy =
843 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000844 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000845 SCEVHandle ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000846 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000847 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000848 SCEVHandle Add = getAddExpr(Start, ZMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000849 SCEVHandle OperandExtendedAdd =
850 getAddExpr(getZeroExtendExpr(Start, WideTy),
851 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
852 getZeroExtendExpr(Step, WideTy)));
853 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000854 // Return the expression with the addrec on the outside.
855 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
856 getZeroExtendExpr(Step, Ty),
857 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000858
859 // Similar to above, only this time treat the step value as signed.
860 // This covers loops that count down.
861 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000862 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000863 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000864 Add = getAddExpr(Start, SMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000865 OperandExtendedAdd =
866 getAddExpr(getZeroExtendExpr(Start, WideTy),
867 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
868 getSignExtendExpr(Step, WideTy)));
869 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000870 // Return the expression with the addrec on the outside.
871 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
872 getSignExtendExpr(Step, Ty),
873 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000874 }
875 }
876 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000877
878 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
879 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
880 return Result;
881}
882
Dan Gohmana9dba962009-04-27 20:16:15 +0000883SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
884 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000885 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000886 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000887 assert(isSCEVable(Ty) &&
888 "This is not a conversion to a SCEVable type!");
889 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000890
Dan Gohmanc76b5452009-05-04 22:02:23 +0000891 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000892 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000893 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
894 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
895 return getUnknown(C);
896 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000897
Dan Gohman1a5c4992009-04-22 16:20:48 +0000898 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000899 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000900 return getSignExtendExpr(SS->getOperand(), Ty);
901
Dan Gohmana9dba962009-04-27 20:16:15 +0000902 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000903 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000904 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000905 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000906 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000907 if (AR->isAffine()) {
908 // Check whether the backedge-taken count is SCEVCouldNotCompute.
909 // Note that this serves two purposes: It filters out loops that are
910 // simply not analyzable, and it covers the case where this code is
911 // being called from within backedge-taken count analysis, such that
912 // attempting to ask for the backedge-taken count would likely result
913 // in infinite recursion. In the later case, the analysis code will
914 // cope with a conservative value, and it will take care to purge
915 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000916 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
917 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000918 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000919 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000920 SCEVHandle Start = AR->getStart();
921 SCEVHandle Step = AR->getStepRecurrence(*this);
922
923 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000924 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000925 SCEVHandle CastedMaxBECount =
926 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman3bb37f52009-05-18 15:58:39 +0000927 SCEVHandle RecastedMaxBECount =
928 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
929 if (MaxBECount == RecastedMaxBECount) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000930 const Type *WideTy =
931 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000932 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000933 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000934 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000935 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000936 SCEVHandle Add = getAddExpr(Start, SMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000937 SCEVHandle OperandExtendedAdd =
938 getAddExpr(getSignExtendExpr(Start, WideTy),
939 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
940 getSignExtendExpr(Step, WideTy)));
941 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000942 // Return the expression with the addrec on the outside.
943 return getAddRecExpr(getSignExtendExpr(Start, Ty),
944 getSignExtendExpr(Step, Ty),
945 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000946 }
947 }
948 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000949
950 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
951 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
952 return Result;
953}
954
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000955/// getAnyExtendExpr - Return a SCEV for the given operand extended with
956/// unspecified bits out to the given type.
957///
958SCEVHandle ScalarEvolution::getAnyExtendExpr(const SCEVHandle &Op,
959 const Type *Ty) {
960 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
961 "This is not an extending conversion!");
962 assert(isSCEVable(Ty) &&
963 "This is not a conversion to a SCEVable type!");
964 Ty = getEffectiveSCEVType(Ty);
965
966 // Sign-extend negative constants.
967 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
968 if (SC->getValue()->getValue().isNegative())
969 return getSignExtendExpr(Op, Ty);
970
971 // Peel off a truncate cast.
972 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
973 SCEVHandle NewOp = T->getOperand();
974 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
975 return getAnyExtendExpr(NewOp, Ty);
976 return getTruncateOrNoop(NewOp, Ty);
977 }
978
979 // Next try a zext cast. If the cast is folded, use it.
980 SCEVHandle ZExt = getZeroExtendExpr(Op, Ty);
981 if (!isa<SCEVZeroExtendExpr>(ZExt))
982 return ZExt;
983
984 // Next try a sext cast. If the cast is folded, use it.
985 SCEVHandle SExt = getSignExtendExpr(Op, Ty);
986 if (!isa<SCEVSignExtendExpr>(SExt))
987 return SExt;
988
989 // If the expression is obviously signed, use the sext cast value.
990 if (isa<SCEVSMaxExpr>(Op))
991 return SExt;
992
993 // Absent any other information, use the zext cast value.
994 return ZExt;
995}
996
Dan Gohman27bd4cb2009-06-14 22:58:51 +0000997/// CollectAddOperandsWithScales - Process the given Ops list, which is
998/// a list of operands to be added under the given scale, update the given
999/// map. This is a helper function for getAddRecExpr. As an example of
1000/// what it does, given a sequence of operands that would form an add
1001/// expression like this:
1002///
1003/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1004///
1005/// where A and B are constants, update the map with these values:
1006///
1007/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1008///
1009/// and add 13 + A*B*29 to AccumulatedConstant.
1010/// This will allow getAddRecExpr to produce this:
1011///
1012/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1013///
1014/// This form often exposes folding opportunities that are hidden in
1015/// the original operand list.
1016///
1017/// Return true iff it appears that any interesting folding opportunities
1018/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1019/// the common case where no interesting opportunities are present, and
1020/// is also used as a check to avoid infinite recursion.
1021///
1022static bool
1023CollectAddOperandsWithScales(DenseMap<SCEVHandle, APInt> &M,
1024 SmallVector<SCEVHandle, 8> &NewOps,
1025 APInt &AccumulatedConstant,
1026 const SmallVectorImpl<SCEVHandle> &Ops,
1027 const APInt &Scale,
1028 ScalarEvolution &SE) {
1029 bool Interesting = false;
1030
1031 // Iterate over the add operands.
1032 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1033 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1034 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1035 APInt NewScale =
1036 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1037 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1038 // A multiplication of a constant with another add; recurse.
1039 Interesting |=
1040 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1041 cast<SCEVAddExpr>(Mul->getOperand(1))
1042 ->getOperands(),
1043 NewScale, SE);
1044 } else {
1045 // A multiplication of a constant with some other value. Update
1046 // the map.
1047 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1048 SCEVHandle Key = SE.getMulExpr(MulOps);
1049 std::pair<DenseMap<SCEVHandle, APInt>::iterator, bool> Pair =
1050 M.insert(std::make_pair(Key, APInt()));
1051 if (Pair.second) {
1052 Pair.first->second = NewScale;
1053 NewOps.push_back(Pair.first->first);
1054 } else {
1055 Pair.first->second += NewScale;
1056 // The map already had an entry for this value, which may indicate
1057 // a folding opportunity.
1058 Interesting = true;
1059 }
1060 }
1061 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1062 // Pull a buried constant out to the outside.
1063 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1064 Interesting = true;
1065 AccumulatedConstant += Scale * C->getValue()->getValue();
1066 } else {
1067 // An ordinary operand. Update the map.
1068 std::pair<DenseMap<SCEVHandle, APInt>::iterator, bool> Pair =
1069 M.insert(std::make_pair(Ops[i], APInt()));
1070 if (Pair.second) {
1071 Pair.first->second = Scale;
1072 NewOps.push_back(Pair.first->first);
1073 } else {
1074 Pair.first->second += Scale;
1075 // The map already had an entry for this value, which may indicate
1076 // a folding opportunity.
1077 Interesting = true;
1078 }
1079 }
1080 }
1081
1082 return Interesting;
1083}
1084
1085namespace {
1086 struct APIntCompare {
1087 bool operator()(const APInt &LHS, const APInt &RHS) const {
1088 return LHS.ult(RHS);
1089 }
1090 };
1091}
1092
Dan Gohmanc8a29272009-05-24 23:45:28 +00001093/// getAddExpr - Get a canonical add expression, or something simpler if
1094/// possible.
Dan Gohman02ff9392009-06-14 22:47:23 +00001095SCEVHandle ScalarEvolution::getAddExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001096 assert(!Ops.empty() && "Cannot get empty add!");
1097 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001098#ifndef NDEBUG
1099 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1100 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1101 getEffectiveSCEVType(Ops[0]->getType()) &&
1102 "SCEVAddExpr operand types don't match!");
1103#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001104
1105 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001106 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001107
1108 // If there are any constants, fold them together.
1109 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001110 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001111 ++Idx;
1112 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001113 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001114 // We found two constants, fold them together!
Dan Gohman02ff9392009-06-14 22:47:23 +00001115 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1116 RHSC->getValue()->getValue());
Dan Gohman68f23e82009-06-14 22:53:57 +00001117 if (Ops.size() == 2) return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001118 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001119 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001120 }
1121
1122 // If we are left with a constant zero being added, strip it off.
1123 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1124 Ops.erase(Ops.begin());
1125 --Idx;
1126 }
1127 }
1128
1129 if (Ops.size() == 1) return Ops[0];
1130
1131 // Okay, check to see if the same value occurs in the operand list twice. If
1132 // so, merge them together into an multiply expression. Since we sorted the
1133 // list, these values are required to be adjacent.
1134 const Type *Ty = Ops[0]->getType();
1135 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1136 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1137 // Found a match, merge the two values into a multiply, and add any
1138 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +00001139 SCEVHandle Two = getIntegerSCEV(2, Ty);
1140 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001141 if (Ops.size() == 2)
1142 return Mul;
1143 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1144 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +00001145 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146 }
1147
Dan Gohman45b3b542009-05-08 21:03:19 +00001148 // Check for truncates. If all the operands are truncated from the same
1149 // type, see if factoring out the truncate would permit the result to be
1150 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1151 // if the contents of the resulting outer trunc fold to something simple.
1152 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1153 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1154 const Type *DstType = Trunc->getType();
1155 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman02ff9392009-06-14 22:47:23 +00001156 SmallVector<SCEVHandle, 8> LargeOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001157 bool Ok = true;
1158 // Check all the operands to see if they can be represented in the
1159 // source type of the truncate.
1160 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1161 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1162 if (T->getOperand()->getType() != SrcType) {
1163 Ok = false;
1164 break;
1165 }
1166 LargeOps.push_back(T->getOperand());
1167 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1168 // This could be either sign or zero extension, but sign extension
1169 // is much more likely to be foldable here.
1170 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1171 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001172 SmallVector<SCEVHandle, 8> LargeMulOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001173 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1174 if (const SCEVTruncateExpr *T =
1175 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1176 if (T->getOperand()->getType() != SrcType) {
1177 Ok = false;
1178 break;
1179 }
1180 LargeMulOps.push_back(T->getOperand());
1181 } else if (const SCEVConstant *C =
1182 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1183 // This could be either sign or zero extension, but sign extension
1184 // is much more likely to be foldable here.
1185 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1186 } else {
1187 Ok = false;
1188 break;
1189 }
1190 }
1191 if (Ok)
1192 LargeOps.push_back(getMulExpr(LargeMulOps));
1193 } else {
1194 Ok = false;
1195 break;
1196 }
1197 }
1198 if (Ok) {
1199 // Evaluate the expression in the larger type.
1200 SCEVHandle Fold = getAddExpr(LargeOps);
1201 // If it folds to something simple, use it. Otherwise, don't.
1202 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1203 return getTruncateExpr(Fold, DstType);
1204 }
1205 }
1206
1207 // Skip past any other cast SCEVs.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001208 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1209 ++Idx;
1210
1211 // If there are add operands they would be next.
1212 if (Idx < Ops.size()) {
1213 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001214 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001215 // If we have an add, expand the add operands onto the end of the operands
1216 // list.
1217 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1218 Ops.erase(Ops.begin()+Idx);
1219 DeletedAdd = true;
1220 }
1221
1222 // If we deleted at least one add, we added operands to the end of the list,
1223 // and they are not necessarily sorted. Recurse to resort and resimplify
1224 // any operands we just aquired.
1225 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +00001226 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001227 }
1228
1229 // Skip over the add expression until we get to a multiply.
1230 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1231 ++Idx;
1232
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001233 // Check to see if there are any folding opportunities present with
1234 // operands multiplied by constant values.
1235 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1236 uint64_t BitWidth = getTypeSizeInBits(Ty);
1237 DenseMap<SCEVHandle, APInt> M;
1238 SmallVector<SCEVHandle, 8> NewOps;
1239 APInt AccumulatedConstant(BitWidth, 0);
1240 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1241 Ops, APInt(BitWidth, 1), *this)) {
1242 // Some interesting folding opportunity is present, so its worthwhile to
1243 // re-generate the operands list. Group the operands by constant scale,
1244 // to avoid multiplying by the same constant scale multiple times.
1245 std::map<APInt, SmallVector<SCEVHandle, 4>, APIntCompare> MulOpLists;
1246 for (SmallVector<SCEVHandle, 8>::iterator I = NewOps.begin(),
1247 E = NewOps.end(); I != E; ++I)
1248 MulOpLists[M.find(*I)->second].push_back(*I);
1249 // Re-generate the operands list.
1250 Ops.clear();
1251 if (AccumulatedConstant != 0)
1252 Ops.push_back(getConstant(AccumulatedConstant));
1253 for (std::map<APInt, SmallVector<SCEVHandle, 4>, APIntCompare>::iterator I =
1254 MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1255 if (I->first != 0)
1256 Ops.push_back(getMulExpr(getConstant(I->first), getAddExpr(I->second)));
1257 if (Ops.empty())
1258 return getIntegerSCEV(0, Ty);
1259 if (Ops.size() == 1)
1260 return Ops[0];
1261 return getAddExpr(Ops);
1262 }
1263 }
1264
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001265 // If we are adding something to a multiply expression, make sure the
1266 // something is not already an operand of the multiply. If so, merge it into
1267 // the multiply.
1268 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001269 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001270 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001271 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001272 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman02ff9392009-06-14 22:47:23 +00001273 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1275 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
1276 if (Mul->getNumOperands() != 2) {
1277 // If the multiply has more than two operands, we must get the
1278 // Y*Z term.
Dan Gohman02ff9392009-06-14 22:47:23 +00001279 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin(), Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001280 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001281 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001282 }
Dan Gohman89f85052007-10-22 18:31:58 +00001283 SCEVHandle One = getIntegerSCEV(1, Ty);
1284 SCEVHandle AddOne = getAddExpr(InnerMul, One);
1285 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001286 if (Ops.size() == 2) return OuterMul;
1287 if (AddOp < Idx) {
1288 Ops.erase(Ops.begin()+AddOp);
1289 Ops.erase(Ops.begin()+Idx-1);
1290 } else {
1291 Ops.erase(Ops.begin()+Idx);
1292 Ops.erase(Ops.begin()+AddOp-1);
1293 }
1294 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001295 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001296 }
1297
1298 // Check this multiply against other multiplies being added together.
1299 for (unsigned OtherMulIdx = Idx+1;
1300 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1301 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001302 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001303 // If MulOp occurs in OtherMul, we can fold the two multiplies
1304 // together.
1305 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1306 OMulOp != e; ++OMulOp)
1307 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1308 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1309 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1310 if (Mul->getNumOperands() != 2) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001311 SmallVector<SCEVHandle, 4> MulOps(Mul->op_begin(), Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001312 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001313 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001314 }
1315 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1316 if (OtherMul->getNumOperands() != 2) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001317 SmallVector<SCEVHandle, 4> MulOps(OtherMul->op_begin(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001318 OtherMul->op_end());
1319 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001320 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321 }
Dan Gohman89f85052007-10-22 18:31:58 +00001322 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1323 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001324 if (Ops.size() == 2) return OuterMul;
1325 Ops.erase(Ops.begin()+Idx);
1326 Ops.erase(Ops.begin()+OtherMulIdx-1);
1327 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001328 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001329 }
1330 }
1331 }
1332 }
1333
1334 // If there are any add recurrences in the operands list, see if any other
1335 // added values are loop invariant. If so, we can fold them into the
1336 // recurrence.
1337 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1338 ++Idx;
1339
1340 // Scan over all recurrences, trying to fold loop invariants into them.
1341 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1342 // Scan all of the other operands to this add and add them to the vector if
1343 // they are loop invariant w.r.t. the recurrence.
Dan Gohman02ff9392009-06-14 22:47:23 +00001344 SmallVector<SCEVHandle, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001345 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001346 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1347 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1348 LIOps.push_back(Ops[i]);
1349 Ops.erase(Ops.begin()+i);
1350 --i; --e;
1351 }
1352
1353 // If we found some loop invariants, fold them into the recurrence.
1354 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001355 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001356 LIOps.push_back(AddRec->getStart());
1357
Dan Gohman02ff9392009-06-14 22:47:23 +00001358 SmallVector<SCEVHandle, 4> AddRecOps(AddRec->op_begin(),
1359 AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001360 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361
Dan Gohman89f85052007-10-22 18:31:58 +00001362 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001363 // If all of the other operands were loop invariant, we are done.
1364 if (Ops.size() == 1) return NewRec;
1365
1366 // Otherwise, add the folded AddRec by the non-liv parts.
1367 for (unsigned i = 0;; ++i)
1368 if (Ops[i] == AddRec) {
1369 Ops[i] = NewRec;
1370 break;
1371 }
Dan Gohman89f85052007-10-22 18:31:58 +00001372 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001373 }
1374
1375 // Okay, if there weren't any loop invariants to be folded, check to see if
1376 // there are multiple AddRec's with the same loop induction variable being
1377 // added together. If so, we can fold them.
1378 for (unsigned OtherIdx = Idx+1;
1379 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1380 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001381 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001382 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1383 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman02ff9392009-06-14 22:47:23 +00001384 SmallVector<SCEVHandle, 4> NewOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001385 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1386 if (i >= NewOps.size()) {
1387 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1388 OtherAddRec->op_end());
1389 break;
1390 }
Dan Gohman89f85052007-10-22 18:31:58 +00001391 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001392 }
Dan Gohman89f85052007-10-22 18:31:58 +00001393 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001394
1395 if (Ops.size() == 2) return NewAddRec;
1396
1397 Ops.erase(Ops.begin()+Idx);
1398 Ops.erase(Ops.begin()+OtherIdx-1);
1399 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001400 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001401 }
1402 }
1403
1404 // Otherwise couldn't fold anything into this recurrence. Move onto the
1405 // next one.
1406 }
1407
1408 // Okay, it looks like we really DO need an add expr. Check to see if we
1409 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001410 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001411 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1412 SCEVOps)];
1413 if (Result == 0) Result = new SCEVAddExpr(Ops);
1414 return Result;
1415}
1416
1417
Dan Gohmanc8a29272009-05-24 23:45:28 +00001418/// getMulExpr - Get a canonical multiply expression, or something simpler if
1419/// possible.
Dan Gohman02ff9392009-06-14 22:47:23 +00001420SCEVHandle ScalarEvolution::getMulExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001421 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana77b3d42009-05-18 15:44:58 +00001422#ifndef NDEBUG
1423 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1424 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1425 getEffectiveSCEVType(Ops[0]->getType()) &&
1426 "SCEVMulExpr operand types don't match!");
1427#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001428
1429 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001430 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001431
1432 // If there are any constants, fold them together.
1433 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001434 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001435
1436 // C1*(C2+V) -> C1*C2 + C1*V
1437 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001438 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001439 if (Add->getNumOperands() == 2 &&
1440 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001441 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1442 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001443
1444
1445 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001446 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001447 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001448 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1449 RHSC->getValue()->getValue());
1450 Ops[0] = getConstant(Fold);
1451 Ops.erase(Ops.begin()+1); // Erase the folded element
1452 if (Ops.size() == 1) return Ops[0];
1453 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001454 }
1455
1456 // If we are left with a constant one being multiplied, strip it off.
1457 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1458 Ops.erase(Ops.begin());
1459 --Idx;
1460 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1461 // If we have a multiply of zero, it will always be zero.
1462 return Ops[0];
1463 }
1464 }
1465
1466 // Skip over the add expression until we get to a multiply.
1467 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1468 ++Idx;
1469
1470 if (Ops.size() == 1)
1471 return Ops[0];
1472
1473 // If there are mul operands inline them all into this expression.
1474 if (Idx < Ops.size()) {
1475 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001476 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001477 // If we have an mul, expand the mul operands onto the end of the operands
1478 // list.
1479 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1480 Ops.erase(Ops.begin()+Idx);
1481 DeletedMul = true;
1482 }
1483
1484 // If we deleted at least one mul, we added operands to the end of the list,
1485 // and they are not necessarily sorted. Recurse to resort and resimplify
1486 // any operands we just aquired.
1487 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001488 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001489 }
1490
1491 // If there are any add recurrences in the operands list, see if any other
1492 // added values are loop invariant. If so, we can fold them into the
1493 // recurrence.
1494 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1495 ++Idx;
1496
1497 // Scan over all recurrences, trying to fold loop invariants into them.
1498 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1499 // Scan all of the other operands to this mul and add them to the vector if
1500 // they are loop invariant w.r.t. the recurrence.
Dan Gohman02ff9392009-06-14 22:47:23 +00001501 SmallVector<SCEVHandle, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001502 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001503 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1504 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1505 LIOps.push_back(Ops[i]);
1506 Ops.erase(Ops.begin()+i);
1507 --i; --e;
1508 }
1509
1510 // If we found some loop invariants, fold them into the recurrence.
1511 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001512 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman02ff9392009-06-14 22:47:23 +00001513 SmallVector<SCEVHandle, 4> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001514 NewOps.reserve(AddRec->getNumOperands());
1515 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001516 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001517 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001518 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001519 } else {
1520 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001521 SmallVector<SCEVHandle, 4> MulOps(LIOps.begin(), LIOps.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001522 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001523 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001524 }
1525 }
1526
Dan Gohman89f85052007-10-22 18:31:58 +00001527 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001528
1529 // If all of the other operands were loop invariant, we are done.
1530 if (Ops.size() == 1) return NewRec;
1531
1532 // Otherwise, multiply the folded AddRec by the non-liv parts.
1533 for (unsigned i = 0;; ++i)
1534 if (Ops[i] == AddRec) {
1535 Ops[i] = NewRec;
1536 break;
1537 }
Dan Gohman89f85052007-10-22 18:31:58 +00001538 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001539 }
1540
1541 // Okay, if there weren't any loop invariants to be folded, check to see if
1542 // there are multiple AddRec's with the same loop induction variable being
1543 // multiplied together. If so, we can fold them.
1544 for (unsigned OtherIdx = Idx+1;
1545 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1546 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001547 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001548 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1549 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001550 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001551 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001552 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001553 SCEVHandle B = F->getStepRecurrence(*this);
1554 SCEVHandle D = G->getStepRecurrence(*this);
1555 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1556 getMulExpr(G, B),
1557 getMulExpr(B, D));
1558 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1559 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001560 if (Ops.size() == 2) return NewAddRec;
1561
1562 Ops.erase(Ops.begin()+Idx);
1563 Ops.erase(Ops.begin()+OtherIdx-1);
1564 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001565 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001566 }
1567 }
1568
1569 // Otherwise couldn't fold anything into this recurrence. Move onto the
1570 // next one.
1571 }
1572
1573 // Okay, it looks like we really DO need an mul expr. Check to see if we
1574 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001575 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001576 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1577 SCEVOps)];
1578 if (Result == 0)
1579 Result = new SCEVMulExpr(Ops);
1580 return Result;
1581}
1582
Dan Gohmanc8a29272009-05-24 23:45:28 +00001583/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1584/// possible.
Dan Gohman77841cd2009-05-04 22:23:18 +00001585SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1586 const SCEVHandle &RHS) {
Dan Gohmana77b3d42009-05-18 15:44:58 +00001587 assert(getEffectiveSCEVType(LHS->getType()) ==
1588 getEffectiveSCEVType(RHS->getType()) &&
1589 "SCEVUDivExpr operand types don't match!");
1590
Dan Gohmanc76b5452009-05-04 22:02:23 +00001591 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001592 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001593 return LHS; // X udiv 1 --> x
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001594 if (RHSC->isZero())
1595 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001596
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001597 // Determine if the division can be folded into the operands of
1598 // its operands.
1599 // TODO: Generalize this to non-constants by using known-bits information.
1600 const Type *Ty = LHS->getType();
1601 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1602 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1603 // For non-power-of-two values, effectively round the value up to the
1604 // nearest power of two.
1605 if (!RHSC->getValue()->getValue().isPowerOf2())
1606 ++MaxShiftAmt;
1607 const IntegerType *ExtTy =
1608 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1609 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1610 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1611 if (const SCEVConstant *Step =
1612 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1613 if (!Step->getValue()->getValue()
1614 .urem(RHSC->getValue()->getValue()) &&
Dan Gohman14374d32009-05-08 23:11:16 +00001615 getZeroExtendExpr(AR, ExtTy) ==
1616 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1617 getZeroExtendExpr(Step, ExtTy),
1618 AR->getLoop())) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001619 SmallVector<SCEVHandle, 4> Operands;
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001620 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1621 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1622 return getAddRecExpr(Operands, AR->getLoop());
1623 }
1624 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001625 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001626 SmallVector<SCEVHandle, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001627 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1628 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1629 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001630 // Find an operand that's safely divisible.
1631 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1632 SCEVHandle Op = M->getOperand(i);
1633 SCEVHandle Div = getUDivExpr(Op, RHSC);
1634 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001635 const SmallVectorImpl<SCEVHandle> &MOperands = M->getOperands();
1636 Operands = SmallVector<SCEVHandle, 4>(MOperands.begin(),
1637 MOperands.end());
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001638 Operands[i] = Div;
1639 return getMulExpr(Operands);
1640 }
1641 }
Dan Gohman14374d32009-05-08 23:11:16 +00001642 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001643 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001644 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001645 SmallVector<SCEVHandle, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001646 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1647 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1648 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1649 Operands.clear();
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001650 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1651 SCEVHandle Op = getUDivExpr(A->getOperand(i), RHS);
1652 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1653 break;
1654 Operands.push_back(Op);
1655 }
1656 if (Operands.size() == A->getNumOperands())
1657 return getAddExpr(Operands);
1658 }
Dan Gohman14374d32009-05-08 23:11:16 +00001659 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001660
1661 // Fold if both operands are constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001662 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001663 Constant *LHSCV = LHSC->getValue();
1664 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001665 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001666 }
1667 }
1668
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001669 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1670 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001671 return Result;
1672}
1673
1674
Dan Gohmanc8a29272009-05-24 23:45:28 +00001675/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1676/// Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001677SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001678 const SCEVHandle &Step, const Loop *L) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001679 SmallVector<SCEVHandle, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001680 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001681 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001682 if (StepChrec->getLoop() == L) {
1683 Operands.insert(Operands.end(), StepChrec->op_begin(),
1684 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001685 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001686 }
1687
1688 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001689 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001690}
1691
Dan Gohmanc8a29272009-05-24 23:45:28 +00001692/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1693/// Simplify the expression as much as possible.
Dan Gohman02ff9392009-06-14 22:47:23 +00001694SCEVHandle ScalarEvolution::getAddRecExpr(SmallVectorImpl<SCEVHandle> &Operands,
Nick Lewycky37d04642009-04-23 05:15:08 +00001695 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001696 if (Operands.size() == 1) return Operands[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001697#ifndef NDEBUG
1698 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1699 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1700 getEffectiveSCEVType(Operands[0]->getType()) &&
1701 "SCEVAddRecExpr operand types don't match!");
1702#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001703
Dan Gohman7b560c42008-06-18 16:23:07 +00001704 if (Operands.back()->isZero()) {
1705 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001706 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001707 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001708
Dan Gohman42936882008-08-08 18:33:12 +00001709 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001710 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001711 const Loop* NestedLoop = NestedAR->getLoop();
1712 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001713 SmallVector<SCEVHandle, 4> NestedOperands(NestedAR->op_begin(),
1714 NestedAR->op_end());
Dan Gohman42936882008-08-08 18:33:12 +00001715 SCEVHandle NestedARHandle(NestedAR);
1716 Operands[0] = NestedAR->getStart();
1717 NestedOperands[0] = getAddRecExpr(Operands, L);
1718 return getAddRecExpr(NestedOperands, NestedLoop);
1719 }
1720 }
1721
Dan Gohmanbff6b582009-05-04 22:30:44 +00001722 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1723 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001724 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1725 return Result;
1726}
1727
Nick Lewycky711640a2007-11-25 22:41:31 +00001728SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1729 const SCEVHandle &RHS) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001730 SmallVector<SCEVHandle, 2> Ops;
Nick Lewycky711640a2007-11-25 22:41:31 +00001731 Ops.push_back(LHS);
1732 Ops.push_back(RHS);
1733 return getSMaxExpr(Ops);
1734}
1735
Dan Gohman02ff9392009-06-14 22:47:23 +00001736SCEVHandle
1737ScalarEvolution::getSMaxExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001738 assert(!Ops.empty() && "Cannot get empty smax!");
1739 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001740#ifndef NDEBUG
1741 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1742 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1743 getEffectiveSCEVType(Ops[0]->getType()) &&
1744 "SCEVSMaxExpr operand types don't match!");
1745#endif
Nick Lewycky711640a2007-11-25 22:41:31 +00001746
1747 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001748 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001749
1750 // If there are any constants, fold them together.
1751 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001752 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001753 ++Idx;
1754 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001755 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001756 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001757 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001758 APIntOps::smax(LHSC->getValue()->getValue(),
1759 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001760 Ops[0] = getConstant(Fold);
1761 Ops.erase(Ops.begin()+1); // Erase the folded element
1762 if (Ops.size() == 1) return Ops[0];
1763 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001764 }
1765
1766 // If we are left with a constant -inf, strip it off.
1767 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1768 Ops.erase(Ops.begin());
1769 --Idx;
1770 }
1771 }
1772
1773 if (Ops.size() == 1) return Ops[0];
1774
1775 // Find the first SMax
1776 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1777 ++Idx;
1778
1779 // Check to see if one of the operands is an SMax. If so, expand its operands
1780 // onto our operand list, and recurse to simplify.
1781 if (Idx < Ops.size()) {
1782 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001783 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001784 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1785 Ops.erase(Ops.begin()+Idx);
1786 DeletedSMax = true;
1787 }
1788
1789 if (DeletedSMax)
1790 return getSMaxExpr(Ops);
1791 }
1792
1793 // Okay, check to see if the same value occurs in the operand list twice. If
1794 // so, delete one. Since we sorted the list, these values are required to
1795 // be adjacent.
1796 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1797 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1798 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1799 --i; --e;
1800 }
1801
1802 if (Ops.size() == 1) return Ops[0];
1803
1804 assert(!Ops.empty() && "Reduced smax down to nothing!");
1805
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001806 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001807 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001808 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewycky711640a2007-11-25 22:41:31 +00001809 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1810 SCEVOps)];
1811 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1812 return Result;
1813}
1814
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001815SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1816 const SCEVHandle &RHS) {
Dan Gohman02ff9392009-06-14 22:47:23 +00001817 SmallVector<SCEVHandle, 2> Ops;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001818 Ops.push_back(LHS);
1819 Ops.push_back(RHS);
1820 return getUMaxExpr(Ops);
1821}
1822
Dan Gohman02ff9392009-06-14 22:47:23 +00001823SCEVHandle
1824ScalarEvolution::getUMaxExpr(SmallVectorImpl<SCEVHandle> &Ops) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001825 assert(!Ops.empty() && "Cannot get empty umax!");
1826 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001827#ifndef NDEBUG
1828 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1829 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1830 getEffectiveSCEVType(Ops[0]->getType()) &&
1831 "SCEVUMaxExpr operand types don't match!");
1832#endif
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001833
1834 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001835 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001836
1837 // If there are any constants, fold them together.
1838 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001839 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001840 ++Idx;
1841 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001842 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001843 // We found two constants, fold them together!
1844 ConstantInt *Fold = ConstantInt::get(
1845 APIntOps::umax(LHSC->getValue()->getValue(),
1846 RHSC->getValue()->getValue()));
1847 Ops[0] = getConstant(Fold);
1848 Ops.erase(Ops.begin()+1); // Erase the folded element
1849 if (Ops.size() == 1) return Ops[0];
1850 LHSC = cast<SCEVConstant>(Ops[0]);
1851 }
1852
1853 // If we are left with a constant zero, strip it off.
1854 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1855 Ops.erase(Ops.begin());
1856 --Idx;
1857 }
1858 }
1859
1860 if (Ops.size() == 1) return Ops[0];
1861
1862 // Find the first UMax
1863 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1864 ++Idx;
1865
1866 // Check to see if one of the operands is a UMax. If so, expand its operands
1867 // onto our operand list, and recurse to simplify.
1868 if (Idx < Ops.size()) {
1869 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001870 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001871 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1872 Ops.erase(Ops.begin()+Idx);
1873 DeletedUMax = true;
1874 }
1875
1876 if (DeletedUMax)
1877 return getUMaxExpr(Ops);
1878 }
1879
1880 // Okay, check to see if the same value occurs in the operand list twice. If
1881 // so, delete one. Since we sorted the list, these values are required to
1882 // be adjacent.
1883 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1884 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1885 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1886 --i; --e;
1887 }
1888
1889 if (Ops.size() == 1) return Ops[0];
1890
1891 assert(!Ops.empty() && "Reduced umax down to nothing!");
1892
1893 // Okay, it looks like we really DO need a umax expr. Check to see if we
1894 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001895 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001896 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1897 SCEVOps)];
1898 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1899 return Result;
1900}
1901
Dan Gohman89f85052007-10-22 18:31:58 +00001902SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001903 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001904 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001905 if (isa<ConstantPointerNull>(V))
1906 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001907 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1908 if (Result == 0) Result = new SCEVUnknown(V);
1909 return Result;
1910}
1911
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001912//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001913// Basic SCEV Analysis and PHI Idiom Recognition Code
1914//
1915
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001916/// isSCEVable - Test if values of the given type are analyzable within
1917/// the SCEV framework. This primarily includes integer types, and it
1918/// can optionally include pointer types if the ScalarEvolution class
1919/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001920bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001921 // Integers are always SCEVable.
1922 if (Ty->isInteger())
1923 return true;
1924
1925 // Pointers are SCEVable if TargetData information is available
1926 // to provide pointer size information.
1927 if (isa<PointerType>(Ty))
1928 return TD != NULL;
1929
1930 // Otherwise it's not SCEVable.
1931 return false;
1932}
1933
1934/// getTypeSizeInBits - Return the size in bits of the specified type,
1935/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001936uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001937 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1938
1939 // If we have a TargetData, use it!
1940 if (TD)
1941 return TD->getTypeSizeInBits(Ty);
1942
1943 // Otherwise, we support only integer types.
1944 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1945 return Ty->getPrimitiveSizeInBits();
1946}
1947
1948/// getEffectiveSCEVType - Return a type with the same bitwidth as
1949/// the given type and which represents how SCEV will treat the given
1950/// type, for which isSCEVable must return true. For pointer types,
1951/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001952const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001953 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1954
1955 if (Ty->isInteger())
1956 return Ty;
1957
1958 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1959 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001960}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001961
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001962SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman0c850912009-06-06 14:37:11 +00001963 return CouldNotCompute;
Dan Gohman0ad08b02009-04-18 17:58:19 +00001964}
1965
Dan Gohmand83d4af2009-05-04 22:20:30 +00001966/// hasSCEV - Return true if the SCEV for this value has already been
Edwin Török0e828d62009-05-01 08:33:47 +00001967/// computed.
1968bool ScalarEvolution::hasSCEV(Value *V) const {
1969 return Scalars.count(V);
1970}
1971
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001972/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1973/// expression and create a new one.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001974SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001975 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001976
Dan Gohmanbff6b582009-05-04 22:30:44 +00001977 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001978 if (I != Scalars.end()) return I->second;
1979 SCEVHandle S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00001980 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001981 return S;
1982}
1983
Dan Gohman01c2ee72009-04-16 03:18:22 +00001984/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1985/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001986SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1987 Ty = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001988 Constant *C;
1989 if (Val == 0)
1990 C = Constant::getNullValue(Ty);
1991 else if (Ty->isFloatingPoint())
1992 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1993 APFloat::IEEEdouble, Val));
1994 else
1995 C = ConstantInt::get(Ty, Val);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001996 return getUnknown(C);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001997}
1998
1999/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2000///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002001SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002002 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002003 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002004
2005 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002006 Ty = getEffectiveSCEVType(Ty);
2007 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002008}
2009
2010/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002011SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002012 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002013 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002014
2015 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002016 Ty = getEffectiveSCEVType(Ty);
2017 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002018 return getMinusSCEV(AllOnes, V);
2019}
2020
2021/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2022///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002023SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky37d04642009-04-23 05:15:08 +00002024 const SCEVHandle &RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002025 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002026 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002027}
2028
2029/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2030/// input value to the specified type. If the type must be extended, it is zero
2031/// extended.
2032SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002033ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002034 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002035 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002036 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2037 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002038 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002039 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002040 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002041 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002042 return getTruncateExpr(V, Ty);
2043 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002044}
2045
2046/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2047/// input value to the specified type. If the type must be extended, it is sign
2048/// extended.
2049SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002050ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002051 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002052 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002053 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2054 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002055 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002056 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002057 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002058 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002059 return getTruncateExpr(V, Ty);
2060 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002061}
2062
Dan Gohmanac959332009-05-13 03:46:30 +00002063/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2064/// input value to the specified type. If the type must be extended, it is zero
2065/// extended. The conversion must not be narrowing.
2066SCEVHandle
2067ScalarEvolution::getNoopOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
2068 const Type *SrcTy = V->getType();
2069 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2070 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2071 "Cannot noop or zero extend with non-integer arguments!");
2072 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2073 "getNoopOrZeroExtend cannot truncate!");
2074 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2075 return V; // No conversion
2076 return getZeroExtendExpr(V, Ty);
2077}
2078
2079/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2080/// input value to the specified type. If the type must be extended, it is sign
2081/// extended. The conversion must not be narrowing.
2082SCEVHandle
2083ScalarEvolution::getNoopOrSignExtend(const SCEVHandle &V, const Type *Ty) {
2084 const Type *SrcTy = V->getType();
2085 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2086 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2087 "Cannot noop or sign extend with non-integer arguments!");
2088 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2089 "getNoopOrSignExtend cannot truncate!");
2090 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2091 return V; // No conversion
2092 return getSignExtendExpr(V, Ty);
2093}
2094
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002095/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2096/// the input value to the specified type. If the type must be extended,
2097/// it is extended with unspecified bits. The conversion must not be
2098/// narrowing.
2099SCEVHandle
2100ScalarEvolution::getNoopOrAnyExtend(const SCEVHandle &V, const Type *Ty) {
2101 const Type *SrcTy = V->getType();
2102 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2103 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2104 "Cannot noop or any extend with non-integer arguments!");
2105 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2106 "getNoopOrAnyExtend cannot truncate!");
2107 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2108 return V; // No conversion
2109 return getAnyExtendExpr(V, Ty);
2110}
2111
Dan Gohmanac959332009-05-13 03:46:30 +00002112/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2113/// input value to the specified type. The conversion must not be widening.
2114SCEVHandle
2115ScalarEvolution::getTruncateOrNoop(const SCEVHandle &V, const Type *Ty) {
2116 const Type *SrcTy = V->getType();
2117 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2118 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2119 "Cannot truncate or noop with non-integer arguments!");
2120 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2121 "getTruncateOrNoop cannot extend!");
2122 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2123 return V; // No conversion
2124 return getTruncateExpr(V, Ty);
2125}
2126
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002127/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2128/// the specified instruction and replaces any references to the symbolic value
2129/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002130void ScalarEvolution::
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002131ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
2132 const SCEVHandle &NewVal) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002133 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
2134 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002135 if (SI == Scalars.end()) return;
2136
2137 SCEVHandle NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002138 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002139 if (NV == SI->second) return; // No change.
2140
2141 SI->second = NV; // Update the scalars map!
2142
2143 // Any instruction values that use this instruction might also need to be
2144 // updated!
2145 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2146 UI != E; ++UI)
2147 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2148}
2149
2150/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2151/// a loop header, making it a potential recurrence, or it doesn't.
2152///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002153SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002154 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002155 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002156 if (L->getHeader() == PN->getParent()) {
2157 // If it lives in the loop header, it has two incoming values, one
2158 // from outside the loop, and one from inside.
2159 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2160 unsigned BackEdge = IncomingEdge^1;
2161
2162 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002163 SCEVHandle SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002164 assert(Scalars.find(PN) == Scalars.end() &&
2165 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002166 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002167
2168 // Using this symbolic name for the PHI, analyze the value coming around
2169 // the back-edge.
2170 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
2171
2172 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2173 // has a special value for the first iteration of the loop.
2174
2175 // If the value coming around the backedge is an add with the symbolic
2176 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00002177 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002178 // If there is a single occurrence of the symbolic value, replace it
2179 // with a recurrence.
2180 unsigned FoundIndex = Add->getNumOperands();
2181 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2182 if (Add->getOperand(i) == SymbolicName)
2183 if (FoundIndex == e) {
2184 FoundIndex = i;
2185 break;
2186 }
2187
2188 if (FoundIndex != Add->getNumOperands()) {
2189 // Create an add with everything but the specified operand.
Dan Gohman02ff9392009-06-14 22:47:23 +00002190 SmallVector<SCEVHandle, 8> Ops;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002191 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2192 if (i != FoundIndex)
2193 Ops.push_back(Add->getOperand(i));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002194 SCEVHandle Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002195
2196 // This is not a valid addrec if the step amount is varying each
2197 // loop iteration, but is not itself an addrec in this loop.
2198 if (Accum->isLoopInvariant(L) ||
2199 (isa<SCEVAddRecExpr>(Accum) &&
2200 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
2201 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002202 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002203
2204 // Okay, for the entire analysis of this edge we assumed the PHI
2205 // to be symbolic. We now need to go back and update all of the
2206 // entries for the scalars that use the PHI (except for the PHI
2207 // itself) to use the new analyzed value instead of the "symbolic"
2208 // value.
2209 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2210 return PHISCEV;
2211 }
2212 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00002213 } else if (const SCEVAddRecExpr *AddRec =
2214 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002215 // Otherwise, this could be a loop like this:
2216 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2217 // In this case, j = {1,+,1} and BEValue is j.
2218 // Because the other in-value of i (0) fits the evolution of BEValue
2219 // i really is an addrec evolution.
2220 if (AddRec->getLoop() == L && AddRec->isAffine()) {
2221 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2222
2223 // If StartVal = j.start - j.stride, we can use StartVal as the
2224 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002225 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00002226 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002227 SCEVHandle PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002228 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002229
2230 // Okay, for the entire analysis of this edge we assumed the PHI
2231 // to be symbolic. We now need to go back and update all of the
2232 // entries for the scalars that use the PHI (except for the PHI
2233 // itself) to use the new analyzed value instead of the "symbolic"
2234 // value.
2235 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2236 return PHISCEV;
2237 }
2238 }
2239 }
2240
2241 return SymbolicName;
2242 }
2243
2244 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002245 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002246}
2247
Dan Gohman509cf4d2009-05-08 20:26:55 +00002248/// createNodeForGEP - Expand GEP instructions into add and multiply
2249/// operations. This allows them to be analyzed by regular SCEV code.
2250///
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002251SCEVHandle ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman509cf4d2009-05-08 20:26:55 +00002252
2253 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002254 Value *Base = GEP->getOperand(0);
Dan Gohmand586a4f2009-05-09 00:14:52 +00002255 // Don't attempt to analyze GEPs over unsized objects.
2256 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2257 return getUnknown(GEP);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002258 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002259 gep_type_iterator GTI = gep_type_begin(GEP);
2260 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2261 E = GEP->op_end();
Dan Gohman509cf4d2009-05-08 20:26:55 +00002262 I != E; ++I) {
2263 Value *Index = *I;
2264 // Compute the (potentially symbolic) offset in bytes for this index.
2265 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2266 // For a struct, add the member offset.
2267 const StructLayout &SL = *TD->getStructLayout(STy);
2268 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2269 uint64_t Offset = SL.getElementOffset(FieldNo);
2270 TotalOffset = getAddExpr(TotalOffset,
2271 getIntegerSCEV(Offset, IntPtrTy));
2272 } else {
2273 // For an array, add the element offset, explicitly scaled.
2274 SCEVHandle LocalOffset = getSCEV(Index);
2275 if (!isa<PointerType>(LocalOffset->getType()))
2276 // Getelementptr indicies are signed.
2277 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2278 IntPtrTy);
2279 LocalOffset =
2280 getMulExpr(LocalOffset,
Duncan Sandsec4f97d2009-05-09 07:06:46 +00002281 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman509cf4d2009-05-08 20:26:55 +00002282 IntPtrTy));
2283 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2284 }
2285 }
2286 return getAddExpr(getSCEV(Base), TotalOffset);
2287}
2288
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002289/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2290/// guaranteed to end in (at every loop iteration). It is, at the same time,
2291/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2292/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002293static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002294 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00002295 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002296
Dan Gohmanc76b5452009-05-04 22:02:23 +00002297 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002298 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
2299 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002300
Dan Gohmanc76b5452009-05-04 22:02:23 +00002301 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002302 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2303 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
Dan Gohmanbfd51da2009-05-12 01:23:18 +00002304 SE.getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002305 }
2306
Dan Gohmanc76b5452009-05-04 22:02:23 +00002307 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002308 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2309 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
Dan Gohmanbfd51da2009-05-12 01:23:18 +00002310 SE.getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002311 }
2312
Dan Gohmanc76b5452009-05-04 22:02:23 +00002313 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002314 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002315 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002316 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002317 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002318 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002319 }
2320
Dan Gohmanc76b5452009-05-04 22:02:23 +00002321 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002322 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002323 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
2324 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002325 for (unsigned i = 1, e = M->getNumOperands();
2326 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002327 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002328 BitWidth);
2329 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002330 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002331
Dan Gohmanc76b5452009-05-04 22:02:23 +00002332 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002333 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002334 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002335 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002336 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002337 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002338 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002339
Dan Gohmanc76b5452009-05-04 22:02:23 +00002340 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00002341 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002342 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00002343 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002344 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00002345 return MinOpRes;
2346 }
2347
Dan Gohmanc76b5452009-05-04 22:02:23 +00002348 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002349 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002350 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002351 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002352 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002353 return MinOpRes;
2354 }
2355
Nick Lewycky35b56022009-01-13 09:18:58 +00002356 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002357 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002358}
2359
2360/// createSCEV - We know that there is no SCEV for the specified value.
2361/// Analyze the expression.
2362///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002363SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002364 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002365 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002366
Dan Gohman3996f472008-06-22 19:56:46 +00002367 unsigned Opcode = Instruction::UserOp1;
2368 if (Instruction *I = dyn_cast<Instruction>(V))
2369 Opcode = I->getOpcode();
2370 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2371 Opcode = CE->getOpcode();
2372 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002373 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002374
Dan Gohman3996f472008-06-22 19:56:46 +00002375 User *U = cast<User>(V);
2376 switch (Opcode) {
2377 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002378 return getAddExpr(getSCEV(U->getOperand(0)),
2379 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002380 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002381 return getMulExpr(getSCEV(U->getOperand(0)),
2382 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002383 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002384 return getUDivExpr(getSCEV(U->getOperand(0)),
2385 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002386 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002387 return getMinusSCEV(getSCEV(U->getOperand(0)),
2388 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002389 case Instruction::And:
2390 // For an expression like x&255 that merely masks off the high bits,
2391 // use zext(trunc(x)) as the SCEV expression.
2392 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002393 if (CI->isNullValue())
2394 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00002395 if (CI->isAllOnesValue())
2396 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002397 const APInt &A = CI->getValue();
Dan Gohmana7726c32009-06-16 19:52:01 +00002398
2399 // Instcombine's ShrinkDemandedConstant may strip bits out of
2400 // constants, obscuring what would otherwise be a low-bits mask.
2401 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2402 // knew about to reconstruct a low-bits mask value.
2403 unsigned LZ = A.countLeadingZeros();
2404 unsigned BitWidth = A.getBitWidth();
2405 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2406 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2407 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2408
2409 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2410
Dan Gohmanae1d7dd2009-06-17 23:54:37 +00002411 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman53bf64a2009-04-21 02:26:00 +00002412 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002413 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohmana7726c32009-06-16 19:52:01 +00002414 IntegerType::get(BitWidth - LZ)),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002415 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00002416 }
2417 break;
Dan Gohmana7726c32009-06-16 19:52:01 +00002418
Dan Gohman3996f472008-06-22 19:56:46 +00002419 case Instruction::Or:
2420 // If the RHS of the Or is a constant, we may have something like:
2421 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2422 // optimizations will transparently handle this case.
2423 //
2424 // In order for this transformation to be safe, the LHS must be of the
2425 // form X*(2^n) and the Or constant must be less than 2^n.
2426 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2427 SCEVHandle LHS = getSCEV(U->getOperand(0));
2428 const APInt &CIVal = CI->getValue();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002429 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman3996f472008-06-22 19:56:46 +00002430 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002431 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002432 }
Dan Gohman3996f472008-06-22 19:56:46 +00002433 break;
2434 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00002435 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00002436 // If the RHS of the xor is a signbit, then this is just an add.
2437 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00002438 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002439 return getAddExpr(getSCEV(U->getOperand(0)),
2440 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002441
2442 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmanc897f752009-05-18 16:17:44 +00002443 if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002444 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohmanfc78cff2009-05-18 16:29:04 +00002445
2446 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2447 // This is a variant of the check for xor with -1, and it handles
2448 // the case where instcombine has trimmed non-demanded bits out
2449 // of an xor with -1.
2450 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2451 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2452 if (BO->getOpcode() == Instruction::And &&
2453 LCI->getValue() == CI->getValue())
2454 if (const SCEVZeroExtendExpr *Z =
Dan Gohmane49ae432009-06-17 01:22:39 +00002455 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
2456 SCEVHandle ZO = Z->getOperand();
2457 if (APIntOps::isMask(getTypeSizeInBits(ZO->getType()),
2458 CI->getValue()))
2459 return getZeroExtendExpr(getNotSCEV(ZO), U->getType());
2460 }
Dan Gohman3996f472008-06-22 19:56:46 +00002461 }
2462 break;
2463
2464 case Instruction::Shl:
2465 // Turn shift left of a constant amount into a multiply.
2466 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2467 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2468 Constant *X = ConstantInt::get(
2469 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002470 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00002471 }
2472 break;
2473
Nick Lewycky7fd27892008-07-07 06:15:49 +00002474 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00002475 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00002476 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2477 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2478 Constant *X = ConstantInt::get(
2479 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002480 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002481 }
2482 break;
2483
Dan Gohman53bf64a2009-04-21 02:26:00 +00002484 case Instruction::AShr:
2485 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2486 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2487 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2488 if (L->getOpcode() == Instruction::Shl &&
2489 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002490 unsigned BitWidth = getTypeSizeInBits(U->getType());
2491 uint64_t Amt = BitWidth - CI->getZExtValue();
2492 if (Amt == BitWidth)
2493 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2494 if (Amt > BitWidth)
2495 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00002496 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002497 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00002498 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00002499 U->getType());
2500 }
2501 break;
2502
Dan Gohman3996f472008-06-22 19:56:46 +00002503 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002504 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002505
2506 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002507 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002508
2509 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002510 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002511
2512 case Instruction::BitCast:
2513 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002514 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002515 return getSCEV(U->getOperand(0));
2516 break;
2517
Dan Gohman01c2ee72009-04-16 03:18:22 +00002518 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002519 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002520 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002521 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002522
2523 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002524 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002525 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2526 U->getType());
2527
Dan Gohman509cf4d2009-05-08 20:26:55 +00002528 case Instruction::GetElementPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002529 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002530 return createNodeForGEP(U);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002531
Dan Gohman3996f472008-06-22 19:56:46 +00002532 case Instruction::PHI:
2533 return createNodeForPHI(cast<PHINode>(U));
2534
2535 case Instruction::Select:
2536 // This could be a smax or umax that was lowered earlier.
2537 // Try to recover it.
2538 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2539 Value *LHS = ICI->getOperand(0);
2540 Value *RHS = ICI->getOperand(1);
2541 switch (ICI->getPredicate()) {
2542 case ICmpInst::ICMP_SLT:
2543 case ICmpInst::ICMP_SLE:
2544 std::swap(LHS, RHS);
2545 // fall through
2546 case ICmpInst::ICMP_SGT:
2547 case ICmpInst::ICMP_SGE:
2548 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002549 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002550 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00002551 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002552 return getNotSCEV(getSMaxExpr(
2553 getNotSCEV(getSCEV(LHS)),
2554 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002555 break;
2556 case ICmpInst::ICMP_ULT:
2557 case ICmpInst::ICMP_ULE:
2558 std::swap(LHS, RHS);
2559 // fall through
2560 case ICmpInst::ICMP_UGT:
2561 case ICmpInst::ICMP_UGE:
2562 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002563 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002564 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2565 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002566 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2567 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002568 break;
2569 default:
2570 break;
2571 }
2572 }
2573
2574 default: // We cannot analyze this expression.
2575 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002576 }
2577
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002578 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002579}
2580
2581
2582
2583//===----------------------------------------------------------------------===//
2584// Iteration Count Computation Code
2585//
2586
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002587/// getBackedgeTakenCount - If the specified loop has a predictable
2588/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2589/// object. The backedge-taken count is the number of times the loop header
2590/// will be branched to from within the loop. This is one less than the
2591/// trip count of the loop, since it doesn't count the first iteration,
2592/// when the header is branched to from outside the loop.
2593///
2594/// Note that it is not valid to call this method on a loop without a
2595/// loop-invariant backedge-taken count (see
2596/// hasLoopInvariantBackedgeTakenCount).
2597///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002598SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002599 return getBackedgeTakenInfo(L).Exact;
2600}
2601
2602/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2603/// return the least SCEV value that is known never to be less than the
2604/// actual backedge taken count.
2605SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2606 return getBackedgeTakenInfo(L).Max;
2607}
2608
2609const ScalarEvolution::BackedgeTakenInfo &
2610ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002611 // Initially insert a CouldNotCompute for this loop. If the insertion
2612 // succeeds, procede to actually compute a backedge-taken count and
2613 // update the value. The temporary CouldNotCompute value tells SCEV
2614 // code elsewhere that it shouldn't attempt to request a new
2615 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002616 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002617 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2618 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002619 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman0c850912009-06-06 14:37:11 +00002620 if (ItCount.Exact != CouldNotCompute) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002621 assert(ItCount.Exact->isLoopInvariant(L) &&
2622 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002623 "Computed trip count isn't loop invariant for loop!");
2624 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002625
Dan Gohmana9dba962009-04-27 20:16:15 +00002626 // Update the value in the map.
2627 Pair.first->second = ItCount;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002628 } else if (isa<PHINode>(L->getHeader()->begin())) {
2629 // Only count loops that have phi nodes as not being computable.
2630 ++NumTripCountsNotComputed;
2631 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002632
2633 // Now that we know more about the trip count for this loop, forget any
2634 // existing SCEV values for PHI nodes in this loop since they are only
2635 // conservative estimates made without the benefit
2636 // of trip count information.
2637 if (ItCount.hasAnyInfo())
Dan Gohman94623022009-05-02 17:43:35 +00002638 forgetLoopPHIs(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002639 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002640 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002641}
2642
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002643/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002644/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002645/// ScalarEvolution's ability to compute a trip count, or if the loop
2646/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002647void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002648 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002649 forgetLoopPHIs(L);
2650}
2651
2652/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2653/// PHI nodes in the given loop. This is used when the trip count of
2654/// the loop may have changed.
2655void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002656 BasicBlock *Header = L->getHeader();
2657
Dan Gohman9fd4a002009-05-12 01:27:58 +00002658 // Push all Loop-header PHIs onto the Worklist stack, except those
2659 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2660 // a PHI either means that it has an unrecognized structure, or it's
2661 // a PHI that's in the progress of being computed by createNodeForPHI.
2662 // In the former case, additional loop trip count information isn't
2663 // going to change anything. In the later case, createNodeForPHI will
2664 // perform the necessary updates on its own when it gets to that point.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002665 SmallVector<Instruction *, 16> Worklist;
2666 for (BasicBlock::iterator I = Header->begin();
Dan Gohman9fd4a002009-05-12 01:27:58 +00002667 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2668 std::map<SCEVCallbackVH, SCEVHandle>::iterator It = Scalars.find((Value*)I);
2669 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2670 Worklist.push_back(PN);
2671 }
Dan Gohmanbff6b582009-05-04 22:30:44 +00002672
2673 while (!Worklist.empty()) {
2674 Instruction *I = Worklist.pop_back_val();
2675 if (Scalars.erase(I))
2676 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2677 UI != UE; ++UI)
2678 Worklist.push_back(cast<Instruction>(UI));
2679 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002680}
2681
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002682/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2683/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002684ScalarEvolution::BackedgeTakenInfo
2685ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002686 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel7388a9a2009-06-05 23:08:56 +00002687 BasicBlock *ExitBlock = L->getExitBlock();
2688 if (!ExitBlock)
Dan Gohman0c850912009-06-06 14:37:11 +00002689 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002690
2691 // Okay, there is one exit block. Try to find the condition that causes the
2692 // loop to be exited.
Devang Patel7388a9a2009-06-05 23:08:56 +00002693 BasicBlock *ExitingBlock = L->getExitingBlock();
2694 if (!ExitingBlock)
Dan Gohman0c850912009-06-06 14:37:11 +00002695 return CouldNotCompute; // More than one block exiting!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002696
2697 // Okay, we've computed the exiting block. See what condition causes us to
2698 // exit.
2699 //
2700 // FIXME: we should be able to handle switch instructions (with a single exit)
2701 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman0c850912009-06-06 14:37:11 +00002702 if (ExitBr == 0) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002703 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2704
2705 // At this point, we know we have a conditional branch that determines whether
2706 // the loop is exited. However, we don't know if the branch is executed each
2707 // time through the loop. If not, then the execution count of the branch will
2708 // not be equal to the trip count of the loop.
2709 //
2710 // Currently we check for this by checking to see if the Exit branch goes to
2711 // the loop header. If so, we know it will always execute the same number of
2712 // times as the loop. We also handle the case where the exit block *is* the
2713 // loop header. This is common for un-rotated loops. More extensive analysis
2714 // could be done to handle more cases here.
2715 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2716 ExitBr->getSuccessor(1) != L->getHeader() &&
2717 ExitBr->getParent() != L->getHeader())
Dan Gohman0c850912009-06-06 14:37:11 +00002718 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002719
2720 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2721
Eli Friedman459d7292009-05-09 12:32:42 +00002722 // If it's not an integer or pointer comparison then compute it the hard way.
2723 if (ExitCond == 0)
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002724 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002725 ExitBr->getSuccessor(0) == ExitBlock);
2726
2727 // If the condition was exit on true, convert the condition to exit on false
2728 ICmpInst::Predicate Cond;
2729 if (ExitBr->getSuccessor(1) == ExitBlock)
2730 Cond = ExitCond->getPredicate();
2731 else
2732 Cond = ExitCond->getInversePredicate();
2733
2734 // Handle common loops like: for (X = "string"; *X; ++X)
2735 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2736 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2737 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002738 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002739 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2740 }
2741
2742 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2743 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2744
2745 // Try to evaluate any dependencies out of the loop.
Dan Gohmanaff14d62009-05-24 23:25:42 +00002746 LHS = getSCEVAtScope(LHS, L);
2747 RHS = getSCEVAtScope(RHS, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002748
2749 // At this point, we would like to compute how many iterations of the
2750 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002751 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2752 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002753 std::swap(LHS, RHS);
2754 Cond = ICmpInst::getSwappedPredicate(Cond);
2755 }
2756
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002757 // If we have a comparison of a chrec against a constant, try to use value
2758 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002759 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2760 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002761 if (AddRec->getLoop() == L) {
Eli Friedman459d7292009-05-09 12:32:42 +00002762 // Form the constant range.
2763 ConstantRange CompRange(
2764 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002765
Eli Friedman459d7292009-05-09 12:32:42 +00002766 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
2767 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002768 }
2769
2770 switch (Cond) {
2771 case ICmpInst::ICMP_NE: { // while (X != Y)
2772 // Convert to: while (X-Y != 0)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002773 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002774 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2775 break;
2776 }
2777 case ICmpInst::ICMP_EQ: {
2778 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002779 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002780 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2781 break;
2782 }
2783 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002784 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2785 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002786 break;
2787 }
2788 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002789 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2790 getNotSCEV(RHS), L, true);
2791 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002792 break;
2793 }
2794 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002795 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2796 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002797 break;
2798 }
2799 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002800 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2801 getNotSCEV(RHS), L, false);
2802 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002803 break;
2804 }
2805 default:
2806#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002807 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002808 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002809 errs() << "[unsigned] ";
2810 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002811 << Instruction::getOpcodeName(Instruction::ICmp)
2812 << " " << *RHS << "\n";
2813#endif
2814 break;
2815 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002816 return
2817 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2818 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002819}
2820
2821static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002822EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2823 ScalarEvolution &SE) {
2824 SCEVHandle InVal = SE.getConstant(C);
2825 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002826 assert(isa<SCEVConstant>(Val) &&
2827 "Evaluation of SCEV at constant didn't fold correctly?");
2828 return cast<SCEVConstant>(Val)->getValue();
2829}
2830
2831/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2832/// and a GEP expression (missing the pointer index) indexing into it, return
2833/// the addressed element of the initializer or null if the index expression is
2834/// invalid.
2835static Constant *
2836GetAddressedElementFromGlobal(GlobalVariable *GV,
2837 const std::vector<ConstantInt*> &Indices) {
2838 Constant *Init = GV->getInitializer();
2839 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2840 uint64_t Idx = Indices[i]->getZExtValue();
2841 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2842 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2843 Init = cast<Constant>(CS->getOperand(Idx));
2844 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2845 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2846 Init = cast<Constant>(CA->getOperand(Idx));
2847 } else if (isa<ConstantAggregateZero>(Init)) {
2848 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2849 assert(Idx < STy->getNumElements() && "Bad struct index!");
2850 Init = Constant::getNullValue(STy->getElementType(Idx));
2851 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2852 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2853 Init = Constant::getNullValue(ATy->getElementType());
2854 } else {
2855 assert(0 && "Unknown constant aggregate type!");
2856 }
2857 return 0;
2858 } else {
2859 return 0; // Unknown initializer type
2860 }
2861 }
2862 return Init;
2863}
2864
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002865/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2866/// 'icmp op load X, cst', try to see if we can compute the backedge
2867/// execution count.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002868SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002869ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2870 const Loop *L,
2871 ICmpInst::Predicate predicate) {
Dan Gohman0c850912009-06-06 14:37:11 +00002872 if (LI->isVolatile()) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002873
2874 // Check to see if the loaded pointer is a getelementptr of a global.
2875 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman0c850912009-06-06 14:37:11 +00002876 if (!GEP) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002877
2878 // Make sure that it is really a constant global we are gepping, with an
2879 // initializer, and make sure the first IDX is really 0.
2880 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2881 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2882 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2883 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman0c850912009-06-06 14:37:11 +00002884 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002885
2886 // Okay, we allow one non-constant index into the GEP instruction.
2887 Value *VarIdx = 0;
2888 std::vector<ConstantInt*> Indexes;
2889 unsigned VarIdxNum = 0;
2890 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2891 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2892 Indexes.push_back(CI);
2893 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman0c850912009-06-06 14:37:11 +00002894 if (VarIdx) return CouldNotCompute; // Multiple non-constant idx's.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002895 VarIdx = GEP->getOperand(i);
2896 VarIdxNum = i-2;
2897 Indexes.push_back(0);
2898 }
2899
2900 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2901 // Check to see if X is a loop variant variable value now.
2902 SCEVHandle Idx = getSCEV(VarIdx);
Dan Gohmanaff14d62009-05-24 23:25:42 +00002903 Idx = getSCEVAtScope(Idx, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002904
2905 // We can only recognize very limited forms of loop index expressions, in
2906 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002907 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002908 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2909 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2910 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman0c850912009-06-06 14:37:11 +00002911 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002912
2913 unsigned MaxSteps = MaxBruteForceIterations;
2914 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2915 ConstantInt *ItCst =
Dan Gohman8fd520a2009-06-15 22:12:54 +00002916 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002917 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002918
2919 // Form the GEP offset.
2920 Indexes[VarIdxNum] = Val;
2921
2922 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2923 if (Result == 0) break; // Cannot compute!
2924
2925 // Evaluate the condition for this iteration.
2926 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2927 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2928 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2929#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002930 errs() << "\n***\n*** Computed loop count " << *ItCst
2931 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2932 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002933#endif
2934 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002935 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002936 }
2937 }
Dan Gohman0c850912009-06-06 14:37:11 +00002938 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002939}
2940
2941
2942/// CanConstantFold - Return true if we can constant fold an instruction of the
2943/// specified type, assuming that all operands were constants.
2944static bool CanConstantFold(const Instruction *I) {
2945 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2946 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2947 return true;
2948
2949 if (const CallInst *CI = dyn_cast<CallInst>(I))
2950 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002951 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002952 return false;
2953}
2954
2955/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2956/// in the loop that V is derived from. We allow arbitrary operations along the
2957/// way, but the operands of an operation must either be constants or a value
2958/// derived from a constant PHI. If this expression does not fit with these
2959/// constraints, return null.
2960static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2961 // If this is not an instruction, or if this is an instruction outside of the
2962 // loop, it can't be derived from a loop PHI.
2963 Instruction *I = dyn_cast<Instruction>(V);
2964 if (I == 0 || !L->contains(I->getParent())) return 0;
2965
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002966 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002967 if (L->getHeader() == I->getParent())
2968 return PN;
2969 else
2970 // We don't currently keep track of the control flow needed to evaluate
2971 // PHIs, so we cannot handle PHIs inside of loops.
2972 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002973 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002974
2975 // If we won't be able to constant fold this expression even if the operands
2976 // are constants, return early.
2977 if (!CanConstantFold(I)) return 0;
2978
2979 // Otherwise, we can evaluate this instruction if all of its operands are
2980 // constant or derived from a PHI node themselves.
2981 PHINode *PHI = 0;
2982 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2983 if (!(isa<Constant>(I->getOperand(Op)) ||
2984 isa<GlobalValue>(I->getOperand(Op)))) {
2985 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2986 if (P == 0) return 0; // Not evolving from PHI
2987 if (PHI == 0)
2988 PHI = P;
2989 else if (PHI != P)
2990 return 0; // Evolving from multiple different PHIs.
2991 }
2992
2993 // This is a expression evolving from a constant PHI!
2994 return PHI;
2995}
2996
2997/// EvaluateExpression - Given an expression that passes the
2998/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2999/// in the loop has the value PHIVal. If we can't fold this expression for some
3000/// reason, return null.
3001static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3002 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003003 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003004 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003005 Instruction *I = cast<Instruction>(V);
3006
3007 std::vector<Constant*> Operands;
3008 Operands.resize(I->getNumOperands());
3009
3010 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3011 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3012 if (Operands[i] == 0) return 0;
3013 }
3014
Chris Lattnerd6e56912007-12-10 22:53:04 +00003015 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3016 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3017 &Operands[0], Operands.size());
3018 else
3019 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3020 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003021}
3022
3023/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3024/// in the header of its containing loop, we know the loop executes a
3025/// constant number of times, and the PHI node is just a recurrence
3026/// involving constants, fold it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003027Constant *ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003028getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003029 std::map<PHINode*, Constant*>::iterator I =
3030 ConstantEvolutionLoopExitValue.find(PN);
3031 if (I != ConstantEvolutionLoopExitValue.end())
3032 return I->second;
3033
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003034 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003035 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3036
3037 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3038
3039 // Since the loop is canonicalized, the PHI node must have two entries. One
3040 // entry must be a constant (coming in from outside of the loop), and the
3041 // second must be derived from the same PHI.
3042 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3043 Constant *StartCST =
3044 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3045 if (StartCST == 0)
3046 return RetVal = 0; // Must be a constant.
3047
3048 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3049 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3050 if (PN2 != PN)
3051 return RetVal = 0; // Not derived from same PHI.
3052
3053 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003054 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003055 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3056
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003057 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003058 unsigned IterationNum = 0;
3059 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3060 if (IterationNum == NumIterations)
3061 return RetVal = PHIVal; // Got exit value!
3062
3063 // Compute the value of the PHI node for the next iteration.
3064 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3065 if (NextPHI == PHIVal)
3066 return RetVal = NextPHI; // Stopped evolving!
3067 if (NextPHI == 0)
3068 return 0; // Couldn't evaluate!
3069 PHIVal = NextPHI;
3070 }
3071}
3072
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003073/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003074/// constant number of times (the condition evolves only from constants),
3075/// try to evaluate a few iterations of the loop until we get the exit
3076/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman0c850912009-06-06 14:37:11 +00003077/// evaluate the trip count of the loop, return CouldNotCompute.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003078SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003079ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003080 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman0c850912009-06-06 14:37:11 +00003081 if (PN == 0) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003082
3083 // Since the loop is canonicalized, the PHI node must have two entries. One
3084 // entry must be a constant (coming in from outside of the loop), and the
3085 // second must be derived from the same PHI.
3086 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3087 Constant *StartCST =
3088 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman0c850912009-06-06 14:37:11 +00003089 if (StartCST == 0) return CouldNotCompute; // Must be a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003090
3091 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3092 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman0c850912009-06-06 14:37:11 +00003093 if (PN2 != PN) return CouldNotCompute; // Not derived from same PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003094
3095 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3096 // the loop symbolically to determine when the condition gets a value of
3097 // "ExitWhen".
3098 unsigned IterationNum = 0;
3099 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3100 for (Constant *PHIVal = StartCST;
3101 IterationNum != MaxIterations; ++IterationNum) {
3102 ConstantInt *CondVal =
3103 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3104
3105 // Couldn't symbolically evaluate.
Dan Gohman0c850912009-06-06 14:37:11 +00003106 if (!CondVal) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003107
3108 if (CondVal->getValue() == uint64_t(ExitWhen)) {
3109 ConstantEvolutionLoopExitValue[PN] = PHIVal;
3110 ++NumBruteForceTripCountsComputed;
Dan Gohman8fd520a2009-06-15 22:12:54 +00003111 return getConstant(Type::Int32Ty, IterationNum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003112 }
3113
3114 // Compute the value of the PHI node for the next iteration.
3115 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3116 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman0c850912009-06-06 14:37:11 +00003117 return CouldNotCompute; // Couldn't evaluate or not making progress...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003118 PHIVal = NextPHI;
3119 }
3120
3121 // Too many iterations were needed to evaluate.
Dan Gohman0c850912009-06-06 14:37:11 +00003122 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003123}
3124
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003125/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3126/// at the specified scope in the program. The L value specifies a loop
3127/// nest to evaluate the expression at, where null is the top-level or a
3128/// specified loop is immediately inside of the loop.
3129///
3130/// This method can be used to compute the exit value for a variable defined
3131/// in a loop by querying what the value will hold in the parent loop.
3132///
Dan Gohmanaff14d62009-05-24 23:25:42 +00003133/// In the case that a relevant loop exit value cannot be computed, the
3134/// original value V is returned.
Dan Gohmanbff6b582009-05-04 22:30:44 +00003135SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003136 // FIXME: this should be turned into a virtual method on SCEV!
3137
3138 if (isa<SCEVConstant>(V)) return V;
3139
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003140 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003141 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003142 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003143 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003144 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003145 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3146 if (PHINode *PN = dyn_cast<PHINode>(I))
3147 if (PN->getParent() == LI->getHeader()) {
3148 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003149 // to see if the loop that contains it has a known backedge-taken
3150 // count. If so, we may be able to force computation of the exit
3151 // value.
3152 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003153 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003154 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003155 // Okay, we know how many times the containing loop executes. If
3156 // this is a constant evolving PHI node, get the final value at
3157 // the specified iteration number.
3158 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003159 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003160 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003161 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003162 }
3163 }
3164
3165 // Okay, this is an expression that we cannot symbolically evaluate
3166 // into a SCEV. Check to see if it's possible to symbolically evaluate
3167 // the arguments into constants, and if so, try to constant propagate the
3168 // result. This is particularly useful for computing loop exit values.
3169 if (CanConstantFold(I)) {
Dan Gohmanda0071e2009-05-08 20:47:27 +00003170 // Check to see if we've folded this instruction at this loop before.
3171 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3172 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3173 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3174 if (!Pair.second)
3175 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
3176
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003177 std::vector<Constant*> Operands;
3178 Operands.reserve(I->getNumOperands());
3179 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3180 Value *Op = I->getOperand(i);
3181 if (Constant *C = dyn_cast<Constant>(Op)) {
3182 Operands.push_back(C);
3183 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00003184 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00003185 // non-integer and non-pointer, don't even try to analyze them
3186 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00003187 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00003188 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003189
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003190 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003191 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003192 Constant *C = SC->getValue();
3193 if (C->getType() != Op->getType())
3194 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3195 Op->getType(),
3196 false),
3197 C, Op->getType());
3198 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003199 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003200 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3201 if (C->getType() != Op->getType())
3202 C =
3203 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3204 Op->getType(),
3205 false),
3206 C, Op->getType());
3207 Operands.push_back(C);
3208 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003209 return V;
3210 } else {
3211 return V;
3212 }
3213 }
3214 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00003215
3216 Constant *C;
3217 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3218 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3219 &Operands[0], Operands.size());
3220 else
3221 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3222 &Operands[0], Operands.size());
Dan Gohmanda0071e2009-05-08 20:47:27 +00003223 Pair.first->second = C;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003224 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003225 }
3226 }
3227
3228 // This is some other type of SCEVUnknown, just return it.
3229 return V;
3230 }
3231
Dan Gohmanc76b5452009-05-04 22:02:23 +00003232 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003233 // Avoid performing the look-up in the common case where the specified
3234 // expression has no loop-variant portions.
3235 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
3236 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3237 if (OpAtScope != Comm->getOperand(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003238 // Okay, at least one of these operands is loop variant but might be
3239 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman02ff9392009-06-14 22:47:23 +00003240 SmallVector<SCEVHandle, 8> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003241 NewOps.push_back(OpAtScope);
3242
3243 for (++i; i != e; ++i) {
3244 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003245 NewOps.push_back(OpAtScope);
3246 }
3247 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003248 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003249 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003250 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003251 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003252 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003253 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003254 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003255 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003256 }
3257 }
3258 // If we got here, all operands are loop invariant.
3259 return Comm;
3260 }
3261
Dan Gohmanc76b5452009-05-04 22:02:23 +00003262 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003263 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003264 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003265 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3266 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003267 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003268 }
3269
3270 // If this is a loop recurrence for a loop that does not contain L, then we
3271 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003272 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003273 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3274 // To evaluate this recurrence, we need to know how many times the AddRec
3275 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003276 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman0c850912009-06-06 14:37:11 +00003277 if (BackedgeTakenCount == CouldNotCompute) return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003278
Eli Friedman7489ec92008-08-04 23:49:06 +00003279 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003280 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003281 }
Dan Gohmanaff14d62009-05-24 23:25:42 +00003282 return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003283 }
3284
Dan Gohmanc76b5452009-05-04 22:02:23 +00003285 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003286 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003287 if (Op == Cast->getOperand())
3288 return Cast; // must be loop invariant
3289 return getZeroExtendExpr(Op, Cast->getType());
3290 }
3291
Dan Gohmanc76b5452009-05-04 22:02:23 +00003292 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003293 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003294 if (Op == Cast->getOperand())
3295 return Cast; // must be loop invariant
3296 return getSignExtendExpr(Op, Cast->getType());
3297 }
3298
Dan Gohmanc76b5452009-05-04 22:02:23 +00003299 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003300 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003301 if (Op == Cast->getOperand())
3302 return Cast; // must be loop invariant
3303 return getTruncateExpr(Op, Cast->getType());
3304 }
3305
3306 assert(0 && "Unknown SCEV type!");
Daniel Dunbara95d96c2009-05-18 16:43:04 +00003307 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003308}
3309
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003310/// getSCEVAtScope - This is a convenience function which does
3311/// getSCEVAtScope(getSCEV(V), L).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003312SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
3313 return getSCEVAtScope(getSCEV(V), L);
3314}
3315
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003316/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3317/// following equation:
3318///
3319/// A * X = B (mod N)
3320///
3321/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3322/// A and B isn't important.
3323///
3324/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
3325static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
3326 ScalarEvolution &SE) {
3327 uint32_t BW = A.getBitWidth();
3328 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3329 assert(A != 0 && "A must be non-zero.");
3330
3331 // 1. D = gcd(A, N)
3332 //
3333 // The gcd of A and N may have only one prime factor: 2. The number of
3334 // trailing zeros in A is its multiplicity
3335 uint32_t Mult2 = A.countTrailingZeros();
3336 // D = 2^Mult2
3337
3338 // 2. Check if B is divisible by D.
3339 //
3340 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3341 // is not less than multiplicity of this prime factor for D.
3342 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00003343 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003344
3345 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3346 // modulo (N / D).
3347 //
3348 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3349 // bit width during computations.
3350 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3351 APInt Mod(BW + 1, 0);
3352 Mod.set(BW - Mult2); // Mod = N / D
3353 APInt I = AD.multiplicativeInverse(Mod);
3354
3355 // 4. Compute the minimum unsigned root of the equation:
3356 // I * (B / D) mod (N / D)
3357 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3358
3359 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3360 // bits.
3361 return SE.getConstant(Result.trunc(BW));
3362}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003363
3364/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3365/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3366/// might be the same) or two SCEVCouldNotCompute objects.
3367///
3368static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00003369SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003370 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00003371 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3372 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3373 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003374
3375 // We currently can only solve this if the coefficients are constants.
3376 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003377 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003378 return std::make_pair(CNC, CNC);
3379 }
3380
3381 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3382 const APInt &L = LC->getValue()->getValue();
3383 const APInt &M = MC->getValue()->getValue();
3384 const APInt &N = NC->getValue()->getValue();
3385 APInt Two(BitWidth, 2);
3386 APInt Four(BitWidth, 4);
3387
3388 {
3389 using namespace APIntOps;
3390 const APInt& C = L;
3391 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3392 // The B coefficient is M-N/2
3393 APInt B(M);
3394 B -= sdiv(N,Two);
3395
3396 // The A coefficient is N/2
3397 APInt A(N.sdiv(Two));
3398
3399 // Compute the B^2-4ac term.
3400 APInt SqrtTerm(B);
3401 SqrtTerm *= B;
3402 SqrtTerm -= Four * (A * C);
3403
3404 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3405 // integer value or else APInt::sqrt() will assert.
3406 APInt SqrtVal(SqrtTerm.sqrt());
3407
3408 // Compute the two solutions for the quadratic formula.
3409 // The divisions must be performed as signed divisions.
3410 APInt NegB(-B);
3411 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00003412 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003413 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00003414 return std::make_pair(CNC, CNC);
3415 }
3416
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003417 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3418 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
3419
Dan Gohman89f85052007-10-22 18:31:58 +00003420 return std::make_pair(SE.getConstant(Solution1),
3421 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003422 } // end APIntOps namespace
3423}
3424
3425/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman0c850912009-06-06 14:37:11 +00003426/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohmanbff6b582009-05-04 22:30:44 +00003427SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003428 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00003429 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003430 // If the value is already zero, the branch will execute zero times.
3431 if (C->getValue()->isZero()) return C;
Dan Gohman0c850912009-06-06 14:37:11 +00003432 return CouldNotCompute; // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003433 }
3434
Dan Gohmanbff6b582009-05-04 22:30:44 +00003435 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003436 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman0c850912009-06-06 14:37:11 +00003437 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003438
3439 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003440 // If this is an affine expression, the execution count of this branch is
3441 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003442 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003443 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003444 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003445 // equivalent to:
3446 //
3447 // Step*N = -Start (mod 2^BW)
3448 //
3449 // where BW is the common bit width of Start and Step.
3450
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003451 // Get the initial value for the loop.
3452 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003453 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003454
Dan Gohmanc76b5452009-05-04 22:02:23 +00003455 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003456 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003457
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003458 // First, handle unitary steps.
3459 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003460 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003461 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3462 return Start; // N = Start (as unsigned)
3463
3464 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003465 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003466 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003467 -StartC->getValue()->getValue(),
3468 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003469 }
3470 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3471 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3472 // the quadratic equation to solve it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003473 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
3474 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003475 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3476 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003477 if (R1) {
3478#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003479 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3480 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003481#endif
3482 // Pick the smallest positive root value.
3483 if (ConstantInt *CB =
3484 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3485 R1->getValue(), R2->getValue()))) {
3486 if (CB->getZExtValue() == false)
3487 std::swap(R1, R2); // R1 is the minimum root now.
3488
3489 // We can only use this value if the chrec ends up with an exact zero
3490 // value at this index. When solving for "X*X != 5", for example, we
3491 // should not accept a root of 2.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003492 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00003493 if (Val->isZero())
3494 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003495 }
3496 }
3497 }
3498
Dan Gohman0c850912009-06-06 14:37:11 +00003499 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003500}
3501
3502/// HowFarToNonZero - Return the number of times a backedge checking the
3503/// specified value for nonzero will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00003504/// CouldNotCompute
Dan Gohmanbff6b582009-05-04 22:30:44 +00003505SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003506 // Loops that look like: while (X == 0) are very strange indeed. We don't
3507 // handle them yet except for the trivial case. This could be expanded in the
3508 // future as needed.
3509
3510 // If the value is a constant, check to see if it is known to be non-zero
3511 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003512 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00003513 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003514 return getIntegerSCEV(0, C->getType());
Dan Gohman0c850912009-06-06 14:37:11 +00003515 return CouldNotCompute; // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003516 }
3517
3518 // We could implement others, but I really doubt anyone writes loops like
3519 // this, and if they did, they would already be constant folded.
Dan Gohman0c850912009-06-06 14:37:11 +00003520 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003521}
3522
Dan Gohmanab157b22009-05-18 15:36:09 +00003523/// getLoopPredecessor - If the given loop's header has exactly one unique
3524/// predecessor outside the loop, return it. Otherwise return null.
3525///
3526BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3527 BasicBlock *Header = L->getHeader();
3528 BasicBlock *Pred = 0;
3529 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3530 PI != E; ++PI)
3531 if (!L->contains(*PI)) {
3532 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3533 Pred = *PI;
3534 }
3535 return Pred;
3536}
3537
Dan Gohman1cddf972008-09-15 22:18:04 +00003538/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3539/// (which may not be an immediate predecessor) which has exactly one
3540/// successor from which BB is reachable, or null if no such block is
3541/// found.
3542///
3543BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003544ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00003545 // If the block has a unique predecessor, then there is no path from the
3546 // predecessor to the block that does not go through the direct edge
3547 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00003548 if (BasicBlock *Pred = BB->getSinglePredecessor())
3549 return Pred;
3550
3551 // A loop's header is defined to be a block that dominates the loop.
Dan Gohmanab157b22009-05-18 15:36:09 +00003552 // If the header has a unique predecessor outside the loop, it must be
3553 // a block that has exactly one successor that can reach the loop.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003554 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanab157b22009-05-18 15:36:09 +00003555 return getLoopPredecessor(L);
Dan Gohman1cddf972008-09-15 22:18:04 +00003556
3557 return 0;
3558}
3559
Dan Gohmancacd2012009-02-12 22:19:27 +00003560/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman1116ea72009-04-30 20:48:53 +00003561/// a conditional between LHS and RHS. This is used to help avoid max
3562/// expressions in loop trip counts.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003563bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman1116ea72009-04-30 20:48:53 +00003564 ICmpInst::Predicate Pred,
Dan Gohmanbff6b582009-05-04 22:30:44 +00003565 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8b938182009-05-18 16:03:58 +00003566 // Interpret a null as meaning no loop, where there is obviously no guard
3567 // (interprocedural conditions notwithstanding).
3568 if (!L) return false;
3569
Dan Gohmanab157b22009-05-18 15:36:09 +00003570 BasicBlock *Predecessor = getLoopPredecessor(L);
3571 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003572
Dan Gohmanab157b22009-05-18 15:36:09 +00003573 // Starting at the loop predecessor, climb up the predecessor chain, as long
3574 // as there are predecessors that can be found that have unique successors
Dan Gohman1cddf972008-09-15 22:18:04 +00003575 // leading to the original header.
Dan Gohmanab157b22009-05-18 15:36:09 +00003576 for (; Predecessor;
3577 PredecessorDest = Predecessor,
3578 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00003579
3580 BranchInst *LoopEntryPredicate =
Dan Gohmanab157b22009-05-18 15:36:09 +00003581 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00003582 if (!LoopEntryPredicate ||
3583 LoopEntryPredicate->isUnconditional())
3584 continue;
3585
3586 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3587 if (!ICI) continue;
3588
3589 // Now that we found a conditional branch that dominates the loop, check to
3590 // see if it is the comparison we are looking for.
3591 Value *PreCondLHS = ICI->getOperand(0);
3592 Value *PreCondRHS = ICI->getOperand(1);
3593 ICmpInst::Predicate Cond;
Dan Gohmanab157b22009-05-18 15:36:09 +00003594 if (LoopEntryPredicate->getSuccessor(0) == PredecessorDest)
Dan Gohmanab678fb2008-08-12 20:17:31 +00003595 Cond = ICI->getPredicate();
3596 else
3597 Cond = ICI->getInversePredicate();
3598
Dan Gohmancacd2012009-02-12 22:19:27 +00003599 if (Cond == Pred)
3600 ; // An exact match.
3601 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3602 ; // The actual condition is beyond sufficient.
3603 else
3604 // Check a few special cases.
3605 switch (Cond) {
3606 case ICmpInst::ICMP_UGT:
3607 if (Pred == ICmpInst::ICMP_ULT) {
3608 std::swap(PreCondLHS, PreCondRHS);
3609 Cond = ICmpInst::ICMP_ULT;
3610 break;
3611 }
3612 continue;
3613 case ICmpInst::ICMP_SGT:
3614 if (Pred == ICmpInst::ICMP_SLT) {
3615 std::swap(PreCondLHS, PreCondRHS);
3616 Cond = ICmpInst::ICMP_SLT;
3617 break;
3618 }
3619 continue;
3620 case ICmpInst::ICMP_NE:
3621 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3622 // so check for this case by checking if the NE is comparing against
3623 // a minimum or maximum constant.
3624 if (!ICmpInst::isTrueWhenEqual(Pred))
3625 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3626 const APInt &A = CI->getValue();
3627 switch (Pred) {
3628 case ICmpInst::ICMP_SLT:
3629 if (A.isMaxSignedValue()) break;
3630 continue;
3631 case ICmpInst::ICMP_SGT:
3632 if (A.isMinSignedValue()) break;
3633 continue;
3634 case ICmpInst::ICMP_ULT:
3635 if (A.isMaxValue()) break;
3636 continue;
3637 case ICmpInst::ICMP_UGT:
3638 if (A.isMinValue()) break;
3639 continue;
3640 default:
3641 continue;
3642 }
3643 Cond = ICmpInst::ICMP_NE;
3644 // NE is symmetric but the original comparison may not be. Swap
3645 // the operands if necessary so that they match below.
3646 if (isa<SCEVConstant>(LHS))
3647 std::swap(PreCondLHS, PreCondRHS);
3648 break;
3649 }
3650 continue;
3651 default:
3652 // We weren't able to reconcile the condition.
3653 continue;
3654 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003655
3656 if (!PreCondLHS->getType()->isInteger()) continue;
3657
3658 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3659 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3660 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003661 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3662 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohmanab678fb2008-08-12 20:17:31 +00003663 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003664 }
3665
Dan Gohmanab678fb2008-08-12 20:17:31 +00003666 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003667}
3668
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003669/// HowManyLessThans - Return the number of times a backedge containing the
3670/// specified less-than comparison will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00003671/// CouldNotCompute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003672ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Dan Gohmanbff6b582009-05-04 22:30:44 +00003673HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3674 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003675 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman0c850912009-06-06 14:37:11 +00003676 if (!RHS->isLoopInvariant(L)) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003677
Dan Gohmanbff6b582009-05-04 22:30:44 +00003678 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003679 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman0c850912009-06-06 14:37:11 +00003680 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003681
3682 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003683 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003684 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3685 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3686 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3687
3688 // TODO: handle non-constant strides.
3689 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3690 if (!CStep || CStep->isZero())
Dan Gohman0c850912009-06-06 14:37:11 +00003691 return CouldNotCompute;
Dan Gohmanf8bc8e82009-05-18 15:22:39 +00003692 if (CStep->isOne()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003693 // With unit stride, the iteration never steps past the limit value.
3694 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3695 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3696 // Test whether a positive iteration iteration can step past the limit
3697 // value and past the maximum value for its type in a single step.
3698 if (isSigned) {
3699 APInt Max = APInt::getSignedMaxValue(BitWidth);
3700 if ((Max - CStep->getValue()->getValue())
3701 .slt(CLimit->getValue()->getValue()))
Dan Gohman0c850912009-06-06 14:37:11 +00003702 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003703 } else {
3704 APInt Max = APInt::getMaxValue(BitWidth);
3705 if ((Max - CStep->getValue()->getValue())
3706 .ult(CLimit->getValue()->getValue()))
Dan Gohman0c850912009-06-06 14:37:11 +00003707 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003708 }
3709 } else
3710 // TODO: handle non-constant limit values below.
Dan Gohman0c850912009-06-06 14:37:11 +00003711 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003712 } else
3713 // TODO: handle negative strides below.
Dan Gohman0c850912009-06-06 14:37:11 +00003714 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003715
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003716 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3717 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3718 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00003719 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003720
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003721 // First, we get the value of the LHS in the first iteration: n
3722 SCEVHandle Start = AddRec->getOperand(0);
3723
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003724 // Determine the minimum constant start value.
3725 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3726 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3727 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003728
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003729 // If we know that the condition is true in order to enter the loop,
3730 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohmanc8a29272009-05-24 23:45:28 +00003731 // only know that it will execute (max(m,n)-n)/s times. In both cases,
3732 // the division must round up.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003733 SCEVHandle End = RHS;
3734 if (!isLoopGuardedByCond(L,
3735 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3736 getMinusSCEV(Start, Step), RHS))
3737 End = isSigned ? getSMaxExpr(RHS, Start)
3738 : getUMaxExpr(RHS, Start);
3739
3740 // Determine the maximum constant end value.
3741 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3742 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3743 APInt::getMaxValue(BitWidth));
3744
3745 // Finally, we subtract these two values and divide, rounding up, to get
3746 // the number of times the backedge is executed.
3747 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3748 getAddExpr(Step, NegOne)),
3749 Step);
3750
3751 // The maximum backedge count is similar, except using the minimum start
3752 // value and the maximum end value.
3753 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3754 MinStart),
3755 getAddExpr(Step, NegOne)),
3756 Step);
3757
3758 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003759 }
3760
Dan Gohman0c850912009-06-06 14:37:11 +00003761 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003762}
3763
3764/// getNumIterationsInRange - Return the number of iterations of this loop that
3765/// produce values in the specified constant range. Another way of looking at
3766/// this is that it returns the first iteration number where the value is not in
3767/// the condition, thus computing the exit count. If the iteration count can't
3768/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00003769SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3770 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003771 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003772 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003773
3774 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003775 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003776 if (!SC->getValue()->isZero()) {
Dan Gohman02ff9392009-06-14 22:47:23 +00003777 SmallVector<SCEVHandle, 4> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003778 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3779 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00003780 if (const SCEVAddRecExpr *ShiftedAddRec =
3781 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003782 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003783 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003784 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003785 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003786 }
3787
3788 // The only time we can solve this is when we have all constant indices.
3789 // Otherwise, we cannot determine the overflow conditions.
3790 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3791 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003792 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003793
3794
3795 // Okay at this point we know that all elements of the chrec are constants and
3796 // that the start element is zero.
3797
3798 // First check to see if the range contains zero. If not, the first
3799 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003800 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003801 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman8fd520a2009-06-15 22:12:54 +00003802 return SE.getIntegerSCEV(0, getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003803
3804 if (isAffine()) {
3805 // If this is an affine expression then we have this situation:
3806 // Solve {0,+,A} in Range === Ax in Range
3807
3808 // We know that zero is in the range. If A is positive then we know that
3809 // the upper value of the range must be the first possible exit value.
3810 // If A is negative then the lower of the range is the last possible loop
3811 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003812 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003813 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3814 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3815
3816 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003817 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003818 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3819
3820 // Evaluate at the exit value. If we really did fall out of the valid
3821 // range, then we computed our trip count, otherwise wrap around or other
3822 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003823 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003824 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003825 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003826
3827 // Ensure that the previous value is in the range. This is a sanity check.
3828 assert(Range.contains(
3829 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003830 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003831 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003832 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003833 } else if (isQuadratic()) {
3834 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3835 // quadratic equation to solve it. To do this, we must frame our problem in
3836 // terms of figuring out when zero is crossed, instead of when
3837 // Range.getUpper() is crossed.
Dan Gohman02ff9392009-06-14 22:47:23 +00003838 SmallVector<SCEVHandle, 4> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003839 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3840 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003841
3842 // Next, solve the constructed addrec
3843 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003844 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003845 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3846 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003847 if (R1) {
3848 // Pick the smallest positive root value.
3849 if (ConstantInt *CB =
3850 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3851 R1->getValue(), R2->getValue()))) {
3852 if (CB->getZExtValue() == false)
3853 std::swap(R1, R2); // R1 is the minimum root now.
3854
3855 // Make sure the root is not off by one. The returned iteration should
3856 // not be in the range, but the previous one should be. When solving
3857 // for "X*X < 5", for example, we should not return a root of 2.
3858 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003859 R1->getValue(),
3860 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003861 if (Range.contains(R1Val->getValue())) {
3862 // The next iteration must be out of the range...
3863 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3864
Dan Gohman89f85052007-10-22 18:31:58 +00003865 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003866 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003867 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003868 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003869 }
3870
3871 // If R1 was not in the range, then it is a good return value. Make
3872 // sure that R1-1 WAS in the range though, just in case.
3873 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003874 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003875 if (Range.contains(R1Val->getValue()))
3876 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003877 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003878 }
3879 }
3880 }
3881
Dan Gohman0ad08b02009-04-18 17:58:19 +00003882 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003883}
3884
3885
3886
3887//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00003888// SCEVCallbackVH Class Implementation
3889//===----------------------------------------------------------------------===//
3890
Dan Gohman999d14e2009-05-19 19:22:47 +00003891void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003892 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3893 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3894 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003895 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
3896 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003897 SE->Scalars.erase(getValPtr());
3898 // this now dangles!
3899}
3900
Dan Gohman999d14e2009-05-19 19:22:47 +00003901void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003902 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3903
3904 // Forget all the expressions associated with users of the old value,
3905 // so that future queries will recompute the expressions using the new
3906 // value.
3907 SmallVector<User *, 16> Worklist;
3908 Value *Old = getValPtr();
3909 bool DeleteOld = false;
3910 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3911 UI != UE; ++UI)
3912 Worklist.push_back(*UI);
3913 while (!Worklist.empty()) {
3914 User *U = Worklist.pop_back_val();
3915 // Deleting the Old value will cause this to dangle. Postpone
3916 // that until everything else is done.
3917 if (U == Old) {
3918 DeleteOld = true;
3919 continue;
3920 }
3921 if (PHINode *PN = dyn_cast<PHINode>(U))
3922 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003923 if (Instruction *I = dyn_cast<Instruction>(U))
3924 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003925 if (SE->Scalars.erase(U))
3926 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3927 UI != UE; ++UI)
3928 Worklist.push_back(*UI);
3929 }
3930 if (DeleteOld) {
3931 if (PHINode *PN = dyn_cast<PHINode>(Old))
3932 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003933 if (Instruction *I = dyn_cast<Instruction>(Old))
3934 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003935 SE->Scalars.erase(Old);
3936 // this now dangles!
3937 }
3938 // this may dangle!
3939}
3940
Dan Gohman999d14e2009-05-19 19:22:47 +00003941ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohmanbff6b582009-05-04 22:30:44 +00003942 : CallbackVH(V), SE(se) {}
3943
3944//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003945// ScalarEvolution Class Implementation
3946//===----------------------------------------------------------------------===//
3947
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003948ScalarEvolution::ScalarEvolution()
Dan Gohman0c850912009-06-06 14:37:11 +00003949 : FunctionPass(&ID), CouldNotCompute(new SCEVCouldNotCompute()) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003950}
3951
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003952bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003953 this->F = &F;
3954 LI = &getAnalysis<LoopInfo>();
3955 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003956 return false;
3957}
3958
3959void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003960 Scalars.clear();
3961 BackedgeTakenCounts.clear();
3962 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanda0071e2009-05-08 20:47:27 +00003963 ValuesAtScopes.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003964}
3965
3966void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3967 AU.setPreservesAll();
3968 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003969}
3970
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003971bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003972 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003973}
3974
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003975static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003976 const Loop *L) {
3977 // Print all inner loops first
3978 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3979 PrintLoopInfo(OS, SE, *I);
3980
Nick Lewyckye5da1912008-01-02 02:49:20 +00003981 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003982
Devang Patel02451fa2007-08-21 00:31:24 +00003983 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003984 L->getExitBlocks(ExitBlocks);
3985 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003986 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003987
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003988 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3989 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003990 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003991 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003992 }
3993
Nick Lewyckye5da1912008-01-02 02:49:20 +00003994 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003995}
3996
Dan Gohman13058cc2009-04-21 00:47:46 +00003997void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003998 // ScalarEvolution's implementaiton of the print method is to print
3999 // out SCEV values of all instructions that are interesting. Doing
4000 // this potentially causes it to create new SCEV objects though,
4001 // which technically conflicts with the const qualifier. This isn't
4002 // observable from outside the class though (the hasSCEV function
4003 // notwithstanding), so casting away the const isn't dangerous.
4004 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004005
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004006 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004007 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00004008 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004009 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00004010 OS << " --> ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004011 SCEVHandle SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004012 SV->print(OS);
4013 OS << "\t\t";
4014
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004015 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004016 OS << "Exits: ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004017 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmanaff14d62009-05-24 23:25:42 +00004018 if (!ExitValue->isLoopInvariant(L)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004019 OS << "<<Unknown>>";
4020 } else {
4021 OS << *ExitValue;
4022 }
4023 }
4024
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004025 OS << "\n";
4026 }
4027
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004028 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4029 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4030 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004031}
Dan Gohman13058cc2009-04-21 00:47:46 +00004032
4033void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4034 raw_os_ostream OS(o);
4035 print(OS, M);
4036}