blob: eaa847aa10da59435515dd0311c5952cee7fe820 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
17// can handle. These classes are reference counted, managed by the SCEVHandle
18// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
31//
32// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
36// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
62#define DEBUG_TYPE "scalar-evolution"
63#include "llvm/Analysis/ScalarEvolutionExpressions.h"
64#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
66#include "llvm/GlobalVariable.h"
67#include "llvm/Instructions.h"
68#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng98c073b2009-02-17 00:13:06 +000069#include "llvm/Analysis/Dominators.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070#include "llvm/Analysis/LoopInfo.h"
71#include "llvm/Assembly/Writer.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000072#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000073#include "llvm/Support/CommandLine.h"
74#include "llvm/Support/Compiler.h"
75#include "llvm/Support/ConstantRange.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000076#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000077#include "llvm/Support/InstIterator.h"
78#include "llvm/Support/ManagedStatic.h"
79#include "llvm/Support/MathExtras.h"
Dan Gohman13058cc2009-04-21 00:47:46 +000080#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081#include "llvm/ADT/Statistic.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000082#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083#include <ostream>
84#include <algorithm>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085using namespace llvm;
86
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087STATISTIC(NumArrayLenItCounts,
88 "Number of trip counts computed with array length");
89STATISTIC(NumTripCountsComputed,
90 "Number of loops with predictable loop counts");
91STATISTIC(NumTripCountsNotComputed,
92 "Number of loops without predictable loop counts");
93STATISTIC(NumBruteForceTripCountsComputed,
94 "Number of loops with trip counts computed by force");
95
Dan Gohman089efff2008-05-13 00:00:25 +000096static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000097MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
98 cl::desc("Maximum number of iterations SCEV will "
99 "symbolically execute a constant derived loop"),
100 cl::init(100));
101
Dan Gohman089efff2008-05-13 00:00:25 +0000102static RegisterPass<ScalarEvolution>
103R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000104char ScalarEvolution::ID = 0;
105
106//===----------------------------------------------------------------------===//
107// SCEV class definitions
108//===----------------------------------------------------------------------===//
109
110//===----------------------------------------------------------------------===//
111// Implementation of the SCEV class.
112//
113SCEV::~SCEV() {}
114void SCEV::dump() const {
Dan Gohman13058cc2009-04-21 00:47:46 +0000115 print(errs());
116 errs() << '\n';
117}
118
119void SCEV::print(std::ostream &o) const {
120 raw_os_ostream OS(o);
121 print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122}
123
Dan Gohman7b560c42008-06-18 16:23:07 +0000124bool SCEV::isZero() const {
125 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
126 return SC->getValue()->isZero();
127 return false;
128}
129
Dan 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 Gohmanf17a25c2007-07-18 16:29:46 +0000190const Type *SCEVConstant::getType() const { return V->getType(); }
191
Dan Gohman13058cc2009-04-21 00:47:46 +0000192void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193 WriteAsOperand(OS, V, false);
194}
195
Dan Gohman2a381532009-04-21 01:25:57 +0000196SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
197 const SCEVHandle &op, const Type *ty)
198 : SCEV(SCEVTy), Op(op), Ty(ty) {}
199
200SCEVCastExpr::~SCEVCastExpr() {}
201
202bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
203 return Op->dominates(BB, DT);
204}
205
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000206// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
207// particular input. Don't use a SCEVHandle here, or else the object will
208// never be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000209static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 SCEVTruncateExpr*> > SCEVTruncates;
211
212SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000213 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000214 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
215 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000216 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217}
218
219SCEVTruncateExpr::~SCEVTruncateExpr() {
220 SCEVTruncates->erase(std::make_pair(Op, Ty));
221}
222
Dan Gohman13058cc2009-04-21 00:47:46 +0000223void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000224 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225}
226
227// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
228// particular input. Don't use a SCEVHandle here, or else the object will never
229// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000230static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231 SCEVZeroExtendExpr*> > SCEVZeroExtends;
232
233SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000234 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000235 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
236 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238}
239
240SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
241 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
242}
243
Dan Gohman13058cc2009-04-21 00:47:46 +0000244void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000245 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246}
247
248// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
249// particular input. Don't use a SCEVHandle here, or else the object will never
250// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000251static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252 SCEVSignExtendExpr*> > SCEVSignExtends;
253
254SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000255 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000256 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
257 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000258 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000259}
260
261SCEVSignExtendExpr::~SCEVSignExtendExpr() {
262 SCEVSignExtends->erase(std::make_pair(Op, Ty));
263}
264
Dan Gohman13058cc2009-04-21 00:47:46 +0000265void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000266 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000267}
268
269// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
270// particular input. Don't use a SCEVHandle here, or else the object will never
271// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000272static ManagedStatic<std::map<std::pair<unsigned, std::vector<const SCEV*> >,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 SCEVCommutativeExpr*> > SCEVCommExprs;
274
275SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000276 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
277 SCEVCommExprs->erase(std::make_pair(getSCEVType(), SCEVOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000278}
279
Dan Gohman13058cc2009-04-21 00:47:46 +0000280void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000281 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
282 const char *OpStr = getOperationStr();
283 OS << "(" << *Operands[0];
284 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
285 OS << OpStr << *Operands[i];
286 OS << ")";
287}
288
289SCEVHandle SCEVCommutativeExpr::
290replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000291 const SCEVHandle &Conc,
292 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000293 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000294 SCEVHandle H =
295 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000296 if (H != getOperand(i)) {
297 std::vector<SCEVHandle> NewOps;
298 NewOps.reserve(getNumOperands());
299 for (unsigned j = 0; j != i; ++j)
300 NewOps.push_back(getOperand(j));
301 NewOps.push_back(H);
302 for (++i; i != e; ++i)
303 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000304 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000305
306 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000307 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000309 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000310 else if (isa<SCEVSMaxExpr>(this))
311 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000312 else if (isa<SCEVUMaxExpr>(this))
313 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000314 else
315 assert(0 && "Unknown commutative expr!");
316 }
317 }
318 return this;
319}
320
Dan Gohman72a8a022009-05-07 14:00:19 +0000321bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng98c073b2009-02-17 00:13:06 +0000322 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
323 if (!getOperand(i)->dominates(BB, DT))
324 return false;
325 }
326 return true;
327}
328
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000329
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000330// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331// input. Don't use a SCEVHandle here, or else the object will never be
332// deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000333static ManagedStatic<std::map<std::pair<const SCEV*, const SCEV*>,
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000334 SCEVUDivExpr*> > SCEVUDivs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000335
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000336SCEVUDivExpr::~SCEVUDivExpr() {
337 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000338}
339
Evan Cheng98c073b2009-02-17 00:13:06 +0000340bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
341 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
342}
343
Dan Gohman13058cc2009-04-21 00:47:46 +0000344void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000345 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346}
347
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000348const Type *SCEVUDivExpr::getType() const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349 return LHS->getType();
350}
351
352// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
353// particular input. Don't use a SCEVHandle here, or else the object will never
354// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000355static ManagedStatic<std::map<std::pair<const Loop *,
356 std::vector<const SCEV*> >,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357 SCEVAddRecExpr*> > SCEVAddRecExprs;
358
359SCEVAddRecExpr::~SCEVAddRecExpr() {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000360 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
361 SCEVAddRecExprs->erase(std::make_pair(L, SCEVOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000362}
363
364SCEVHandle SCEVAddRecExpr::
365replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000366 const SCEVHandle &Conc,
367 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000368 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000369 SCEVHandle H =
370 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000371 if (H != getOperand(i)) {
372 std::vector<SCEVHandle> NewOps;
373 NewOps.reserve(getNumOperands());
374 for (unsigned j = 0; j != i; ++j)
375 NewOps.push_back(getOperand(j));
376 NewOps.push_back(H);
377 for (++i; i != e; ++i)
378 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000379 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000380
Dan Gohman89f85052007-10-22 18:31:58 +0000381 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000382 }
383 }
384 return this;
385}
386
387
388bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
389 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
390 // contain L and if the start is invariant.
391 return !QueryLoop->contains(L->getHeader()) &&
392 getOperand(0)->isLoopInvariant(QueryLoop);
393}
394
395
Dan Gohman13058cc2009-04-21 00:47:46 +0000396void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000397 OS << "{" << *Operands[0];
398 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
399 OS << ",+," << *Operands[i];
400 OS << "}<" << L->getHeader()->getName() + ">";
401}
402
403// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
404// value. Don't use a SCEVHandle here, or else the object will never be
405// deleted!
406static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
407
408SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
409
410bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
411 // All non-instruction values are loop invariant. All instructions are loop
412 // invariant if they are not contained in the specified loop.
413 if (Instruction *I = dyn_cast<Instruction>(V))
414 return !L->contains(I->getParent());
415 return true;
416}
417
Evan Cheng98c073b2009-02-17 00:13:06 +0000418bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
419 if (Instruction *I = dyn_cast<Instruction>(getValue()))
420 return DT->dominates(I->getParent(), BB);
421 return true;
422}
423
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000424const Type *SCEVUnknown::getType() const {
425 return V->getType();
426}
427
Dan Gohman13058cc2009-04-21 00:47:46 +0000428void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000429 WriteAsOperand(OS, V, false);
430}
431
432//===----------------------------------------------------------------------===//
433// SCEV Utilities
434//===----------------------------------------------------------------------===//
435
436namespace {
437 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
438 /// than the complexity of the RHS. This comparator is used to canonicalize
439 /// expressions.
Dan Gohman5d486452009-05-07 14:39:04 +0000440 class VISIBILITY_HIDDEN SCEVComplexityCompare {
441 LoopInfo *LI;
442 public:
443 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
444
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000445 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman5d486452009-05-07 14:39:04 +0000446 // Primarily, sort the SCEVs by their getSCEVType().
447 if (LHS->getSCEVType() != RHS->getSCEVType())
448 return LHS->getSCEVType() < RHS->getSCEVType();
449
450 // Aside from the getSCEVType() ordering, the particular ordering
451 // isn't very important except that it's beneficial to be consistent,
452 // so that (a + b) and (b + a) don't end up as different expressions.
453
454 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
455 // not as complete as it could be.
456 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
457 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
458
459 // Compare getValueID values.
460 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
461 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
462
463 // Sort arguments by their position.
464 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
465 const Argument *RA = cast<Argument>(RU->getValue());
466 return LA->getArgNo() < RA->getArgNo();
467 }
468
469 // For instructions, compare their loop depth, and their opcode.
470 // This is pretty loose.
471 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
472 Instruction *RV = cast<Instruction>(RU->getValue());
473
474 // Compare loop depths.
475 if (LI->getLoopDepth(LV->getParent()) !=
476 LI->getLoopDepth(RV->getParent()))
477 return LI->getLoopDepth(LV->getParent()) <
478 LI->getLoopDepth(RV->getParent());
479
480 // Compare opcodes.
481 if (LV->getOpcode() != RV->getOpcode())
482 return LV->getOpcode() < RV->getOpcode();
483
484 // Compare the number of operands.
485 if (LV->getNumOperands() != RV->getNumOperands())
486 return LV->getNumOperands() < RV->getNumOperands();
487 }
488
489 return false;
490 }
491
492 // Constant sorting doesn't matter since they'll be folded.
493 if (isa<SCEVConstant>(LHS))
494 return false;
495
496 // Lexicographically compare n-ary expressions.
497 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
498 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
499 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
500 if (i >= RC->getNumOperands())
501 return false;
502 if (operator()(LC->getOperand(i), RC->getOperand(i)))
503 return true;
504 if (operator()(RC->getOperand(i), LC->getOperand(i)))
505 return false;
506 }
507 return LC->getNumOperands() < RC->getNumOperands();
508 }
509
Dan Gohman6e10db12009-05-07 19:23:21 +0000510 // Lexicographically compare udiv expressions.
511 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
512 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
513 if (operator()(LC->getLHS(), RC->getLHS()))
514 return true;
515 if (operator()(RC->getLHS(), LC->getLHS()))
516 return false;
517 if (operator()(LC->getRHS(), RC->getRHS()))
518 return true;
519 if (operator()(RC->getRHS(), LC->getRHS()))
520 return false;
521 return false;
522 }
523
Dan Gohman5d486452009-05-07 14:39:04 +0000524 // Compare cast expressions by operand.
525 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
526 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
527 return operator()(LC->getOperand(), RC->getOperand());
528 }
529
530 assert(0 && "Unknown SCEV kind!");
531 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000532 }
533 };
534}
535
536/// GroupByComplexity - Given a list of SCEV objects, order them by their
537/// complexity, and group objects of the same complexity together by value.
538/// When this routine is finished, we know that any duplicates in the vector are
539/// consecutive and that complexity is monotonically increasing.
540///
541/// Note that we go take special precautions to ensure that we get determinstic
542/// results from this routine. In other words, we don't want the results of
543/// this to depend on where the addresses of various SCEV objects happened to
544/// land in memory.
545///
Dan Gohman5d486452009-05-07 14:39:04 +0000546static void GroupByComplexity(std::vector<SCEVHandle> &Ops,
547 LoopInfo *LI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000548 if (Ops.size() < 2) return; // Noop
549 if (Ops.size() == 2) {
550 // This is the common case, which also happens to be trivially simple.
551 // Special case it.
Dan Gohman5d486452009-05-07 14:39:04 +0000552 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000553 std::swap(Ops[0], Ops[1]);
554 return;
555 }
556
557 // Do the rough sort by complexity.
Dan Gohman5d486452009-05-07 14:39:04 +0000558 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000559
560 // Now that we are sorted by complexity, group elements of the same
561 // complexity. Note that this is, at worst, N^2, but the vector is likely to
562 // be extremely short in practice. Note that we take this approach because we
563 // do not want to depend on the addresses of the objects we are grouping.
564 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000565 const SCEV *S = Ops[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000566 unsigned Complexity = S->getSCEVType();
567
568 // If there are any objects of the same complexity and same value as this
569 // one, group them.
570 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
571 if (Ops[j] == S) { // Found a duplicate.
572 // Move it to immediately after i'th element.
573 std::swap(Ops[i+1], Ops[j]);
574 ++i; // no need to rescan it.
575 if (i == e-2) return; // Done!
576 }
577 }
578 }
579}
580
581
582
583//===----------------------------------------------------------------------===//
584// Simple SCEV method implementations
585//===----------------------------------------------------------------------===//
586
Eli Friedman7489ec92008-08-04 23:49:06 +0000587/// BinomialCoefficient - Compute BC(It, K). The result has width W.
588// Assume, K > 0.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000589static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000590 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000591 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000592 // Handle the simplest case efficiently.
593 if (K == 1)
594 return SE.getTruncateOrZeroExtend(It, ResultTy);
595
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000596 // We are using the following formula for BC(It, K):
597 //
598 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
599 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000600 // Suppose, W is the bitwidth of the return value. We must be prepared for
601 // overflow. Hence, we must assure that the result of our computation is
602 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
603 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000604 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000605 // However, this code doesn't use exactly that formula; the formula it uses
606 // is something like the following, where T is the number of factors of 2 in
607 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
608 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000609 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000610 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000611 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000612 // This formula is trivially equivalent to the previous formula. However,
613 // this formula can be implemented much more efficiently. The trick is that
614 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
615 // arithmetic. To do exact division in modular arithmetic, all we have
616 // to do is multiply by the inverse. Therefore, this step can be done at
617 // width W.
618 //
619 // The next issue is how to safely do the division by 2^T. The way this
620 // is done is by doing the multiplication step at a width of at least W + T
621 // bits. This way, the bottom W+T bits of the product are accurate. Then,
622 // when we perform the division by 2^T (which is equivalent to a right shift
623 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
624 // truncated out after the division by 2^T.
625 //
626 // In comparison to just directly using the first formula, this technique
627 // is much more efficient; using the first formula requires W * K bits,
628 // but this formula less than W + K bits. Also, the first formula requires
629 // a division step, whereas this formula only requires multiplies and shifts.
630 //
631 // It doesn't matter whether the subtraction step is done in the calculation
632 // width or the input iteration count's width; if the subtraction overflows,
633 // the result must be zero anyway. We prefer here to do it in the width of
634 // the induction variable because it helps a lot for certain cases; CodeGen
635 // isn't smart enough to ignore the overflow, which leads to much less
636 // efficient code if the width of the subtraction is wider than the native
637 // register width.
638 //
639 // (It's possible to not widen at all by pulling out factors of 2 before
640 // the multiplication; for example, K=2 can be calculated as
641 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
642 // extra arithmetic, so it's not an obvious win, and it gets
643 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000644
Eli Friedman7489ec92008-08-04 23:49:06 +0000645 // Protection from insane SCEVs; this bound is conservative,
646 // but it probably doesn't matter.
647 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000648 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000649
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000650 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000651
Eli Friedman7489ec92008-08-04 23:49:06 +0000652 // Calculate K! / 2^T and T; we divide out the factors of two before
653 // multiplying for calculating K! / 2^T to avoid overflow.
654 // Other overflow doesn't matter because we only care about the bottom
655 // W bits of the result.
656 APInt OddFactorial(W, 1);
657 unsigned T = 1;
658 for (unsigned i = 3; i <= K; ++i) {
659 APInt Mult(W, i);
660 unsigned TwoFactors = Mult.countTrailingZeros();
661 T += TwoFactors;
662 Mult = Mult.lshr(TwoFactors);
663 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000665
Eli Friedman7489ec92008-08-04 23:49:06 +0000666 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000667 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000668
669 // Calcuate 2^T, at width T+W.
670 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
671
672 // Calculate the multiplicative inverse of K! / 2^T;
673 // this multiplication factor will perform the exact division by
674 // K! / 2^T.
675 APInt Mod = APInt::getSignedMinValue(W+1);
676 APInt MultiplyFactor = OddFactorial.zext(W+1);
677 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
678 MultiplyFactor = MultiplyFactor.trunc(W);
679
680 // Calculate the product, at width T+W
681 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
682 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
683 for (unsigned i = 1; i != K; ++i) {
684 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
685 Dividend = SE.getMulExpr(Dividend,
686 SE.getTruncateOrZeroExtend(S, CalculationTy));
687 }
688
689 // Divide by 2^T
690 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
691
692 // Truncate the result, and divide by K! / 2^T.
693
694 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
695 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000696}
697
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000698/// evaluateAtIteration - Return the value of this chain of recurrences at
699/// the specified iteration number. We can evaluate this recurrence by
700/// multiplying each element in the chain by the binomial coefficient
701/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
702///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000703/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000704///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000705/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000706///
Dan Gohman89f85052007-10-22 18:31:58 +0000707SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
708 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000709 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000710 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000711 // The computation is correct in the face of overflow provided that the
712 // multiplication is performed _after_ the evaluation of the binomial
713 // coefficient.
Dan Gohman01c2ee72009-04-16 03:18:22 +0000714 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000715 if (isa<SCEVCouldNotCompute>(Coeff))
716 return Coeff;
717
718 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000719 }
720 return Result;
721}
722
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000723//===----------------------------------------------------------------------===//
724// SCEV Expression folder implementations
725//===----------------------------------------------------------------------===//
726
Dan Gohman9c8abcc2009-05-01 16:44:56 +0000727SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
728 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000729 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000730 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000731 assert(isSCEVable(Ty) &&
732 "This is not a conversion to a SCEVable type!");
733 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000734
Dan Gohmanc76b5452009-05-04 22:02:23 +0000735 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000736 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000737 ConstantExpr::getTrunc(SC->getValue(), Ty));
738
Dan Gohman1a5c4992009-04-22 16:20:48 +0000739 // trunc(trunc(x)) --> trunc(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000740 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000741 return getTruncateExpr(ST->getOperand(), Ty);
742
Nick Lewycky37d04642009-04-23 05:15:08 +0000743 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000744 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000745 return getTruncateOrSignExtend(SS->getOperand(), Ty);
746
747 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000748 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000749 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
750
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000751 // If the input value is a chrec scev made out of constants, truncate
752 // all of the constants.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000753 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000754 std::vector<SCEVHandle> Operands;
755 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman45b3b542009-05-08 21:03:19 +0000756 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
757 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000758 }
759
760 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
761 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
762 return Result;
763}
764
Dan Gohman36d40922009-04-16 19:25:55 +0000765SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
766 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000767 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000768 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000769 assert(isSCEVable(Ty) &&
770 "This is not a conversion to a SCEVable type!");
771 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000772
Dan Gohmanc76b5452009-05-04 22:02:23 +0000773 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000774 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000775 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
776 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
777 return getUnknown(C);
778 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000779
Dan Gohman1a5c4992009-04-22 16:20:48 +0000780 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000781 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000782 return getZeroExtendExpr(SZ->getOperand(), Ty);
783
Dan Gohmana9dba962009-04-27 20:16:15 +0000784 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000786 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000788 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000789 if (AR->isAffine()) {
790 // Check whether the backedge-taken count is SCEVCouldNotCompute.
791 // Note that this serves two purposes: It filters out loops that are
792 // simply not analyzable, and it covers the case where this code is
793 // being called from within backedge-taken count analysis, such that
794 // attempting to ask for the backedge-taken count would likely result
795 // in infinite recursion. In the later case, the analysis code will
796 // cope with a conservative value, and it will take care to purge
797 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000798 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
799 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000800 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000801 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000802 SCEVHandle Start = AR->getStart();
803 SCEVHandle Step = AR->getStepRecurrence(*this);
804
805 // Check whether the backedge-taken count can be losslessly casted to
806 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000807 SCEVHandle CastedMaxBECount =
808 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman3bb37f52009-05-18 15:58:39 +0000809 SCEVHandle RecastedMaxBECount =
810 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
811 if (MaxBECount == RecastedMaxBECount) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000812 const Type *WideTy =
813 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000814 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000815 SCEVHandle ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000816 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000817 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000818 SCEVHandle Add = getAddExpr(Start, ZMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000819 SCEVHandle OperandExtendedAdd =
820 getAddExpr(getZeroExtendExpr(Start, WideTy),
821 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
822 getZeroExtendExpr(Step, WideTy)));
823 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000824 // Return the expression with the addrec on the outside.
825 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
826 getZeroExtendExpr(Step, Ty),
827 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000828
829 // Similar to above, only this time treat the step value as signed.
830 // This covers loops that count down.
831 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000832 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000833 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000834 Add = getAddExpr(Start, SMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000835 OperandExtendedAdd =
836 getAddExpr(getZeroExtendExpr(Start, WideTy),
837 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
838 getSignExtendExpr(Step, WideTy)));
839 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000840 // Return the expression with the addrec on the outside.
841 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
842 getSignExtendExpr(Step, Ty),
843 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000844 }
845 }
846 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000847
848 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
849 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
850 return Result;
851}
852
Dan Gohmana9dba962009-04-27 20:16:15 +0000853SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
854 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000855 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000856 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000857 assert(isSCEVable(Ty) &&
858 "This is not a conversion to a SCEVable type!");
859 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000860
Dan Gohmanc76b5452009-05-04 22:02:23 +0000861 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000862 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000863 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
864 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
865 return getUnknown(C);
866 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000867
Dan Gohman1a5c4992009-04-22 16:20:48 +0000868 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000869 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000870 return getSignExtendExpr(SS->getOperand(), Ty);
871
Dan Gohmana9dba962009-04-27 20:16:15 +0000872 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000873 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000874 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000875 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000876 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000877 if (AR->isAffine()) {
878 // Check whether the backedge-taken count is SCEVCouldNotCompute.
879 // Note that this serves two purposes: It filters out loops that are
880 // simply not analyzable, and it covers the case where this code is
881 // being called from within backedge-taken count analysis, such that
882 // attempting to ask for the backedge-taken count would likely result
883 // in infinite recursion. In the later case, the analysis code will
884 // cope with a conservative value, and it will take care to purge
885 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000886 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
887 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000888 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000889 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000890 SCEVHandle Start = AR->getStart();
891 SCEVHandle Step = AR->getStepRecurrence(*this);
892
893 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000894 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000895 SCEVHandle CastedMaxBECount =
896 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman3bb37f52009-05-18 15:58:39 +0000897 SCEVHandle RecastedMaxBECount =
898 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
899 if (MaxBECount == RecastedMaxBECount) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000900 const Type *WideTy =
901 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000902 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000903 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000904 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000905 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000906 SCEVHandle Add = getAddExpr(Start, SMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000907 SCEVHandle OperandExtendedAdd =
908 getAddExpr(getSignExtendExpr(Start, WideTy),
909 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
910 getSignExtendExpr(Step, WideTy)));
911 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000912 // Return the expression with the addrec on the outside.
913 return getAddRecExpr(getSignExtendExpr(Start, Ty),
914 getSignExtendExpr(Step, Ty),
915 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000916 }
917 }
918 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000919
920 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
921 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
922 return Result;
923}
924
925// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000926SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000927 assert(!Ops.empty() && "Cannot get empty add!");
928 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +0000929#ifndef NDEBUG
930 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
931 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
932 getEffectiveSCEVType(Ops[0]->getType()) &&
933 "SCEVAddExpr operand types don't match!");
934#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000935
936 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +0000937 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000938
939 // If there are any constants, fold them together.
940 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +0000941 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000942 ++Idx;
943 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +0000944 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000945 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000946 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
947 RHSC->getValue()->getValue());
948 Ops[0] = getConstant(Fold);
949 Ops.erase(Ops.begin()+1); // Erase the folded element
950 if (Ops.size() == 1) return Ops[0];
951 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000952 }
953
954 // If we are left with a constant zero being added, strip it off.
955 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
956 Ops.erase(Ops.begin());
957 --Idx;
958 }
959 }
960
961 if (Ops.size() == 1) return Ops[0];
962
963 // Okay, check to see if the same value occurs in the operand list twice. If
964 // so, merge them together into an multiply expression. Since we sorted the
965 // list, these values are required to be adjacent.
966 const Type *Ty = Ops[0]->getType();
967 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
968 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
969 // Found a match, merge the two values into a multiply, and add any
970 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000971 SCEVHandle Two = getIntegerSCEV(2, Ty);
972 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000973 if (Ops.size() == 2)
974 return Mul;
975 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
976 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000977 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000978 }
979
Dan Gohman45b3b542009-05-08 21:03:19 +0000980 // Check for truncates. If all the operands are truncated from the same
981 // type, see if factoring out the truncate would permit the result to be
982 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
983 // if the contents of the resulting outer trunc fold to something simple.
984 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
985 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
986 const Type *DstType = Trunc->getType();
987 const Type *SrcType = Trunc->getOperand()->getType();
988 std::vector<SCEVHandle> LargeOps;
989 bool Ok = true;
990 // Check all the operands to see if they can be represented in the
991 // source type of the truncate.
992 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
993 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
994 if (T->getOperand()->getType() != SrcType) {
995 Ok = false;
996 break;
997 }
998 LargeOps.push_back(T->getOperand());
999 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1000 // This could be either sign or zero extension, but sign extension
1001 // is much more likely to be foldable here.
1002 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1003 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
1004 std::vector<SCEVHandle> LargeMulOps;
1005 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1006 if (const SCEVTruncateExpr *T =
1007 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1008 if (T->getOperand()->getType() != SrcType) {
1009 Ok = false;
1010 break;
1011 }
1012 LargeMulOps.push_back(T->getOperand());
1013 } else if (const SCEVConstant *C =
1014 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1015 // This could be either sign or zero extension, but sign extension
1016 // is much more likely to be foldable here.
1017 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1018 } else {
1019 Ok = false;
1020 break;
1021 }
1022 }
1023 if (Ok)
1024 LargeOps.push_back(getMulExpr(LargeMulOps));
1025 } else {
1026 Ok = false;
1027 break;
1028 }
1029 }
1030 if (Ok) {
1031 // Evaluate the expression in the larger type.
1032 SCEVHandle Fold = getAddExpr(LargeOps);
1033 // If it folds to something simple, use it. Otherwise, don't.
1034 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1035 return getTruncateExpr(Fold, DstType);
1036 }
1037 }
1038
1039 // Skip past any other cast SCEVs.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001040 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1041 ++Idx;
1042
1043 // If there are add operands they would be next.
1044 if (Idx < Ops.size()) {
1045 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001046 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001047 // If we have an add, expand the add operands onto the end of the operands
1048 // list.
1049 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1050 Ops.erase(Ops.begin()+Idx);
1051 DeletedAdd = true;
1052 }
1053
1054 // If we deleted at least one add, we added operands to the end of the list,
1055 // and they are not necessarily sorted. Recurse to resort and resimplify
1056 // any operands we just aquired.
1057 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +00001058 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059 }
1060
1061 // Skip over the add expression until we get to a multiply.
1062 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1063 ++Idx;
1064
1065 // If we are adding something to a multiply expression, make sure the
1066 // something is not already an operand of the multiply. If so, merge it into
1067 // the multiply.
1068 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001069 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001070 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001071 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001072 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
1073 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
1074 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1075 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
1076 if (Mul->getNumOperands() != 2) {
1077 // If the multiply has more than two operands, we must get the
1078 // Y*Z term.
1079 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1080 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001081 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001082 }
Dan Gohman89f85052007-10-22 18:31:58 +00001083 SCEVHandle One = getIntegerSCEV(1, Ty);
1084 SCEVHandle AddOne = getAddExpr(InnerMul, One);
1085 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001086 if (Ops.size() == 2) return OuterMul;
1087 if (AddOp < Idx) {
1088 Ops.erase(Ops.begin()+AddOp);
1089 Ops.erase(Ops.begin()+Idx-1);
1090 } else {
1091 Ops.erase(Ops.begin()+Idx);
1092 Ops.erase(Ops.begin()+AddOp-1);
1093 }
1094 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001095 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001096 }
1097
1098 // Check this multiply against other multiplies being added together.
1099 for (unsigned OtherMulIdx = Idx+1;
1100 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1101 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001102 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103 // If MulOp occurs in OtherMul, we can fold the two multiplies
1104 // together.
1105 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1106 OMulOp != e; ++OMulOp)
1107 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1108 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1109 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1110 if (Mul->getNumOperands() != 2) {
1111 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1112 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001113 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001114 }
1115 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1116 if (OtherMul->getNumOperands() != 2) {
1117 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
1118 OtherMul->op_end());
1119 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001120 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001121 }
Dan Gohman89f85052007-10-22 18:31:58 +00001122 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1123 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001124 if (Ops.size() == 2) return OuterMul;
1125 Ops.erase(Ops.begin()+Idx);
1126 Ops.erase(Ops.begin()+OtherMulIdx-1);
1127 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001128 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001129 }
1130 }
1131 }
1132 }
1133
1134 // If there are any add recurrences in the operands list, see if any other
1135 // added values are loop invariant. If so, we can fold them into the
1136 // recurrence.
1137 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1138 ++Idx;
1139
1140 // Scan over all recurrences, trying to fold loop invariants into them.
1141 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1142 // Scan all of the other operands to this add and add them to the vector if
1143 // they are loop invariant w.r.t. the recurrence.
1144 std::vector<SCEVHandle> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001145 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1147 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1148 LIOps.push_back(Ops[i]);
1149 Ops.erase(Ops.begin()+i);
1150 --i; --e;
1151 }
1152
1153 // If we found some loop invariants, fold them into the recurrence.
1154 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001155 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001156 LIOps.push_back(AddRec->getStart());
1157
1158 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001159 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001160
Dan Gohman89f85052007-10-22 18:31:58 +00001161 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001162 // If all of the other operands were loop invariant, we are done.
1163 if (Ops.size() == 1) return NewRec;
1164
1165 // Otherwise, add the folded AddRec by the non-liv parts.
1166 for (unsigned i = 0;; ++i)
1167 if (Ops[i] == AddRec) {
1168 Ops[i] = NewRec;
1169 break;
1170 }
Dan Gohman89f85052007-10-22 18:31:58 +00001171 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001172 }
1173
1174 // Okay, if there weren't any loop invariants to be folded, check to see if
1175 // there are multiple AddRec's with the same loop induction variable being
1176 // added together. If so, we can fold them.
1177 for (unsigned OtherIdx = Idx+1;
1178 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1179 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001180 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001181 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1182 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1183 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1184 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1185 if (i >= NewOps.size()) {
1186 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1187 OtherAddRec->op_end());
1188 break;
1189 }
Dan Gohman89f85052007-10-22 18:31:58 +00001190 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001191 }
Dan Gohman89f85052007-10-22 18:31:58 +00001192 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001193
1194 if (Ops.size() == 2) return NewAddRec;
1195
1196 Ops.erase(Ops.begin()+Idx);
1197 Ops.erase(Ops.begin()+OtherIdx-1);
1198 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001199 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001200 }
1201 }
1202
1203 // Otherwise couldn't fold anything into this recurrence. Move onto the
1204 // next one.
1205 }
1206
1207 // Okay, it looks like we really DO need an add expr. Check to see if we
1208 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001209 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001210 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1211 SCEVOps)];
1212 if (Result == 0) Result = new SCEVAddExpr(Ops);
1213 return Result;
1214}
1215
1216
Dan Gohman89f85052007-10-22 18:31:58 +00001217SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001218 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana77b3d42009-05-18 15:44:58 +00001219#ifndef NDEBUG
1220 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1221 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1222 getEffectiveSCEVType(Ops[0]->getType()) &&
1223 "SCEVMulExpr operand types don't match!");
1224#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001225
1226 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001227 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001228
1229 // If there are any constants, fold them together.
1230 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001231 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001232
1233 // C1*(C2+V) -> C1*C2 + C1*V
1234 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001235 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001236 if (Add->getNumOperands() == 2 &&
1237 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001238 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1239 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001240
1241
1242 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001243 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001244 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001245 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1246 RHSC->getValue()->getValue());
1247 Ops[0] = getConstant(Fold);
1248 Ops.erase(Ops.begin()+1); // Erase the folded element
1249 if (Ops.size() == 1) return Ops[0];
1250 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001251 }
1252
1253 // If we are left with a constant one being multiplied, strip it off.
1254 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1255 Ops.erase(Ops.begin());
1256 --Idx;
1257 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1258 // If we have a multiply of zero, it will always be zero.
1259 return Ops[0];
1260 }
1261 }
1262
1263 // Skip over the add expression until we get to a multiply.
1264 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1265 ++Idx;
1266
1267 if (Ops.size() == 1)
1268 return Ops[0];
1269
1270 // If there are mul operands inline them all into this expression.
1271 if (Idx < Ops.size()) {
1272 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001273 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274 // If we have an mul, expand the mul operands onto the end of the operands
1275 // list.
1276 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1277 Ops.erase(Ops.begin()+Idx);
1278 DeletedMul = true;
1279 }
1280
1281 // If we deleted at least one mul, we added operands to the end of the list,
1282 // and they are not necessarily sorted. Recurse to resort and resimplify
1283 // any operands we just aquired.
1284 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001285 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001286 }
1287
1288 // If there are any add recurrences in the operands list, see if any other
1289 // added values are loop invariant. If so, we can fold them into the
1290 // recurrence.
1291 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1292 ++Idx;
1293
1294 // Scan over all recurrences, trying to fold loop invariants into them.
1295 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1296 // Scan all of the other operands to this mul and add them to the vector if
1297 // they are loop invariant w.r.t. the recurrence.
1298 std::vector<SCEVHandle> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001299 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001300 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1301 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1302 LIOps.push_back(Ops[i]);
1303 Ops.erase(Ops.begin()+i);
1304 --i; --e;
1305 }
1306
1307 // If we found some loop invariants, fold them into the recurrence.
1308 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001309 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001310 std::vector<SCEVHandle> NewOps;
1311 NewOps.reserve(AddRec->getNumOperands());
1312 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001313 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001314 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001315 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001316 } else {
1317 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1318 std::vector<SCEVHandle> MulOps(LIOps);
1319 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001320 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321 }
1322 }
1323
Dan Gohman89f85052007-10-22 18:31:58 +00001324 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001325
1326 // If all of the other operands were loop invariant, we are done.
1327 if (Ops.size() == 1) return NewRec;
1328
1329 // Otherwise, multiply the folded AddRec by the non-liv parts.
1330 for (unsigned i = 0;; ++i)
1331 if (Ops[i] == AddRec) {
1332 Ops[i] = NewRec;
1333 break;
1334 }
Dan Gohman89f85052007-10-22 18:31:58 +00001335 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001336 }
1337
1338 // Okay, if there weren't any loop invariants to be folded, check to see if
1339 // there are multiple AddRec's with the same loop induction variable being
1340 // multiplied together. If so, we can fold them.
1341 for (unsigned OtherIdx = Idx+1;
1342 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1343 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001344 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001345 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1346 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001347 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001348 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001350 SCEVHandle B = F->getStepRecurrence(*this);
1351 SCEVHandle D = G->getStepRecurrence(*this);
1352 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1353 getMulExpr(G, B),
1354 getMulExpr(B, D));
1355 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1356 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001357 if (Ops.size() == 2) return NewAddRec;
1358
1359 Ops.erase(Ops.begin()+Idx);
1360 Ops.erase(Ops.begin()+OtherIdx-1);
1361 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001362 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001363 }
1364 }
1365
1366 // Otherwise couldn't fold anything into this recurrence. Move onto the
1367 // next one.
1368 }
1369
1370 // Okay, it looks like we really DO need an mul expr. Check to see if we
1371 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001372 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001373 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1374 SCEVOps)];
1375 if (Result == 0)
1376 Result = new SCEVMulExpr(Ops);
1377 return Result;
1378}
1379
Dan Gohman77841cd2009-05-04 22:23:18 +00001380SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1381 const SCEVHandle &RHS) {
Dan Gohmana77b3d42009-05-18 15:44:58 +00001382 assert(getEffectiveSCEVType(LHS->getType()) ==
1383 getEffectiveSCEVType(RHS->getType()) &&
1384 "SCEVUDivExpr operand types don't match!");
1385
Dan Gohmanc76b5452009-05-04 22:02:23 +00001386 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001387 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001388 return LHS; // X udiv 1 --> x
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001389 if (RHSC->isZero())
1390 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001391
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001392 // Determine if the division can be folded into the operands of
1393 // its operands.
1394 // TODO: Generalize this to non-constants by using known-bits information.
1395 const Type *Ty = LHS->getType();
1396 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1397 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1398 // For non-power-of-two values, effectively round the value up to the
1399 // nearest power of two.
1400 if (!RHSC->getValue()->getValue().isPowerOf2())
1401 ++MaxShiftAmt;
1402 const IntegerType *ExtTy =
1403 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1404 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1405 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1406 if (const SCEVConstant *Step =
1407 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1408 if (!Step->getValue()->getValue()
1409 .urem(RHSC->getValue()->getValue()) &&
Dan Gohman14374d32009-05-08 23:11:16 +00001410 getZeroExtendExpr(AR, ExtTy) ==
1411 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1412 getZeroExtendExpr(Step, ExtTy),
1413 AR->getLoop())) {
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001414 std::vector<SCEVHandle> Operands;
1415 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1416 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1417 return getAddRecExpr(Operands, AR->getLoop());
1418 }
1419 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001420 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1421 std::vector<SCEVHandle> Operands;
1422 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1423 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1424 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001425 // Find an operand that's safely divisible.
1426 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1427 SCEVHandle Op = M->getOperand(i);
1428 SCEVHandle Div = getUDivExpr(Op, RHSC);
1429 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman14374d32009-05-08 23:11:16 +00001430 Operands = M->getOperands();
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001431 Operands[i] = Div;
1432 return getMulExpr(Operands);
1433 }
1434 }
Dan Gohman14374d32009-05-08 23:11:16 +00001435 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001436 // (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 +00001437 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1438 std::vector<SCEVHandle> Operands;
1439 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1440 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1441 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1442 Operands.clear();
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001443 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1444 SCEVHandle Op = getUDivExpr(A->getOperand(i), RHS);
1445 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1446 break;
1447 Operands.push_back(Op);
1448 }
1449 if (Operands.size() == A->getNumOperands())
1450 return getAddExpr(Operands);
1451 }
Dan Gohman14374d32009-05-08 23:11:16 +00001452 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001453
1454 // Fold if both operands are constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001455 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001456 Constant *LHSCV = LHSC->getValue();
1457 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001458 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001459 }
1460 }
1461
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001462 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1463 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001464 return Result;
1465}
1466
1467
1468/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1469/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001470SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001471 const SCEVHandle &Step, const Loop *L) {
1472 std::vector<SCEVHandle> Operands;
1473 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001474 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001475 if (StepChrec->getLoop() == L) {
1476 Operands.insert(Operands.end(), StepChrec->op_begin(),
1477 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001478 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001479 }
1480
1481 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001482 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001483}
1484
1485/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1486/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001487SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Nick Lewycky37d04642009-04-23 05:15:08 +00001488 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001489 if (Operands.size() == 1) return Operands[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001490#ifndef NDEBUG
1491 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1492 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1493 getEffectiveSCEVType(Operands[0]->getType()) &&
1494 "SCEVAddRecExpr operand types don't match!");
1495#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001496
Dan Gohman7b560c42008-06-18 16:23:07 +00001497 if (Operands.back()->isZero()) {
1498 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001499 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001500 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001501
Dan Gohman42936882008-08-08 18:33:12 +00001502 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001503 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001504 const Loop* NestedLoop = NestedAR->getLoop();
1505 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1506 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1507 NestedAR->op_end());
1508 SCEVHandle NestedARHandle(NestedAR);
1509 Operands[0] = NestedAR->getStart();
1510 NestedOperands[0] = getAddRecExpr(Operands, L);
1511 return getAddRecExpr(NestedOperands, NestedLoop);
1512 }
1513 }
1514
Dan Gohmanbff6b582009-05-04 22:30:44 +00001515 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1516 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001517 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1518 return Result;
1519}
1520
Nick Lewycky711640a2007-11-25 22:41:31 +00001521SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1522 const SCEVHandle &RHS) {
1523 std::vector<SCEVHandle> Ops;
1524 Ops.push_back(LHS);
1525 Ops.push_back(RHS);
1526 return getSMaxExpr(Ops);
1527}
1528
1529SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1530 assert(!Ops.empty() && "Cannot get empty smax!");
1531 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001532#ifndef NDEBUG
1533 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1534 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1535 getEffectiveSCEVType(Ops[0]->getType()) &&
1536 "SCEVSMaxExpr operand types don't match!");
1537#endif
Nick Lewycky711640a2007-11-25 22:41:31 +00001538
1539 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001540 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001541
1542 // If there are any constants, fold them together.
1543 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001544 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001545 ++Idx;
1546 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001547 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001548 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001549 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001550 APIntOps::smax(LHSC->getValue()->getValue(),
1551 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001552 Ops[0] = getConstant(Fold);
1553 Ops.erase(Ops.begin()+1); // Erase the folded element
1554 if (Ops.size() == 1) return Ops[0];
1555 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001556 }
1557
1558 // If we are left with a constant -inf, strip it off.
1559 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1560 Ops.erase(Ops.begin());
1561 --Idx;
1562 }
1563 }
1564
1565 if (Ops.size() == 1) return Ops[0];
1566
1567 // Find the first SMax
1568 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1569 ++Idx;
1570
1571 // Check to see if one of the operands is an SMax. If so, expand its operands
1572 // onto our operand list, and recurse to simplify.
1573 if (Idx < Ops.size()) {
1574 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001575 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001576 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1577 Ops.erase(Ops.begin()+Idx);
1578 DeletedSMax = true;
1579 }
1580
1581 if (DeletedSMax)
1582 return getSMaxExpr(Ops);
1583 }
1584
1585 // Okay, check to see if the same value occurs in the operand list twice. If
1586 // so, delete one. Since we sorted the list, these values are required to
1587 // be adjacent.
1588 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1589 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1590 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1591 --i; --e;
1592 }
1593
1594 if (Ops.size() == 1) return Ops[0];
1595
1596 assert(!Ops.empty() && "Reduced smax down to nothing!");
1597
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001598 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001599 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001600 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewycky711640a2007-11-25 22:41:31 +00001601 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1602 SCEVOps)];
1603 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1604 return Result;
1605}
1606
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001607SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1608 const SCEVHandle &RHS) {
1609 std::vector<SCEVHandle> Ops;
1610 Ops.push_back(LHS);
1611 Ops.push_back(RHS);
1612 return getUMaxExpr(Ops);
1613}
1614
1615SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1616 assert(!Ops.empty() && "Cannot get empty umax!");
1617 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001618#ifndef NDEBUG
1619 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1620 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1621 getEffectiveSCEVType(Ops[0]->getType()) &&
1622 "SCEVUMaxExpr operand types don't match!");
1623#endif
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001624
1625 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001626 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001627
1628 // If there are any constants, fold them together.
1629 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001630 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001631 ++Idx;
1632 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001633 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001634 // We found two constants, fold them together!
1635 ConstantInt *Fold = ConstantInt::get(
1636 APIntOps::umax(LHSC->getValue()->getValue(),
1637 RHSC->getValue()->getValue()));
1638 Ops[0] = getConstant(Fold);
1639 Ops.erase(Ops.begin()+1); // Erase the folded element
1640 if (Ops.size() == 1) return Ops[0];
1641 LHSC = cast<SCEVConstant>(Ops[0]);
1642 }
1643
1644 // If we are left with a constant zero, strip it off.
1645 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1646 Ops.erase(Ops.begin());
1647 --Idx;
1648 }
1649 }
1650
1651 if (Ops.size() == 1) return Ops[0];
1652
1653 // Find the first UMax
1654 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1655 ++Idx;
1656
1657 // Check to see if one of the operands is a UMax. If so, expand its operands
1658 // onto our operand list, and recurse to simplify.
1659 if (Idx < Ops.size()) {
1660 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001661 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001662 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1663 Ops.erase(Ops.begin()+Idx);
1664 DeletedUMax = true;
1665 }
1666
1667 if (DeletedUMax)
1668 return getUMaxExpr(Ops);
1669 }
1670
1671 // Okay, check to see if the same value occurs in the operand list twice. If
1672 // so, delete one. Since we sorted the list, these values are required to
1673 // be adjacent.
1674 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1675 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1676 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1677 --i; --e;
1678 }
1679
1680 if (Ops.size() == 1) return Ops[0];
1681
1682 assert(!Ops.empty() && "Reduced umax down to nothing!");
1683
1684 // Okay, it looks like we really DO need a umax expr. Check to see if we
1685 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001686 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001687 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1688 SCEVOps)];
1689 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1690 return Result;
1691}
1692
Dan Gohman89f85052007-10-22 18:31:58 +00001693SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001694 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001695 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001696 if (isa<ConstantPointerNull>(V))
1697 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001698 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1699 if (Result == 0) Result = new SCEVUnknown(V);
1700 return Result;
1701}
1702
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001703//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001704// Basic SCEV Analysis and PHI Idiom Recognition Code
1705//
1706
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001707/// isSCEVable - Test if values of the given type are analyzable within
1708/// the SCEV framework. This primarily includes integer types, and it
1709/// can optionally include pointer types if the ScalarEvolution class
1710/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001711bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001712 // Integers are always SCEVable.
1713 if (Ty->isInteger())
1714 return true;
1715
1716 // Pointers are SCEVable if TargetData information is available
1717 // to provide pointer size information.
1718 if (isa<PointerType>(Ty))
1719 return TD != NULL;
1720
1721 // Otherwise it's not SCEVable.
1722 return false;
1723}
1724
1725/// getTypeSizeInBits - Return the size in bits of the specified type,
1726/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001727uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001728 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1729
1730 // If we have a TargetData, use it!
1731 if (TD)
1732 return TD->getTypeSizeInBits(Ty);
1733
1734 // Otherwise, we support only integer types.
1735 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1736 return Ty->getPrimitiveSizeInBits();
1737}
1738
1739/// getEffectiveSCEVType - Return a type with the same bitwidth as
1740/// the given type and which represents how SCEV will treat the given
1741/// type, for which isSCEVable must return true. For pointer types,
1742/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001743const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001744 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1745
1746 if (Ty->isInteger())
1747 return Ty;
1748
1749 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1750 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001751}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001752
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001753SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman0ad08b02009-04-18 17:58:19 +00001754 return UnknownValue;
1755}
1756
Dan Gohmand83d4af2009-05-04 22:20:30 +00001757/// hasSCEV - Return true if the SCEV for this value has already been
Edwin Török0e828d62009-05-01 08:33:47 +00001758/// computed.
1759bool ScalarEvolution::hasSCEV(Value *V) const {
1760 return Scalars.count(V);
1761}
1762
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001763/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1764/// expression and create a new one.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001765SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001766 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001767
Dan Gohmanbff6b582009-05-04 22:30:44 +00001768 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001769 if (I != Scalars.end()) return I->second;
1770 SCEVHandle S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00001771 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001772 return S;
1773}
1774
Dan Gohman01c2ee72009-04-16 03:18:22 +00001775/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1776/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001777SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1778 Ty = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001779 Constant *C;
1780 if (Val == 0)
1781 C = Constant::getNullValue(Ty);
1782 else if (Ty->isFloatingPoint())
1783 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1784 APFloat::IEEEdouble, Val));
1785 else
1786 C = ConstantInt::get(Ty, Val);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001787 return getUnknown(C);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001788}
1789
1790/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1791///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001792SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001793 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001794 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001795
1796 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001797 Ty = getEffectiveSCEVType(Ty);
1798 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001799}
1800
1801/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001802SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001803 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001804 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001805
1806 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001807 Ty = getEffectiveSCEVType(Ty);
1808 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001809 return getMinusSCEV(AllOnes, V);
1810}
1811
1812/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1813///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001814SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky37d04642009-04-23 05:15:08 +00001815 const SCEVHandle &RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001816 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001817 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001818}
1819
1820/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1821/// input value to the specified type. If the type must be extended, it is zero
1822/// extended.
1823SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001824ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001825 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001826 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001827 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1828 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001829 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001830 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001831 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001832 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001833 return getTruncateExpr(V, Ty);
1834 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001835}
1836
1837/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1838/// input value to the specified type. If the type must be extended, it is sign
1839/// extended.
1840SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001841ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001842 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001843 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001844 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1845 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001846 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001847 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001848 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001849 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001850 return getTruncateExpr(V, Ty);
1851 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001852}
1853
Dan Gohmanac959332009-05-13 03:46:30 +00001854/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
1855/// input value to the specified type. If the type must be extended, it is zero
1856/// extended. The conversion must not be narrowing.
1857SCEVHandle
1858ScalarEvolution::getNoopOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
1859 const Type *SrcTy = V->getType();
1860 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1861 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1862 "Cannot noop or zero extend with non-integer arguments!");
1863 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
1864 "getNoopOrZeroExtend cannot truncate!");
1865 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1866 return V; // No conversion
1867 return getZeroExtendExpr(V, Ty);
1868}
1869
1870/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
1871/// input value to the specified type. If the type must be extended, it is sign
1872/// extended. The conversion must not be narrowing.
1873SCEVHandle
1874ScalarEvolution::getNoopOrSignExtend(const SCEVHandle &V, const Type *Ty) {
1875 const Type *SrcTy = V->getType();
1876 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1877 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1878 "Cannot noop or sign extend with non-integer arguments!");
1879 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
1880 "getNoopOrSignExtend cannot truncate!");
1881 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1882 return V; // No conversion
1883 return getSignExtendExpr(V, Ty);
1884}
1885
1886/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
1887/// input value to the specified type. The conversion must not be widening.
1888SCEVHandle
1889ScalarEvolution::getTruncateOrNoop(const SCEVHandle &V, const Type *Ty) {
1890 const Type *SrcTy = V->getType();
1891 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1892 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
1893 "Cannot truncate or noop with non-integer arguments!");
1894 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
1895 "getTruncateOrNoop cannot extend!");
1896 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
1897 return V; // No conversion
1898 return getTruncateExpr(V, Ty);
1899}
1900
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001901/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1902/// the specified instruction and replaces any references to the symbolic value
1903/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001904void ScalarEvolution::
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001905ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1906 const SCEVHandle &NewVal) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001907 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
1908 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001909 if (SI == Scalars.end()) return;
1910
1911 SCEVHandle NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001912 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001913 if (NV == SI->second) return; // No change.
1914
1915 SI->second = NV; // Update the scalars map!
1916
1917 // Any instruction values that use this instruction might also need to be
1918 // updated!
1919 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1920 UI != E; ++UI)
1921 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1922}
1923
1924/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1925/// a loop header, making it a potential recurrence, or it doesn't.
1926///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001927SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001928 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001929 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001930 if (L->getHeader() == PN->getParent()) {
1931 // If it lives in the loop header, it has two incoming values, one
1932 // from outside the loop, and one from inside.
1933 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1934 unsigned BackEdge = IncomingEdge^1;
1935
1936 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001937 SCEVHandle SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001938 assert(Scalars.find(PN) == Scalars.end() &&
1939 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00001940 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001941
1942 // Using this symbolic name for the PHI, analyze the value coming around
1943 // the back-edge.
1944 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1945
1946 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1947 // has a special value for the first iteration of the loop.
1948
1949 // If the value coming around the backedge is an add with the symbolic
1950 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00001951 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001952 // If there is a single occurrence of the symbolic value, replace it
1953 // with a recurrence.
1954 unsigned FoundIndex = Add->getNumOperands();
1955 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1956 if (Add->getOperand(i) == SymbolicName)
1957 if (FoundIndex == e) {
1958 FoundIndex = i;
1959 break;
1960 }
1961
1962 if (FoundIndex != Add->getNumOperands()) {
1963 // Create an add with everything but the specified operand.
1964 std::vector<SCEVHandle> Ops;
1965 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1966 if (i != FoundIndex)
1967 Ops.push_back(Add->getOperand(i));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001968 SCEVHandle Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001969
1970 // This is not a valid addrec if the step amount is varying each
1971 // loop iteration, but is not itself an addrec in this loop.
1972 if (Accum->isLoopInvariant(L) ||
1973 (isa<SCEVAddRecExpr>(Accum) &&
1974 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1975 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001976 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001977
1978 // Okay, for the entire analysis of this edge we assumed the PHI
1979 // to be symbolic. We now need to go back and update all of the
1980 // entries for the scalars that use the PHI (except for the PHI
1981 // itself) to use the new analyzed value instead of the "symbolic"
1982 // value.
1983 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1984 return PHISCEV;
1985 }
1986 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00001987 } else if (const SCEVAddRecExpr *AddRec =
1988 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001989 // Otherwise, this could be a loop like this:
1990 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1991 // In this case, j = {1,+,1} and BEValue is j.
1992 // Because the other in-value of i (0) fits the evolution of BEValue
1993 // i really is an addrec evolution.
1994 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1995 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1996
1997 // If StartVal = j.start - j.stride, we can use StartVal as the
1998 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001999 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00002000 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002001 SCEVHandle PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002002 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002003
2004 // Okay, for the entire analysis of this edge we assumed the PHI
2005 // to be symbolic. We now need to go back and update all of the
2006 // entries for the scalars that use the PHI (except for the PHI
2007 // itself) to use the new analyzed value instead of the "symbolic"
2008 // value.
2009 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2010 return PHISCEV;
2011 }
2012 }
2013 }
2014
2015 return SymbolicName;
2016 }
2017
2018 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002019 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002020}
2021
Dan Gohman509cf4d2009-05-08 20:26:55 +00002022/// createNodeForGEP - Expand GEP instructions into add and multiply
2023/// operations. This allows them to be analyzed by regular SCEV code.
2024///
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002025SCEVHandle ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman509cf4d2009-05-08 20:26:55 +00002026
2027 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002028 Value *Base = GEP->getOperand(0);
Dan Gohmand586a4f2009-05-09 00:14:52 +00002029 // Don't attempt to analyze GEPs over unsized objects.
2030 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2031 return getUnknown(GEP);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002032 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002033 gep_type_iterator GTI = gep_type_begin(GEP);
2034 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2035 E = GEP->op_end();
Dan Gohman509cf4d2009-05-08 20:26:55 +00002036 I != E; ++I) {
2037 Value *Index = *I;
2038 // Compute the (potentially symbolic) offset in bytes for this index.
2039 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2040 // For a struct, add the member offset.
2041 const StructLayout &SL = *TD->getStructLayout(STy);
2042 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2043 uint64_t Offset = SL.getElementOffset(FieldNo);
2044 TotalOffset = getAddExpr(TotalOffset,
2045 getIntegerSCEV(Offset, IntPtrTy));
2046 } else {
2047 // For an array, add the element offset, explicitly scaled.
2048 SCEVHandle LocalOffset = getSCEV(Index);
2049 if (!isa<PointerType>(LocalOffset->getType()))
2050 // Getelementptr indicies are signed.
2051 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2052 IntPtrTy);
2053 LocalOffset =
2054 getMulExpr(LocalOffset,
Duncan Sandsec4f97d2009-05-09 07:06:46 +00002055 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman509cf4d2009-05-08 20:26:55 +00002056 IntPtrTy));
2057 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2058 }
2059 }
2060 return getAddExpr(getSCEV(Base), TotalOffset);
2061}
2062
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002063/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2064/// guaranteed to end in (at every loop iteration). It is, at the same time,
2065/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2066/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002067static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002068 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00002069 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002070
Dan Gohmanc76b5452009-05-04 22:02:23 +00002071 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002072 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
2073 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002074
Dan Gohmanc76b5452009-05-04 22:02:23 +00002075 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002076 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2077 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
Dan Gohmanbfd51da2009-05-12 01:23:18 +00002078 SE.getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002079 }
2080
Dan Gohmanc76b5452009-05-04 22:02:23 +00002081 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002082 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
2083 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
Dan Gohmanbfd51da2009-05-12 01:23:18 +00002084 SE.getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002085 }
2086
Dan Gohmanc76b5452009-05-04 22:02:23 +00002087 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002088 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002089 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002090 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002091 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002092 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002093 }
2094
Dan Gohmanc76b5452009-05-04 22:02:23 +00002095 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002096 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002097 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
2098 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002099 for (unsigned i = 1, e = M->getNumOperands();
2100 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002101 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002102 BitWidth);
2103 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002104 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002105
Dan Gohmanc76b5452009-05-04 22:02:23 +00002106 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002107 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002108 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002109 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002110 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002111 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002112 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002113
Dan Gohmanc76b5452009-05-04 22:02:23 +00002114 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00002115 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002116 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00002117 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002118 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00002119 return MinOpRes;
2120 }
2121
Dan Gohmanc76b5452009-05-04 22:02:23 +00002122 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002123 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002124 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002125 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002126 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002127 return MinOpRes;
2128 }
2129
Nick Lewycky35b56022009-01-13 09:18:58 +00002130 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002131 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002132}
2133
2134/// createSCEV - We know that there is no SCEV for the specified value.
2135/// Analyze the expression.
2136///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002137SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002138 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002139 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002140
Dan Gohman3996f472008-06-22 19:56:46 +00002141 unsigned Opcode = Instruction::UserOp1;
2142 if (Instruction *I = dyn_cast<Instruction>(V))
2143 Opcode = I->getOpcode();
2144 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2145 Opcode = CE->getOpcode();
2146 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002147 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002148
Dan Gohman3996f472008-06-22 19:56:46 +00002149 User *U = cast<User>(V);
2150 switch (Opcode) {
2151 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002152 return getAddExpr(getSCEV(U->getOperand(0)),
2153 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002154 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002155 return getMulExpr(getSCEV(U->getOperand(0)),
2156 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002157 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002158 return getUDivExpr(getSCEV(U->getOperand(0)),
2159 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002160 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002161 return getMinusSCEV(getSCEV(U->getOperand(0)),
2162 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002163 case Instruction::And:
2164 // For an expression like x&255 that merely masks off the high bits,
2165 // use zext(trunc(x)) as the SCEV expression.
2166 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002167 if (CI->isNullValue())
2168 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00002169 if (CI->isAllOnesValue())
2170 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002171 const APInt &A = CI->getValue();
2172 unsigned Ones = A.countTrailingOnes();
2173 if (APIntOps::isMask(Ones, A))
2174 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002175 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
2176 IntegerType::get(Ones)),
2177 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00002178 }
2179 break;
Dan Gohman3996f472008-06-22 19:56:46 +00002180 case Instruction::Or:
2181 // If the RHS of the Or is a constant, we may have something like:
2182 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2183 // optimizations will transparently handle this case.
2184 //
2185 // In order for this transformation to be safe, the LHS must be of the
2186 // form X*(2^n) and the Or constant must be less than 2^n.
2187 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2188 SCEVHandle LHS = getSCEV(U->getOperand(0));
2189 const APInt &CIVal = CI->getValue();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002190 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman3996f472008-06-22 19:56:46 +00002191 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002192 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002193 }
Dan Gohman3996f472008-06-22 19:56:46 +00002194 break;
2195 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00002196 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00002197 // If the RHS of the xor is a signbit, then this is just an add.
2198 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00002199 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002200 return getAddExpr(getSCEV(U->getOperand(0)),
2201 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002202
2203 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmanc897f752009-05-18 16:17:44 +00002204 if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002205 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohmanfc78cff2009-05-18 16:29:04 +00002206
2207 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2208 // This is a variant of the check for xor with -1, and it handles
2209 // the case where instcombine has trimmed non-demanded bits out
2210 // of an xor with -1.
2211 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2212 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2213 if (BO->getOpcode() == Instruction::And &&
2214 LCI->getValue() == CI->getValue())
2215 if (const SCEVZeroExtendExpr *Z =
2216 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0))))
2217 return getZeroExtendExpr(getNotSCEV(Z->getOperand()),
2218 U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002219 }
2220 break;
2221
2222 case Instruction::Shl:
2223 // Turn shift left of a constant amount into a multiply.
2224 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2225 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2226 Constant *X = ConstantInt::get(
2227 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002228 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00002229 }
2230 break;
2231
Nick Lewycky7fd27892008-07-07 06:15:49 +00002232 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00002233 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00002234 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2235 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2236 Constant *X = ConstantInt::get(
2237 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002238 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002239 }
2240 break;
2241
Dan Gohman53bf64a2009-04-21 02:26:00 +00002242 case Instruction::AShr:
2243 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2244 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2245 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2246 if (L->getOpcode() == Instruction::Shl &&
2247 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002248 unsigned BitWidth = getTypeSizeInBits(U->getType());
2249 uint64_t Amt = BitWidth - CI->getZExtValue();
2250 if (Amt == BitWidth)
2251 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2252 if (Amt > BitWidth)
2253 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00002254 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002255 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00002256 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00002257 U->getType());
2258 }
2259 break;
2260
Dan Gohman3996f472008-06-22 19:56:46 +00002261 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002262 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002263
2264 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002265 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002266
2267 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002268 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002269
2270 case Instruction::BitCast:
2271 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002272 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002273 return getSCEV(U->getOperand(0));
2274 break;
2275
Dan Gohman01c2ee72009-04-16 03:18:22 +00002276 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002277 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002278 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002279 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002280
2281 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002282 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002283 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2284 U->getType());
2285
Dan Gohman509cf4d2009-05-08 20:26:55 +00002286 case Instruction::GetElementPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002287 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002288 return createNodeForGEP(U);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002289
Dan Gohman3996f472008-06-22 19:56:46 +00002290 case Instruction::PHI:
2291 return createNodeForPHI(cast<PHINode>(U));
2292
2293 case Instruction::Select:
2294 // This could be a smax or umax that was lowered earlier.
2295 // Try to recover it.
2296 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2297 Value *LHS = ICI->getOperand(0);
2298 Value *RHS = ICI->getOperand(1);
2299 switch (ICI->getPredicate()) {
2300 case ICmpInst::ICMP_SLT:
2301 case ICmpInst::ICMP_SLE:
2302 std::swap(LHS, RHS);
2303 // fall through
2304 case ICmpInst::ICMP_SGT:
2305 case ICmpInst::ICMP_SGE:
2306 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002307 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002308 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00002309 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002310 return getNotSCEV(getSMaxExpr(
2311 getNotSCEV(getSCEV(LHS)),
2312 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002313 break;
2314 case ICmpInst::ICMP_ULT:
2315 case ICmpInst::ICMP_ULE:
2316 std::swap(LHS, RHS);
2317 // fall through
2318 case ICmpInst::ICMP_UGT:
2319 case ICmpInst::ICMP_UGE:
2320 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002321 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002322 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2323 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002324 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2325 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002326 break;
2327 default:
2328 break;
2329 }
2330 }
2331
2332 default: // We cannot analyze this expression.
2333 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002334 }
2335
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002336 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002337}
2338
2339
2340
2341//===----------------------------------------------------------------------===//
2342// Iteration Count Computation Code
2343//
2344
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002345/// getBackedgeTakenCount - If the specified loop has a predictable
2346/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2347/// object. The backedge-taken count is the number of times the loop header
2348/// will be branched to from within the loop. This is one less than the
2349/// trip count of the loop, since it doesn't count the first iteration,
2350/// when the header is branched to from outside the loop.
2351///
2352/// Note that it is not valid to call this method on a loop without a
2353/// loop-invariant backedge-taken count (see
2354/// hasLoopInvariantBackedgeTakenCount).
2355///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002356SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002357 return getBackedgeTakenInfo(L).Exact;
2358}
2359
2360/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2361/// return the least SCEV value that is known never to be less than the
2362/// actual backedge taken count.
2363SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2364 return getBackedgeTakenInfo(L).Max;
2365}
2366
2367const ScalarEvolution::BackedgeTakenInfo &
2368ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002369 // Initially insert a CouldNotCompute for this loop. If the insertion
2370 // succeeds, procede to actually compute a backedge-taken count and
2371 // update the value. The temporary CouldNotCompute value tells SCEV
2372 // code elsewhere that it shouldn't attempt to request a new
2373 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002374 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002375 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2376 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002377 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2378 if (ItCount.Exact != UnknownValue) {
2379 assert(ItCount.Exact->isLoopInvariant(L) &&
2380 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002381 "Computed trip count isn't loop invariant for loop!");
2382 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002383
Dan Gohmana9dba962009-04-27 20:16:15 +00002384 // Update the value in the map.
2385 Pair.first->second = ItCount;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002386 } else if (isa<PHINode>(L->getHeader()->begin())) {
2387 // Only count loops that have phi nodes as not being computable.
2388 ++NumTripCountsNotComputed;
2389 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002390
2391 // Now that we know more about the trip count for this loop, forget any
2392 // existing SCEV values for PHI nodes in this loop since they are only
2393 // conservative estimates made without the benefit
2394 // of trip count information.
2395 if (ItCount.hasAnyInfo())
Dan Gohman94623022009-05-02 17:43:35 +00002396 forgetLoopPHIs(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002397 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002398 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002399}
2400
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002401/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002402/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002403/// ScalarEvolution's ability to compute a trip count, or if the loop
2404/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002405void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002406 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002407 forgetLoopPHIs(L);
2408}
2409
2410/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2411/// PHI nodes in the given loop. This is used when the trip count of
2412/// the loop may have changed.
2413void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002414 BasicBlock *Header = L->getHeader();
2415
Dan Gohman9fd4a002009-05-12 01:27:58 +00002416 // Push all Loop-header PHIs onto the Worklist stack, except those
2417 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2418 // a PHI either means that it has an unrecognized structure, or it's
2419 // a PHI that's in the progress of being computed by createNodeForPHI.
2420 // In the former case, additional loop trip count information isn't
2421 // going to change anything. In the later case, createNodeForPHI will
2422 // perform the necessary updates on its own when it gets to that point.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002423 SmallVector<Instruction *, 16> Worklist;
2424 for (BasicBlock::iterator I = Header->begin();
Dan Gohman9fd4a002009-05-12 01:27:58 +00002425 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2426 std::map<SCEVCallbackVH, SCEVHandle>::iterator It = Scalars.find((Value*)I);
2427 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2428 Worklist.push_back(PN);
2429 }
Dan Gohmanbff6b582009-05-04 22:30:44 +00002430
2431 while (!Worklist.empty()) {
2432 Instruction *I = Worklist.pop_back_val();
2433 if (Scalars.erase(I))
2434 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2435 UI != UE; ++UI)
2436 Worklist.push_back(cast<Instruction>(UI));
2437 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002438}
2439
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002440/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2441/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002442ScalarEvolution::BackedgeTakenInfo
2443ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002444 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00002445 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002446 L->getExitBlocks(ExitBlocks);
2447 if (ExitBlocks.size() != 1) return UnknownValue;
2448
2449 // Okay, there is one exit block. Try to find the condition that causes the
2450 // loop to be exited.
2451 BasicBlock *ExitBlock = ExitBlocks[0];
2452
2453 BasicBlock *ExitingBlock = 0;
2454 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2455 PI != E; ++PI)
2456 if (L->contains(*PI)) {
2457 if (ExitingBlock == 0)
2458 ExitingBlock = *PI;
2459 else
2460 return UnknownValue; // More than one block exiting!
2461 }
2462 assert(ExitingBlock && "No exits from loop, something is broken!");
2463
2464 // Okay, we've computed the exiting block. See what condition causes us to
2465 // exit.
2466 //
2467 // FIXME: we should be able to handle switch instructions (with a single exit)
2468 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2469 if (ExitBr == 0) return UnknownValue;
2470 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2471
2472 // At this point, we know we have a conditional branch that determines whether
2473 // the loop is exited. However, we don't know if the branch is executed each
2474 // time through the loop. If not, then the execution count of the branch will
2475 // not be equal to the trip count of the loop.
2476 //
2477 // Currently we check for this by checking to see if the Exit branch goes to
2478 // the loop header. If so, we know it will always execute the same number of
2479 // times as the loop. We also handle the case where the exit block *is* the
2480 // loop header. This is common for un-rotated loops. More extensive analysis
2481 // could be done to handle more cases here.
2482 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2483 ExitBr->getSuccessor(1) != L->getHeader() &&
2484 ExitBr->getParent() != L->getHeader())
2485 return UnknownValue;
2486
2487 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2488
Eli Friedman459d7292009-05-09 12:32:42 +00002489 // If it's not an integer or pointer comparison then compute it the hard way.
2490 if (ExitCond == 0)
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002491 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002492 ExitBr->getSuccessor(0) == ExitBlock);
2493
2494 // If the condition was exit on true, convert the condition to exit on false
2495 ICmpInst::Predicate Cond;
2496 if (ExitBr->getSuccessor(1) == ExitBlock)
2497 Cond = ExitCond->getPredicate();
2498 else
2499 Cond = ExitCond->getInversePredicate();
2500
2501 // Handle common loops like: for (X = "string"; *X; ++X)
2502 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2503 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2504 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002505 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002506 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2507 }
2508
2509 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2510 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2511
2512 // Try to evaluate any dependencies out of the loop.
2513 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2514 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2515 Tmp = getSCEVAtScope(RHS, L);
2516 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2517
2518 // At this point, we would like to compute how many iterations of the
2519 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002520 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2521 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002522 std::swap(LHS, RHS);
2523 Cond = ICmpInst::getSwappedPredicate(Cond);
2524 }
2525
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002526 // If we have a comparison of a chrec against a constant, try to use value
2527 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002528 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2529 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002530 if (AddRec->getLoop() == L) {
Eli Friedman459d7292009-05-09 12:32:42 +00002531 // Form the constant range.
2532 ConstantRange CompRange(
2533 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002534
Eli Friedman459d7292009-05-09 12:32:42 +00002535 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
2536 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002537 }
2538
2539 switch (Cond) {
2540 case ICmpInst::ICMP_NE: { // while (X != Y)
2541 // Convert to: while (X-Y != 0)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002542 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002543 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2544 break;
2545 }
2546 case ICmpInst::ICMP_EQ: {
2547 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002548 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002549 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2550 break;
2551 }
2552 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002553 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2554 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002555 break;
2556 }
2557 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002558 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2559 getNotSCEV(RHS), L, true);
2560 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002561 break;
2562 }
2563 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002564 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2565 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002566 break;
2567 }
2568 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002569 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2570 getNotSCEV(RHS), L, false);
2571 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002572 break;
2573 }
2574 default:
2575#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002576 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002577 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002578 errs() << "[unsigned] ";
2579 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002580 << Instruction::getOpcodeName(Instruction::ICmp)
2581 << " " << *RHS << "\n";
2582#endif
2583 break;
2584 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002585 return
2586 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2587 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002588}
2589
2590static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002591EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2592 ScalarEvolution &SE) {
2593 SCEVHandle InVal = SE.getConstant(C);
2594 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002595 assert(isa<SCEVConstant>(Val) &&
2596 "Evaluation of SCEV at constant didn't fold correctly?");
2597 return cast<SCEVConstant>(Val)->getValue();
2598}
2599
2600/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2601/// and a GEP expression (missing the pointer index) indexing into it, return
2602/// the addressed element of the initializer or null if the index expression is
2603/// invalid.
2604static Constant *
2605GetAddressedElementFromGlobal(GlobalVariable *GV,
2606 const std::vector<ConstantInt*> &Indices) {
2607 Constant *Init = GV->getInitializer();
2608 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2609 uint64_t Idx = Indices[i]->getZExtValue();
2610 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2611 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2612 Init = cast<Constant>(CS->getOperand(Idx));
2613 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2614 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2615 Init = cast<Constant>(CA->getOperand(Idx));
2616 } else if (isa<ConstantAggregateZero>(Init)) {
2617 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2618 assert(Idx < STy->getNumElements() && "Bad struct index!");
2619 Init = Constant::getNullValue(STy->getElementType(Idx));
2620 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2621 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2622 Init = Constant::getNullValue(ATy->getElementType());
2623 } else {
2624 assert(0 && "Unknown constant aggregate type!");
2625 }
2626 return 0;
2627 } else {
2628 return 0; // Unknown initializer type
2629 }
2630 }
2631 return Init;
2632}
2633
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002634/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2635/// 'icmp op load X, cst', try to see if we can compute the backedge
2636/// execution count.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002637SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002638ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2639 const Loop *L,
2640 ICmpInst::Predicate predicate) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002641 if (LI->isVolatile()) return UnknownValue;
2642
2643 // Check to see if the loaded pointer is a getelementptr of a global.
2644 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2645 if (!GEP) return UnknownValue;
2646
2647 // Make sure that it is really a constant global we are gepping, with an
2648 // initializer, and make sure the first IDX is really 0.
2649 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2650 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2651 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2652 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2653 return UnknownValue;
2654
2655 // Okay, we allow one non-constant index into the GEP instruction.
2656 Value *VarIdx = 0;
2657 std::vector<ConstantInt*> Indexes;
2658 unsigned VarIdxNum = 0;
2659 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2660 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2661 Indexes.push_back(CI);
2662 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2663 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2664 VarIdx = GEP->getOperand(i);
2665 VarIdxNum = i-2;
2666 Indexes.push_back(0);
2667 }
2668
2669 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2670 // Check to see if X is a loop variant variable value now.
2671 SCEVHandle Idx = getSCEV(VarIdx);
2672 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2673 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2674
2675 // We can only recognize very limited forms of loop index expressions, in
2676 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002677 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002678 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2679 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2680 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2681 return UnknownValue;
2682
2683 unsigned MaxSteps = MaxBruteForceIterations;
2684 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2685 ConstantInt *ItCst =
2686 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002687 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002688
2689 // Form the GEP offset.
2690 Indexes[VarIdxNum] = Val;
2691
2692 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2693 if (Result == 0) break; // Cannot compute!
2694
2695 // Evaluate the condition for this iteration.
2696 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2697 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2698 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2699#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002700 errs() << "\n***\n*** Computed loop count " << *ItCst
2701 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2702 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002703#endif
2704 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002705 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002706 }
2707 }
2708 return UnknownValue;
2709}
2710
2711
2712/// CanConstantFold - Return true if we can constant fold an instruction of the
2713/// specified type, assuming that all operands were constants.
2714static bool CanConstantFold(const Instruction *I) {
2715 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2716 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2717 return true;
2718
2719 if (const CallInst *CI = dyn_cast<CallInst>(I))
2720 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002721 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002722 return false;
2723}
2724
2725/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2726/// in the loop that V is derived from. We allow arbitrary operations along the
2727/// way, but the operands of an operation must either be constants or a value
2728/// derived from a constant PHI. If this expression does not fit with these
2729/// constraints, return null.
2730static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2731 // If this is not an instruction, or if this is an instruction outside of the
2732 // loop, it can't be derived from a loop PHI.
2733 Instruction *I = dyn_cast<Instruction>(V);
2734 if (I == 0 || !L->contains(I->getParent())) return 0;
2735
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002736 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002737 if (L->getHeader() == I->getParent())
2738 return PN;
2739 else
2740 // We don't currently keep track of the control flow needed to evaluate
2741 // PHIs, so we cannot handle PHIs inside of loops.
2742 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002743 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002744
2745 // If we won't be able to constant fold this expression even if the operands
2746 // are constants, return early.
2747 if (!CanConstantFold(I)) return 0;
2748
2749 // Otherwise, we can evaluate this instruction if all of its operands are
2750 // constant or derived from a PHI node themselves.
2751 PHINode *PHI = 0;
2752 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2753 if (!(isa<Constant>(I->getOperand(Op)) ||
2754 isa<GlobalValue>(I->getOperand(Op)))) {
2755 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2756 if (P == 0) return 0; // Not evolving from PHI
2757 if (PHI == 0)
2758 PHI = P;
2759 else if (PHI != P)
2760 return 0; // Evolving from multiple different PHIs.
2761 }
2762
2763 // This is a expression evolving from a constant PHI!
2764 return PHI;
2765}
2766
2767/// EvaluateExpression - Given an expression that passes the
2768/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2769/// in the loop has the value PHIVal. If we can't fold this expression for some
2770/// reason, return null.
2771static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2772 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002773 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002774 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002775 Instruction *I = cast<Instruction>(V);
2776
2777 std::vector<Constant*> Operands;
2778 Operands.resize(I->getNumOperands());
2779
2780 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2781 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2782 if (Operands[i] == 0) return 0;
2783 }
2784
Chris Lattnerd6e56912007-12-10 22:53:04 +00002785 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2786 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2787 &Operands[0], Operands.size());
2788 else
2789 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2790 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002791}
2792
2793/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2794/// in the header of its containing loop, we know the loop executes a
2795/// constant number of times, and the PHI node is just a recurrence
2796/// involving constants, fold it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002797Constant *ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002798getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002799 std::map<PHINode*, Constant*>::iterator I =
2800 ConstantEvolutionLoopExitValue.find(PN);
2801 if (I != ConstantEvolutionLoopExitValue.end())
2802 return I->second;
2803
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002804 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002805 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2806
2807 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2808
2809 // Since the loop is canonicalized, the PHI node must have two entries. One
2810 // entry must be a constant (coming in from outside of the loop), and the
2811 // second must be derived from the same PHI.
2812 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2813 Constant *StartCST =
2814 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2815 if (StartCST == 0)
2816 return RetVal = 0; // Must be a constant.
2817
2818 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2819 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2820 if (PN2 != PN)
2821 return RetVal = 0; // Not derived from same PHI.
2822
2823 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002824 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002825 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2826
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002827 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002828 unsigned IterationNum = 0;
2829 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2830 if (IterationNum == NumIterations)
2831 return RetVal = PHIVal; // Got exit value!
2832
2833 // Compute the value of the PHI node for the next iteration.
2834 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2835 if (NextPHI == PHIVal)
2836 return RetVal = NextPHI; // Stopped evolving!
2837 if (NextPHI == 0)
2838 return 0; // Couldn't evaluate!
2839 PHIVal = NextPHI;
2840 }
2841}
2842
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002843/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002844/// constant number of times (the condition evolves only from constants),
2845/// try to evaluate a few iterations of the loop until we get the exit
2846/// condition gets a value of ExitWhen (true or false). If we cannot
2847/// evaluate the trip count of the loop, return UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002848SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002849ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002850 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2851 if (PN == 0) return UnknownValue;
2852
2853 // Since the loop is canonicalized, the PHI node must have two entries. One
2854 // entry must be a constant (coming in from outside of the loop), and the
2855 // second must be derived from the same PHI.
2856 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2857 Constant *StartCST =
2858 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2859 if (StartCST == 0) return UnknownValue; // Must be a constant.
2860
2861 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2862 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2863 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2864
2865 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2866 // the loop symbolically to determine when the condition gets a value of
2867 // "ExitWhen".
2868 unsigned IterationNum = 0;
2869 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2870 for (Constant *PHIVal = StartCST;
2871 IterationNum != MaxIterations; ++IterationNum) {
2872 ConstantInt *CondVal =
2873 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2874
2875 // Couldn't symbolically evaluate.
2876 if (!CondVal) return UnknownValue;
2877
2878 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2879 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2880 ++NumBruteForceTripCountsComputed;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002881 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002882 }
2883
2884 // Compute the value of the PHI node for the next iteration.
2885 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2886 if (NextPHI == 0 || NextPHI == PHIVal)
2887 return UnknownValue; // Couldn't evaluate or not making progress...
2888 PHIVal = NextPHI;
2889 }
2890
2891 // Too many iterations were needed to evaluate.
2892 return UnknownValue;
2893}
2894
Dan Gohmandd40e9a2009-05-08 20:38:54 +00002895/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2896/// at the specified scope in the program. The L value specifies a loop
2897/// nest to evaluate the expression at, where null is the top-level or a
2898/// specified loop is immediately inside of the loop.
2899///
2900/// This method can be used to compute the exit value for a variable defined
2901/// in a loop by querying what the value will hold in the parent loop.
2902///
2903/// If this value is not computable at this scope, a SCEVCouldNotCompute
2904/// object is returned.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002905SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002906 // FIXME: this should be turned into a virtual method on SCEV!
2907
2908 if (isa<SCEVConstant>(V)) return V;
2909
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002910 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002911 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002912 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002913 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002914 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002915 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2916 if (PHINode *PN = dyn_cast<PHINode>(I))
2917 if (PN->getParent() == LI->getHeader()) {
2918 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002919 // to see if the loop that contains it has a known backedge-taken
2920 // count. If so, we may be able to force computation of the exit
2921 // value.
2922 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002923 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002924 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002925 // Okay, we know how many times the containing loop executes. If
2926 // this is a constant evolving PHI node, get the final value at
2927 // the specified iteration number.
2928 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002929 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002930 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002931 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002932 }
2933 }
2934
2935 // Okay, this is an expression that we cannot symbolically evaluate
2936 // into a SCEV. Check to see if it's possible to symbolically evaluate
2937 // the arguments into constants, and if so, try to constant propagate the
2938 // result. This is particularly useful for computing loop exit values.
2939 if (CanConstantFold(I)) {
Dan Gohmanda0071e2009-05-08 20:47:27 +00002940 // Check to see if we've folded this instruction at this loop before.
2941 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
2942 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
2943 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
2944 if (!Pair.second)
2945 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
2946
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002947 std::vector<Constant*> Operands;
2948 Operands.reserve(I->getNumOperands());
2949 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2950 Value *Op = I->getOperand(i);
2951 if (Constant *C = dyn_cast<Constant>(Op)) {
2952 Operands.push_back(C);
2953 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002954 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00002955 // non-integer and non-pointer, don't even try to analyze them
2956 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00002957 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00002958 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002959
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002960 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002961 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00002962 Constant *C = SC->getValue();
2963 if (C->getType() != Op->getType())
2964 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2965 Op->getType(),
2966 false),
2967 C, Op->getType());
2968 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002969 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00002970 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
2971 if (C->getType() != Op->getType())
2972 C =
2973 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2974 Op->getType(),
2975 false),
2976 C, Op->getType());
2977 Operands.push_back(C);
2978 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002979 return V;
2980 } else {
2981 return V;
2982 }
2983 }
2984 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002985
2986 Constant *C;
2987 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2988 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2989 &Operands[0], Operands.size());
2990 else
2991 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2992 &Operands[0], Operands.size());
Dan Gohmanda0071e2009-05-08 20:47:27 +00002993 Pair.first->second = C;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002994 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002995 }
2996 }
2997
2998 // This is some other type of SCEVUnknown, just return it.
2999 return V;
3000 }
3001
Dan Gohmanc76b5452009-05-04 22:02:23 +00003002 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003003 // Avoid performing the look-up in the common case where the specified
3004 // expression has no loop-variant portions.
3005 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
3006 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3007 if (OpAtScope != Comm->getOperand(i)) {
3008 if (OpAtScope == UnknownValue) return UnknownValue;
3009 // Okay, at least one of these operands is loop variant but might be
3010 // foldable. Build a new instance of the folded commutative expression.
3011 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
3012 NewOps.push_back(OpAtScope);
3013
3014 for (++i; i != e; ++i) {
3015 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
3016 if (OpAtScope == UnknownValue) return UnknownValue;
3017 NewOps.push_back(OpAtScope);
3018 }
3019 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003020 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003021 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003022 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003023 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003024 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003025 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003026 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003027 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003028 }
3029 }
3030 // If we got here, all operands are loop invariant.
3031 return Comm;
3032 }
3033
Dan Gohmanc76b5452009-05-04 22:02:23 +00003034 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003035 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003036 if (LHS == UnknownValue) return LHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00003037 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003038 if (RHS == UnknownValue) return RHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00003039 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3040 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003041 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003042 }
3043
3044 // If this is a loop recurrence for a loop that does not contain L, then we
3045 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003046 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003047 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3048 // To evaluate this recurrence, we need to know how many times the AddRec
3049 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003050 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
3051 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003052
Eli Friedman7489ec92008-08-04 23:49:06 +00003053 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003054 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003055 }
3056 return UnknownValue;
3057 }
3058
Dan Gohmanc76b5452009-05-04 22:02:23 +00003059 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003060 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
3061 if (Op == UnknownValue) return Op;
3062 if (Op == Cast->getOperand())
3063 return Cast; // must be loop invariant
3064 return getZeroExtendExpr(Op, Cast->getType());
3065 }
3066
Dan Gohmanc76b5452009-05-04 22:02:23 +00003067 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003068 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
3069 if (Op == UnknownValue) return Op;
3070 if (Op == Cast->getOperand())
3071 return Cast; // must be loop invariant
3072 return getSignExtendExpr(Op, Cast->getType());
3073 }
3074
Dan Gohmanc76b5452009-05-04 22:02:23 +00003075 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00003076 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
3077 if (Op == UnknownValue) return Op;
3078 if (Op == Cast->getOperand())
3079 return Cast; // must be loop invariant
3080 return getTruncateExpr(Op, Cast->getType());
3081 }
3082
3083 assert(0 && "Unknown SCEV type!");
Daniel Dunbara95d96c2009-05-18 16:43:04 +00003084 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003085}
3086
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003087/// getSCEVAtScope - This is a convenience function which does
3088/// getSCEVAtScope(getSCEV(V), L).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003089SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
3090 return getSCEVAtScope(getSCEV(V), L);
3091}
3092
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003093/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3094/// following equation:
3095///
3096/// A * X = B (mod N)
3097///
3098/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3099/// A and B isn't important.
3100///
3101/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
3102static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
3103 ScalarEvolution &SE) {
3104 uint32_t BW = A.getBitWidth();
3105 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3106 assert(A != 0 && "A must be non-zero.");
3107
3108 // 1. D = gcd(A, N)
3109 //
3110 // The gcd of A and N may have only one prime factor: 2. The number of
3111 // trailing zeros in A is its multiplicity
3112 uint32_t Mult2 = A.countTrailingZeros();
3113 // D = 2^Mult2
3114
3115 // 2. Check if B is divisible by D.
3116 //
3117 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3118 // is not less than multiplicity of this prime factor for D.
3119 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00003120 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003121
3122 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3123 // modulo (N / D).
3124 //
3125 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3126 // bit width during computations.
3127 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3128 APInt Mod(BW + 1, 0);
3129 Mod.set(BW - Mult2); // Mod = N / D
3130 APInt I = AD.multiplicativeInverse(Mod);
3131
3132 // 4. Compute the minimum unsigned root of the equation:
3133 // I * (B / D) mod (N / D)
3134 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3135
3136 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3137 // bits.
3138 return SE.getConstant(Result.trunc(BW));
3139}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003140
3141/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3142/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3143/// might be the same) or two SCEVCouldNotCompute objects.
3144///
3145static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00003146SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003147 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00003148 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3149 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3150 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003151
3152 // We currently can only solve this if the coefficients are constants.
3153 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003154 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003155 return std::make_pair(CNC, CNC);
3156 }
3157
3158 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3159 const APInt &L = LC->getValue()->getValue();
3160 const APInt &M = MC->getValue()->getValue();
3161 const APInt &N = NC->getValue()->getValue();
3162 APInt Two(BitWidth, 2);
3163 APInt Four(BitWidth, 4);
3164
3165 {
3166 using namespace APIntOps;
3167 const APInt& C = L;
3168 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3169 // The B coefficient is M-N/2
3170 APInt B(M);
3171 B -= sdiv(N,Two);
3172
3173 // The A coefficient is N/2
3174 APInt A(N.sdiv(Two));
3175
3176 // Compute the B^2-4ac term.
3177 APInt SqrtTerm(B);
3178 SqrtTerm *= B;
3179 SqrtTerm -= Four * (A * C);
3180
3181 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3182 // integer value or else APInt::sqrt() will assert.
3183 APInt SqrtVal(SqrtTerm.sqrt());
3184
3185 // Compute the two solutions for the quadratic formula.
3186 // The divisions must be performed as signed divisions.
3187 APInt NegB(-B);
3188 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00003189 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003190 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00003191 return std::make_pair(CNC, CNC);
3192 }
3193
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003194 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3195 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
3196
Dan Gohman89f85052007-10-22 18:31:58 +00003197 return std::make_pair(SE.getConstant(Solution1),
3198 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003199 } // end APIntOps namespace
3200}
3201
3202/// HowFarToZero - Return the number of times a backedge comparing the specified
3203/// value to zero will execute. If not computable, return UnknownValue
Dan Gohmanbff6b582009-05-04 22:30:44 +00003204SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003205 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00003206 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003207 // If the value is already zero, the branch will execute zero times.
3208 if (C->getValue()->isZero()) return C;
3209 return UnknownValue; // Otherwise it will loop infinitely.
3210 }
3211
Dan Gohmanbff6b582009-05-04 22:30:44 +00003212 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003213 if (!AddRec || AddRec->getLoop() != L)
3214 return UnknownValue;
3215
3216 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003217 // If this is an affine expression, the execution count of this branch is
3218 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003219 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003220 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003221 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003222 // equivalent to:
3223 //
3224 // Step*N = -Start (mod 2^BW)
3225 //
3226 // where BW is the common bit width of Start and Step.
3227
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003228 // Get the initial value for the loop.
3229 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
3230 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003231
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003232 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003233
Dan Gohmanc76b5452009-05-04 22:02:23 +00003234 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003235 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003236
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003237 // First, handle unitary steps.
3238 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003239 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003240 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3241 return Start; // N = Start (as unsigned)
3242
3243 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003244 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003245 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003246 -StartC->getValue()->getValue(),
3247 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003248 }
3249 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3250 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3251 // the quadratic equation to solve it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003252 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
3253 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003254 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3255 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003256 if (R1) {
3257#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003258 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3259 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003260#endif
3261 // Pick the smallest positive root value.
3262 if (ConstantInt *CB =
3263 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3264 R1->getValue(), R2->getValue()))) {
3265 if (CB->getZExtValue() == false)
3266 std::swap(R1, R2); // R1 is the minimum root now.
3267
3268 // We can only use this value if the chrec ends up with an exact zero
3269 // value at this index. When solving for "X*X != 5", for example, we
3270 // should not accept a root of 2.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003271 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00003272 if (Val->isZero())
3273 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003274 }
3275 }
3276 }
3277
3278 return UnknownValue;
3279}
3280
3281/// HowFarToNonZero - Return the number of times a backedge checking the
3282/// specified value for nonzero will execute. If not computable, return
3283/// UnknownValue
Dan Gohmanbff6b582009-05-04 22:30:44 +00003284SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003285 // Loops that look like: while (X == 0) are very strange indeed. We don't
3286 // handle them yet except for the trivial case. This could be expanded in the
3287 // future as needed.
3288
3289 // If the value is a constant, check to see if it is known to be non-zero
3290 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003291 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00003292 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003293 return getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003294 return UnknownValue; // Otherwise it will loop infinitely.
3295 }
3296
3297 // We could implement others, but I really doubt anyone writes loops like
3298 // this, and if they did, they would already be constant folded.
3299 return UnknownValue;
3300}
3301
Dan Gohmanab157b22009-05-18 15:36:09 +00003302/// getLoopPredecessor - If the given loop's header has exactly one unique
3303/// predecessor outside the loop, return it. Otherwise return null.
3304///
3305BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3306 BasicBlock *Header = L->getHeader();
3307 BasicBlock *Pred = 0;
3308 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3309 PI != E; ++PI)
3310 if (!L->contains(*PI)) {
3311 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3312 Pred = *PI;
3313 }
3314 return Pred;
3315}
3316
Dan Gohman1cddf972008-09-15 22:18:04 +00003317/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3318/// (which may not be an immediate predecessor) which has exactly one
3319/// successor from which BB is reachable, or null if no such block is
3320/// found.
3321///
3322BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003323ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00003324 // If the block has a unique predecessor, then there is no path from the
3325 // predecessor to the block that does not go through the direct edge
3326 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00003327 if (BasicBlock *Pred = BB->getSinglePredecessor())
3328 return Pred;
3329
3330 // A loop's header is defined to be a block that dominates the loop.
Dan Gohmanab157b22009-05-18 15:36:09 +00003331 // If the header has a unique predecessor outside the loop, it must be
3332 // a block that has exactly one successor that can reach the loop.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003333 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanab157b22009-05-18 15:36:09 +00003334 return getLoopPredecessor(L);
Dan Gohman1cddf972008-09-15 22:18:04 +00003335
3336 return 0;
3337}
3338
Dan Gohmancacd2012009-02-12 22:19:27 +00003339/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman1116ea72009-04-30 20:48:53 +00003340/// a conditional between LHS and RHS. This is used to help avoid max
3341/// expressions in loop trip counts.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003342bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman1116ea72009-04-30 20:48:53 +00003343 ICmpInst::Predicate Pred,
Dan Gohmanbff6b582009-05-04 22:30:44 +00003344 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8b938182009-05-18 16:03:58 +00003345 // Interpret a null as meaning no loop, where there is obviously no guard
3346 // (interprocedural conditions notwithstanding).
3347 if (!L) return false;
3348
Dan Gohmanab157b22009-05-18 15:36:09 +00003349 BasicBlock *Predecessor = getLoopPredecessor(L);
3350 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003351
Dan Gohmanab157b22009-05-18 15:36:09 +00003352 // Starting at the loop predecessor, climb up the predecessor chain, as long
3353 // as there are predecessors that can be found that have unique successors
Dan Gohman1cddf972008-09-15 22:18:04 +00003354 // leading to the original header.
Dan Gohmanab157b22009-05-18 15:36:09 +00003355 for (; Predecessor;
3356 PredecessorDest = Predecessor,
3357 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00003358
3359 BranchInst *LoopEntryPredicate =
Dan Gohmanab157b22009-05-18 15:36:09 +00003360 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00003361 if (!LoopEntryPredicate ||
3362 LoopEntryPredicate->isUnconditional())
3363 continue;
3364
3365 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3366 if (!ICI) continue;
3367
3368 // Now that we found a conditional branch that dominates the loop, check to
3369 // see if it is the comparison we are looking for.
3370 Value *PreCondLHS = ICI->getOperand(0);
3371 Value *PreCondRHS = ICI->getOperand(1);
3372 ICmpInst::Predicate Cond;
Dan Gohmanab157b22009-05-18 15:36:09 +00003373 if (LoopEntryPredicate->getSuccessor(0) == PredecessorDest)
Dan Gohmanab678fb2008-08-12 20:17:31 +00003374 Cond = ICI->getPredicate();
3375 else
3376 Cond = ICI->getInversePredicate();
3377
Dan Gohmancacd2012009-02-12 22:19:27 +00003378 if (Cond == Pred)
3379 ; // An exact match.
3380 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3381 ; // The actual condition is beyond sufficient.
3382 else
3383 // Check a few special cases.
3384 switch (Cond) {
3385 case ICmpInst::ICMP_UGT:
3386 if (Pred == ICmpInst::ICMP_ULT) {
3387 std::swap(PreCondLHS, PreCondRHS);
3388 Cond = ICmpInst::ICMP_ULT;
3389 break;
3390 }
3391 continue;
3392 case ICmpInst::ICMP_SGT:
3393 if (Pred == ICmpInst::ICMP_SLT) {
3394 std::swap(PreCondLHS, PreCondRHS);
3395 Cond = ICmpInst::ICMP_SLT;
3396 break;
3397 }
3398 continue;
3399 case ICmpInst::ICMP_NE:
3400 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3401 // so check for this case by checking if the NE is comparing against
3402 // a minimum or maximum constant.
3403 if (!ICmpInst::isTrueWhenEqual(Pred))
3404 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3405 const APInt &A = CI->getValue();
3406 switch (Pred) {
3407 case ICmpInst::ICMP_SLT:
3408 if (A.isMaxSignedValue()) break;
3409 continue;
3410 case ICmpInst::ICMP_SGT:
3411 if (A.isMinSignedValue()) break;
3412 continue;
3413 case ICmpInst::ICMP_ULT:
3414 if (A.isMaxValue()) break;
3415 continue;
3416 case ICmpInst::ICMP_UGT:
3417 if (A.isMinValue()) break;
3418 continue;
3419 default:
3420 continue;
3421 }
3422 Cond = ICmpInst::ICMP_NE;
3423 // NE is symmetric but the original comparison may not be. Swap
3424 // the operands if necessary so that they match below.
3425 if (isa<SCEVConstant>(LHS))
3426 std::swap(PreCondLHS, PreCondRHS);
3427 break;
3428 }
3429 continue;
3430 default:
3431 // We weren't able to reconcile the condition.
3432 continue;
3433 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003434
3435 if (!PreCondLHS->getType()->isInteger()) continue;
3436
3437 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3438 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3439 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003440 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3441 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohmanab678fb2008-08-12 20:17:31 +00003442 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003443 }
3444
Dan Gohmanab678fb2008-08-12 20:17:31 +00003445 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003446}
3447
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003448/// HowManyLessThans - Return the number of times a backedge containing the
3449/// specified less-than comparison will execute. If not computable, return
3450/// UnknownValue.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003451ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Dan Gohmanbff6b582009-05-04 22:30:44 +00003452HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3453 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003454 // Only handle: "ADDREC < LoopInvariant".
3455 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3456
Dan Gohmanbff6b582009-05-04 22:30:44 +00003457 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003458 if (!AddRec || AddRec->getLoop() != L)
3459 return UnknownValue;
3460
3461 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003462 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003463 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3464 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3465 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3466
3467 // TODO: handle non-constant strides.
3468 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3469 if (!CStep || CStep->isZero())
3470 return UnknownValue;
Dan Gohmanf8bc8e82009-05-18 15:22:39 +00003471 if (CStep->isOne()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003472 // With unit stride, the iteration never steps past the limit value.
3473 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3474 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3475 // Test whether a positive iteration iteration can step past the limit
3476 // value and past the maximum value for its type in a single step.
3477 if (isSigned) {
3478 APInt Max = APInt::getSignedMaxValue(BitWidth);
3479 if ((Max - CStep->getValue()->getValue())
3480 .slt(CLimit->getValue()->getValue()))
3481 return UnknownValue;
3482 } else {
3483 APInt Max = APInt::getMaxValue(BitWidth);
3484 if ((Max - CStep->getValue()->getValue())
3485 .ult(CLimit->getValue()->getValue()))
3486 return UnknownValue;
3487 }
3488 } else
3489 // TODO: handle non-constant limit values below.
3490 return UnknownValue;
3491 } else
3492 // TODO: handle negative strides below.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003493 return UnknownValue;
3494
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003495 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3496 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3497 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00003498 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003499
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003500 // First, we get the value of the LHS in the first iteration: n
3501 SCEVHandle Start = AddRec->getOperand(0);
3502
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003503 // Determine the minimum constant start value.
3504 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3505 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3506 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003507
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003508 // If we know that the condition is true in order to enter the loop,
3509 // then we know that it will run exactly (m-n)/s times. Otherwise, we
3510 // only know if will execute (max(m,n)-n)/s times. In both cases, the
3511 // division must round up.
3512 SCEVHandle End = RHS;
3513 if (!isLoopGuardedByCond(L,
3514 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3515 getMinusSCEV(Start, Step), RHS))
3516 End = isSigned ? getSMaxExpr(RHS, Start)
3517 : getUMaxExpr(RHS, Start);
3518
3519 // Determine the maximum constant end value.
3520 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3521 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3522 APInt::getMaxValue(BitWidth));
3523
3524 // Finally, we subtract these two values and divide, rounding up, to get
3525 // the number of times the backedge is executed.
3526 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3527 getAddExpr(Step, NegOne)),
3528 Step);
3529
3530 // The maximum backedge count is similar, except using the minimum start
3531 // value and the maximum end value.
3532 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3533 MinStart),
3534 getAddExpr(Step, NegOne)),
3535 Step);
3536
3537 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003538 }
3539
3540 return UnknownValue;
3541}
3542
3543/// getNumIterationsInRange - Return the number of iterations of this loop that
3544/// produce values in the specified constant range. Another way of looking at
3545/// this is that it returns the first iteration number where the value is not in
3546/// the condition, thus computing the exit count. If the iteration count can't
3547/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00003548SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3549 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003550 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003551 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003552
3553 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003554 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003555 if (!SC->getValue()->isZero()) {
3556 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003557 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3558 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00003559 if (const SCEVAddRecExpr *ShiftedAddRec =
3560 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003561 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003562 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003563 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003564 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003565 }
3566
3567 // The only time we can solve this is when we have all constant indices.
3568 // Otherwise, we cannot determine the overflow conditions.
3569 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3570 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003571 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003572
3573
3574 // Okay at this point we know that all elements of the chrec are constants and
3575 // that the start element is zero.
3576
3577 // First check to see if the range contains zero. If not, the first
3578 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003579 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003580 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003581 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003582
3583 if (isAffine()) {
3584 // If this is an affine expression then we have this situation:
3585 // Solve {0,+,A} in Range === Ax in Range
3586
3587 // We know that zero is in the range. If A is positive then we know that
3588 // the upper value of the range must be the first possible exit value.
3589 // If A is negative then the lower of the range is the last possible loop
3590 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003591 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003592 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3593 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3594
3595 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003596 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003597 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3598
3599 // Evaluate at the exit value. If we really did fall out of the valid
3600 // range, then we computed our trip count, otherwise wrap around or other
3601 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003602 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003603 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003604 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003605
3606 // Ensure that the previous value is in the range. This is a sanity check.
3607 assert(Range.contains(
3608 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003609 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003610 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003611 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003612 } else if (isQuadratic()) {
3613 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3614 // quadratic equation to solve it. To do this, we must frame our problem in
3615 // terms of figuring out when zero is crossed, instead of when
3616 // Range.getUpper() is crossed.
3617 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003618 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3619 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003620
3621 // Next, solve the constructed addrec
3622 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003623 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003624 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3625 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003626 if (R1) {
3627 // Pick the smallest positive root value.
3628 if (ConstantInt *CB =
3629 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3630 R1->getValue(), R2->getValue()))) {
3631 if (CB->getZExtValue() == false)
3632 std::swap(R1, R2); // R1 is the minimum root now.
3633
3634 // Make sure the root is not off by one. The returned iteration should
3635 // not be in the range, but the previous one should be. When solving
3636 // for "X*X < 5", for example, we should not return a root of 2.
3637 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003638 R1->getValue(),
3639 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003640 if (Range.contains(R1Val->getValue())) {
3641 // The next iteration must be out of the range...
3642 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3643
Dan Gohman89f85052007-10-22 18:31:58 +00003644 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003645 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003646 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003647 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003648 }
3649
3650 // If R1 was not in the range, then it is a good return value. Make
3651 // sure that R1-1 WAS in the range though, just in case.
3652 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003653 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003654 if (Range.contains(R1Val->getValue()))
3655 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003656 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003657 }
3658 }
3659 }
3660
Dan Gohman0ad08b02009-04-18 17:58:19 +00003661 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003662}
3663
3664
3665
3666//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00003667// SCEVCallbackVH Class Implementation
3668//===----------------------------------------------------------------------===//
3669
3670void SCEVCallbackVH::deleted() {
3671 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3672 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3673 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003674 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
3675 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003676 SE->Scalars.erase(getValPtr());
3677 // this now dangles!
3678}
3679
3680void SCEVCallbackVH::allUsesReplacedWith(Value *) {
3681 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3682
3683 // Forget all the expressions associated with users of the old value,
3684 // so that future queries will recompute the expressions using the new
3685 // value.
3686 SmallVector<User *, 16> Worklist;
3687 Value *Old = getValPtr();
3688 bool DeleteOld = false;
3689 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3690 UI != UE; ++UI)
3691 Worklist.push_back(*UI);
3692 while (!Worklist.empty()) {
3693 User *U = Worklist.pop_back_val();
3694 // Deleting the Old value will cause this to dangle. Postpone
3695 // that until everything else is done.
3696 if (U == Old) {
3697 DeleteOld = true;
3698 continue;
3699 }
3700 if (PHINode *PN = dyn_cast<PHINode>(U))
3701 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003702 if (Instruction *I = dyn_cast<Instruction>(U))
3703 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003704 if (SE->Scalars.erase(U))
3705 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3706 UI != UE; ++UI)
3707 Worklist.push_back(*UI);
3708 }
3709 if (DeleteOld) {
3710 if (PHINode *PN = dyn_cast<PHINode>(Old))
3711 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00003712 if (Instruction *I = dyn_cast<Instruction>(Old))
3713 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003714 SE->Scalars.erase(Old);
3715 // this now dangles!
3716 }
3717 // this may dangle!
3718}
3719
3720SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
3721 : CallbackVH(V), SE(se) {}
3722
3723//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003724// ScalarEvolution Class Implementation
3725//===----------------------------------------------------------------------===//
3726
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003727ScalarEvolution::ScalarEvolution()
3728 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3729}
3730
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003731bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003732 this->F = &F;
3733 LI = &getAnalysis<LoopInfo>();
3734 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003735 return false;
3736}
3737
3738void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003739 Scalars.clear();
3740 BackedgeTakenCounts.clear();
3741 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanda0071e2009-05-08 20:47:27 +00003742 ValuesAtScopes.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003743}
3744
3745void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3746 AU.setPreservesAll();
3747 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003748}
3749
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003750bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003751 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003752}
3753
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003754static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003755 const Loop *L) {
3756 // Print all inner loops first
3757 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3758 PrintLoopInfo(OS, SE, *I);
3759
Nick Lewyckye5da1912008-01-02 02:49:20 +00003760 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003761
Devang Patel02451fa2007-08-21 00:31:24 +00003762 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003763 L->getExitBlocks(ExitBlocks);
3764 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003765 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003766
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003767 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3768 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003769 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003770 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003771 }
3772
Nick Lewyckye5da1912008-01-02 02:49:20 +00003773 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003774}
3775
Dan Gohman13058cc2009-04-21 00:47:46 +00003776void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003777 // ScalarEvolution's implementaiton of the print method is to print
3778 // out SCEV values of all instructions that are interesting. Doing
3779 // this potentially causes it to create new SCEV objects though,
3780 // which technically conflicts with the const qualifier. This isn't
3781 // observable from outside the class though (the hasSCEV function
3782 // notwithstanding), so casting away the const isn't dangerous.
3783 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003784
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003785 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003786 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00003787 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003788 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003789 OS << " --> ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003790 SCEVHandle SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003791 SV->print(OS);
3792 OS << "\t\t";
3793
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003794 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003795 OS << "Exits: ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003796 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003797 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3798 OS << "<<Unknown>>";
3799 } else {
3800 OS << *ExitValue;
3801 }
3802 }
3803
3804
3805 OS << "\n";
3806 }
3807
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003808 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3809 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3810 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003811}
Dan Gohman13058cc2009-04-21 00:47:46 +00003812
3813void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3814 raw_os_ostream OS(o);
3815 print(OS, M);
3816}