blob: cebf4d704fee25d76cc9a3476f6408c53ca4de64 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
17// can handle. These classes are reference counted, managed by the SCEVHandle
18// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
31//
32// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
36// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
62#define DEBUG_TYPE "scalar-evolution"
63#include "llvm/Analysis/ScalarEvolutionExpressions.h"
64#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
66#include "llvm/GlobalVariable.h"
67#include "llvm/Instructions.h"
68#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng98c073b2009-02-17 00:13:06 +000069#include "llvm/Analysis/Dominators.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070#include "llvm/Analysis/LoopInfo.h"
71#include "llvm/Assembly/Writer.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000072#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000073#include "llvm/Transforms/Scalar.h"
74#include "llvm/Support/CFG.h"
75#include "llvm/Support/CommandLine.h"
76#include "llvm/Support/Compiler.h"
77#include "llvm/Support/ConstantRange.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000078#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079#include "llvm/Support/InstIterator.h"
80#include "llvm/Support/ManagedStatic.h"
81#include "llvm/Support/MathExtras.h"
Dan Gohman13058cc2009-04-21 00:47:46 +000082#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083#include "llvm/ADT/Statistic.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000084#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085#include <ostream>
86#include <algorithm>
87#include <cmath>
88using namespace llvm;
89
Dan Gohmanf17a25c2007-07-18 16:29:46 +000090STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
98
Dan Gohman089efff2008-05-13 00:00:25 +000099static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000100MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
102 "symbolically execute a constant derived loop"),
103 cl::init(100));
104
Dan Gohman089efff2008-05-13 00:00:25 +0000105static RegisterPass<ScalarEvolution>
106R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107char ScalarEvolution::ID = 0;
108
109//===----------------------------------------------------------------------===//
110// SCEV class definitions
111//===----------------------------------------------------------------------===//
112
113//===----------------------------------------------------------------------===//
114// Implementation of the SCEV class.
115//
116SCEV::~SCEV() {}
117void SCEV::dump() const {
Dan Gohman13058cc2009-04-21 00:47:46 +0000118 print(errs());
119 errs() << '\n';
120}
121
122void SCEV::print(std::ostream &o) const {
123 raw_os_ostream OS(o);
124 print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125}
126
Dan Gohman7b560c42008-06-18 16:23:07 +0000127bool SCEV::isZero() const {
128 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
129 return SC->getValue()->isZero();
130 return false;
131}
132
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133
134SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
Dan Gohmanffd36ba2009-04-21 23:15:49 +0000135SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136
137bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
138 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
139 return false;
140}
141
142const Type *SCEVCouldNotCompute::getType() const {
143 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
144 return 0;
145}
146
147bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
148 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
149 return false;
150}
151
152SCEVHandle SCEVCouldNotCompute::
153replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000154 const SCEVHandle &Conc,
155 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156 return this;
157}
158
Dan Gohman13058cc2009-04-21 00:47:46 +0000159void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000160 OS << "***COULDNOTCOMPUTE***";
161}
162
163bool SCEVCouldNotCompute::classof(const SCEV *S) {
164 return S->getSCEVType() == scCouldNotCompute;
165}
166
167
168// SCEVConstants - Only allow the creation of one SCEVConstant for any
169// particular value. Don't use a SCEVHandle here, or else the object will
170// never be deleted!
171static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
172
173
174SCEVConstant::~SCEVConstant() {
175 SCEVConstants->erase(V);
176}
177
Dan Gohman89f85052007-10-22 18:31:58 +0000178SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 SCEVConstant *&R = (*SCEVConstants)[V];
180 if (R == 0) R = new SCEVConstant(V);
181 return R;
182}
183
Dan Gohman89f85052007-10-22 18:31:58 +0000184SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
185 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000186}
187
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188const Type *SCEVConstant::getType() const { return V->getType(); }
189
Dan Gohman13058cc2009-04-21 00:47:46 +0000190void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191 WriteAsOperand(OS, V, false);
192}
193
Dan Gohman2a381532009-04-21 01:25:57 +0000194SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
195 const SCEVHandle &op, const Type *ty)
196 : SCEV(SCEVTy), Op(op), Ty(ty) {}
197
198SCEVCastExpr::~SCEVCastExpr() {}
199
200bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
201 return Op->dominates(BB, DT);
202}
203
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
205// particular input. Don't use a SCEVHandle here, or else the object will
206// never be deleted!
207static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
208 SCEVTruncateExpr*> > SCEVTruncates;
209
210SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000211 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000212 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
213 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215}
216
217SCEVTruncateExpr::~SCEVTruncateExpr() {
218 SCEVTruncates->erase(std::make_pair(Op, Ty));
219}
220
Dan Gohman13058cc2009-04-21 00:47:46 +0000221void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222 OS << "(truncate " << *Op << " to " << *Ty << ")";
223}
224
225// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
226// particular input. Don't use a SCEVHandle here, or else the object will never
227// be deleted!
228static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
229 SCEVZeroExtendExpr*> > SCEVZeroExtends;
230
231SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000232 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000233 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
234 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000235 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236}
237
238SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
239 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
240}
241
Dan Gohman13058cc2009-04-21 00:47:46 +0000242void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000243 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
244}
245
246// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
247// particular input. Don't use a SCEVHandle here, or else the object will never
248// be deleted!
249static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
250 SCEVSignExtendExpr*> > SCEVSignExtends;
251
252SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000253 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000254 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
255 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000256 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257}
258
259SCEVSignExtendExpr::~SCEVSignExtendExpr() {
260 SCEVSignExtends->erase(std::make_pair(Op, Ty));
261}
262
Dan Gohman13058cc2009-04-21 00:47:46 +0000263void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264 OS << "(signextend " << *Op << " to " << *Ty << ")";
265}
266
267// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
268// particular input. Don't use a SCEVHandle here, or else the object will never
269// be deleted!
270static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
271 SCEVCommutativeExpr*> > SCEVCommExprs;
272
273SCEVCommutativeExpr::~SCEVCommutativeExpr() {
274 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
275 std::vector<SCEV*>(Operands.begin(),
276 Operands.end())));
277}
278
Dan Gohman13058cc2009-04-21 00:47:46 +0000279void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
281 const char *OpStr = getOperationStr();
282 OS << "(" << *Operands[0];
283 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
284 OS << OpStr << *Operands[i];
285 OS << ")";
286}
287
288SCEVHandle SCEVCommutativeExpr::
289replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000290 const SCEVHandle &Conc,
291 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000293 SCEVHandle H =
294 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295 if (H != getOperand(i)) {
296 std::vector<SCEVHandle> NewOps;
297 NewOps.reserve(getNumOperands());
298 for (unsigned j = 0; j != i; ++j)
299 NewOps.push_back(getOperand(j));
300 NewOps.push_back(H);
301 for (++i; i != e; ++i)
302 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000303 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304
305 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000306 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000307 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000308 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000309 else if (isa<SCEVSMaxExpr>(this))
310 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000311 else if (isa<SCEVUMaxExpr>(this))
312 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313 else
314 assert(0 && "Unknown commutative expr!");
315 }
316 }
317 return this;
318}
319
Evan Cheng98c073b2009-02-17 00:13:06 +0000320bool SCEVCommutativeExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
321 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
322 if (!getOperand(i)->dominates(BB, DT))
323 return false;
324 }
325 return true;
326}
327
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000328
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000329// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330// input. Don't use a SCEVHandle here, or else the object will never be
331// deleted!
332static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000333 SCEVUDivExpr*> > SCEVUDivs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000335SCEVUDivExpr::~SCEVUDivExpr() {
336 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000337}
338
Evan Cheng98c073b2009-02-17 00:13:06 +0000339bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
340 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
341}
342
Dan Gohman13058cc2009-04-21 00:47:46 +0000343void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000344 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000345}
346
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000347const Type *SCEVUDivExpr::getType() const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000348 return LHS->getType();
349}
350
351// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
352// particular input. Don't use a SCEVHandle here, or else the object will never
353// be deleted!
354static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
355 SCEVAddRecExpr*> > SCEVAddRecExprs;
356
357SCEVAddRecExpr::~SCEVAddRecExpr() {
358 SCEVAddRecExprs->erase(std::make_pair(L,
359 std::vector<SCEV*>(Operands.begin(),
360 Operands.end())));
361}
362
Evan Cheng98c073b2009-02-17 00:13:06 +0000363bool SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
364 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
365 if (!getOperand(i)->dominates(BB, DT))
366 return false;
367 }
368 return true;
369}
370
371
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372SCEVHandle SCEVAddRecExpr::
373replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000374 const SCEVHandle &Conc,
375 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000376 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000377 SCEVHandle H =
378 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000379 if (H != getOperand(i)) {
380 std::vector<SCEVHandle> NewOps;
381 NewOps.reserve(getNumOperands());
382 for (unsigned j = 0; j != i; ++j)
383 NewOps.push_back(getOperand(j));
384 NewOps.push_back(H);
385 for (++i; i != e; ++i)
386 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000387 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000388
Dan Gohman89f85052007-10-22 18:31:58 +0000389 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000390 }
391 }
392 return this;
393}
394
395
396bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
397 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
398 // contain L and if the start is invariant.
399 return !QueryLoop->contains(L->getHeader()) &&
400 getOperand(0)->isLoopInvariant(QueryLoop);
401}
402
403
Dan Gohman13058cc2009-04-21 00:47:46 +0000404void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000405 OS << "{" << *Operands[0];
406 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
407 OS << ",+," << *Operands[i];
408 OS << "}<" << L->getHeader()->getName() + ">";
409}
410
411// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
412// value. Don't use a SCEVHandle here, or else the object will never be
413// deleted!
414static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
415
416SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
417
418bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
419 // All non-instruction values are loop invariant. All instructions are loop
420 // invariant if they are not contained in the specified loop.
421 if (Instruction *I = dyn_cast<Instruction>(V))
422 return !L->contains(I->getParent());
423 return true;
424}
425
Evan Cheng98c073b2009-02-17 00:13:06 +0000426bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
427 if (Instruction *I = dyn_cast<Instruction>(getValue()))
428 return DT->dominates(I->getParent(), BB);
429 return true;
430}
431
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432const Type *SCEVUnknown::getType() const {
433 return V->getType();
434}
435
Dan Gohman13058cc2009-04-21 00:47:46 +0000436void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000437 if (isa<PointerType>(V->getType()))
438 OS << "(ptrtoint " << *V->getType() << " ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000439 WriteAsOperand(OS, V, false);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000440 if (isa<PointerType>(V->getType()))
441 OS << " to iPTR)";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000442}
443
444//===----------------------------------------------------------------------===//
445// SCEV Utilities
446//===----------------------------------------------------------------------===//
447
448namespace {
449 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
450 /// than the complexity of the RHS. This comparator is used to canonicalize
451 /// expressions.
452 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000453 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000454 return LHS->getSCEVType() < RHS->getSCEVType();
455 }
456 };
457}
458
459/// GroupByComplexity - Given a list of SCEV objects, order them by their
460/// complexity, and group objects of the same complexity together by value.
461/// When this routine is finished, we know that any duplicates in the vector are
462/// consecutive and that complexity is monotonically increasing.
463///
464/// Note that we go take special precautions to ensure that we get determinstic
465/// results from this routine. In other words, we don't want the results of
466/// this to depend on where the addresses of various SCEV objects happened to
467/// land in memory.
468///
469static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
470 if (Ops.size() < 2) return; // Noop
471 if (Ops.size() == 2) {
472 // This is the common case, which also happens to be trivially simple.
473 // Special case it.
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000474 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000475 std::swap(Ops[0], Ops[1]);
476 return;
477 }
478
479 // Do the rough sort by complexity.
480 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
481
482 // Now that we are sorted by complexity, group elements of the same
483 // complexity. Note that this is, at worst, N^2, but the vector is likely to
484 // be extremely short in practice. Note that we take this approach because we
485 // do not want to depend on the addresses of the objects we are grouping.
486 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
487 SCEV *S = Ops[i];
488 unsigned Complexity = S->getSCEVType();
489
490 // If there are any objects of the same complexity and same value as this
491 // one, group them.
492 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
493 if (Ops[j] == S) { // Found a duplicate.
494 // Move it to immediately after i'th element.
495 std::swap(Ops[i+1], Ops[j]);
496 ++i; // no need to rescan it.
497 if (i == e-2) return; // Done!
498 }
499 }
500 }
501}
502
503
504
505//===----------------------------------------------------------------------===//
506// Simple SCEV method implementations
507//===----------------------------------------------------------------------===//
508
Eli Friedman7489ec92008-08-04 23:49:06 +0000509/// BinomialCoefficient - Compute BC(It, K). The result has width W.
510// Assume, K > 0.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000511static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000512 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000513 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000514 // Handle the simplest case efficiently.
515 if (K == 1)
516 return SE.getTruncateOrZeroExtend(It, ResultTy);
517
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000518 // We are using the following formula for BC(It, K):
519 //
520 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
521 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000522 // Suppose, W is the bitwidth of the return value. We must be prepared for
523 // overflow. Hence, we must assure that the result of our computation is
524 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
525 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000526 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000527 // However, this code doesn't use exactly that formula; the formula it uses
528 // is something like the following, where T is the number of factors of 2 in
529 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
530 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000531 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000532 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000533 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000534 // This formula is trivially equivalent to the previous formula. However,
535 // this formula can be implemented much more efficiently. The trick is that
536 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
537 // arithmetic. To do exact division in modular arithmetic, all we have
538 // to do is multiply by the inverse. Therefore, this step can be done at
539 // width W.
540 //
541 // The next issue is how to safely do the division by 2^T. The way this
542 // is done is by doing the multiplication step at a width of at least W + T
543 // bits. This way, the bottom W+T bits of the product are accurate. Then,
544 // when we perform the division by 2^T (which is equivalent to a right shift
545 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
546 // truncated out after the division by 2^T.
547 //
548 // In comparison to just directly using the first formula, this technique
549 // is much more efficient; using the first formula requires W * K bits,
550 // but this formula less than W + K bits. Also, the first formula requires
551 // a division step, whereas this formula only requires multiplies and shifts.
552 //
553 // It doesn't matter whether the subtraction step is done in the calculation
554 // width or the input iteration count's width; if the subtraction overflows,
555 // the result must be zero anyway. We prefer here to do it in the width of
556 // the induction variable because it helps a lot for certain cases; CodeGen
557 // isn't smart enough to ignore the overflow, which leads to much less
558 // efficient code if the width of the subtraction is wider than the native
559 // register width.
560 //
561 // (It's possible to not widen at all by pulling out factors of 2 before
562 // the multiplication; for example, K=2 can be calculated as
563 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
564 // extra arithmetic, so it's not an obvious win, and it gets
565 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000566
Eli Friedman7489ec92008-08-04 23:49:06 +0000567 // Protection from insane SCEVs; this bound is conservative,
568 // but it probably doesn't matter.
569 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000570 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000571
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000572 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000573
Eli Friedman7489ec92008-08-04 23:49:06 +0000574 // Calculate K! / 2^T and T; we divide out the factors of two before
575 // multiplying for calculating K! / 2^T to avoid overflow.
576 // Other overflow doesn't matter because we only care about the bottom
577 // W bits of the result.
578 APInt OddFactorial(W, 1);
579 unsigned T = 1;
580 for (unsigned i = 3; i <= K; ++i) {
581 APInt Mult(W, i);
582 unsigned TwoFactors = Mult.countTrailingZeros();
583 T += TwoFactors;
584 Mult = Mult.lshr(TwoFactors);
585 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000587
Eli Friedman7489ec92008-08-04 23:49:06 +0000588 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000589 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000590
591 // Calcuate 2^T, at width T+W.
592 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
593
594 // Calculate the multiplicative inverse of K! / 2^T;
595 // this multiplication factor will perform the exact division by
596 // K! / 2^T.
597 APInt Mod = APInt::getSignedMinValue(W+1);
598 APInt MultiplyFactor = OddFactorial.zext(W+1);
599 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
600 MultiplyFactor = MultiplyFactor.trunc(W);
601
602 // Calculate the product, at width T+W
603 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
604 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
605 for (unsigned i = 1; i != K; ++i) {
606 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
607 Dividend = SE.getMulExpr(Dividend,
608 SE.getTruncateOrZeroExtend(S, CalculationTy));
609 }
610
611 // Divide by 2^T
612 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
613
614 // Truncate the result, and divide by K! / 2^T.
615
616 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
617 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000618}
619
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000620/// evaluateAtIteration - Return the value of this chain of recurrences at
621/// the specified iteration number. We can evaluate this recurrence by
622/// multiplying each element in the chain by the binomial coefficient
623/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
624///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000625/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000627/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628///
Dan Gohman89f85052007-10-22 18:31:58 +0000629SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
630 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000631 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000633 // The computation is correct in the face of overflow provided that the
634 // multiplication is performed _after_ the evaluation of the binomial
635 // coefficient.
Dan Gohman01c2ee72009-04-16 03:18:22 +0000636 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000637 if (isa<SCEVCouldNotCompute>(Coeff))
638 return Coeff;
639
640 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641 }
642 return Result;
643}
644
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000645//===----------------------------------------------------------------------===//
646// SCEV Expression folder implementations
647//===----------------------------------------------------------------------===//
648
Dan Gohman89f85052007-10-22 18:31:58 +0000649SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000650 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000651 "This is not a truncating conversion!");
652
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000653 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000654 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000655 ConstantExpr::getTrunc(SC->getValue(), Ty));
656
Dan Gohman1a5c4992009-04-22 16:20:48 +0000657 // trunc(trunc(x)) --> trunc(x)
658 if (SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
659 return getTruncateExpr(ST->getOperand(), Ty);
660
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000661 // If the input value is a chrec scev made out of constants, truncate
662 // all of the constants.
663 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
664 std::vector<SCEVHandle> Operands;
665 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
666 // FIXME: This should allow truncation of other expression types!
667 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman89f85052007-10-22 18:31:58 +0000668 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669 else
670 break;
671 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman89f85052007-10-22 18:31:58 +0000672 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673 }
674
675 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
676 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
677 return Result;
678}
679
Dan Gohman36d40922009-04-16 19:25:55 +0000680SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
681 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000682 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000683 "This is not an extending conversion!");
684
Dan Gohman01c2ee72009-04-16 03:18:22 +0000685 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000686 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000687 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
688 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
689 return getUnknown(C);
690 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000691
Dan Gohman1a5c4992009-04-22 16:20:48 +0000692 // zext(zext(x)) --> zext(x)
693 if (SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
694 return getZeroExtendExpr(SZ->getOperand(), Ty);
695
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000696 // FIXME: If the input value is a chrec scev, and we can prove that the value
697 // did not overflow the old, smaller, value, we can zero extend all of the
698 // operands (often constants). This would allow analysis of something like
699 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
700
701 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
702 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
703 return Result;
704}
705
Dan Gohman89f85052007-10-22 18:31:58 +0000706SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000707 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000708 "This is not an extending conversion!");
709
Dan Gohman01c2ee72009-04-16 03:18:22 +0000710 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000711 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000712 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
713 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
714 return getUnknown(C);
715 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000716
Dan Gohman1a5c4992009-04-22 16:20:48 +0000717 // sext(sext(x)) --> sext(x)
718 if (SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
719 return getSignExtendExpr(SS->getOperand(), Ty);
720
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000721 // FIXME: If the input value is a chrec scev, and we can prove that the value
722 // did not overflow the old, smaller, value, we can sign extend all of the
723 // operands (often constants). This would allow analysis of something like
724 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
725
726 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
727 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
728 return Result;
729}
730
731// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000732SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000733 assert(!Ops.empty() && "Cannot get empty add!");
734 if (Ops.size() == 1) return Ops[0];
735
736 // Sort by complexity, this groups all similar expression types together.
737 GroupByComplexity(Ops);
738
739 // If there are any constants, fold them together.
740 unsigned Idx = 0;
741 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
742 ++Idx;
743 assert(Idx < Ops.size());
744 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
745 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000746 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
747 RHSC->getValue()->getValue());
748 Ops[0] = getConstant(Fold);
749 Ops.erase(Ops.begin()+1); // Erase the folded element
750 if (Ops.size() == 1) return Ops[0];
751 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000752 }
753
754 // If we are left with a constant zero being added, strip it off.
755 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
756 Ops.erase(Ops.begin());
757 --Idx;
758 }
759 }
760
761 if (Ops.size() == 1) return Ops[0];
762
763 // Okay, check to see if the same value occurs in the operand list twice. If
764 // so, merge them together into an multiply expression. Since we sorted the
765 // list, these values are required to be adjacent.
766 const Type *Ty = Ops[0]->getType();
767 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
768 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
769 // Found a match, merge the two values into a multiply, and add any
770 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000771 SCEVHandle Two = getIntegerSCEV(2, Ty);
772 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000773 if (Ops.size() == 2)
774 return Mul;
775 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
776 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000777 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000778 }
779
780 // Now we know the first non-constant operand. Skip past any cast SCEVs.
781 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
782 ++Idx;
783
784 // If there are add operands they would be next.
785 if (Idx < Ops.size()) {
786 bool DeletedAdd = false;
787 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
788 // If we have an add, expand the add operands onto the end of the operands
789 // list.
790 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
791 Ops.erase(Ops.begin()+Idx);
792 DeletedAdd = true;
793 }
794
795 // If we deleted at least one add, we added operands to the end of the list,
796 // and they are not necessarily sorted. Recurse to resort and resimplify
797 // any operands we just aquired.
798 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +0000799 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000800 }
801
802 // Skip over the add expression until we get to a multiply.
803 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
804 ++Idx;
805
806 // If we are adding something to a multiply expression, make sure the
807 // something is not already an operand of the multiply. If so, merge it into
808 // the multiply.
809 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
810 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
811 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
812 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
813 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
814 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
815 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
816 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
817 if (Mul->getNumOperands() != 2) {
818 // If the multiply has more than two operands, we must get the
819 // Y*Z term.
820 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
821 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000822 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000823 }
Dan Gohman89f85052007-10-22 18:31:58 +0000824 SCEVHandle One = getIntegerSCEV(1, Ty);
825 SCEVHandle AddOne = getAddExpr(InnerMul, One);
826 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000827 if (Ops.size() == 2) return OuterMul;
828 if (AddOp < Idx) {
829 Ops.erase(Ops.begin()+AddOp);
830 Ops.erase(Ops.begin()+Idx-1);
831 } else {
832 Ops.erase(Ops.begin()+Idx);
833 Ops.erase(Ops.begin()+AddOp-1);
834 }
835 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000836 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000837 }
838
839 // Check this multiply against other multiplies being added together.
840 for (unsigned OtherMulIdx = Idx+1;
841 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
842 ++OtherMulIdx) {
843 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
844 // If MulOp occurs in OtherMul, we can fold the two multiplies
845 // together.
846 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
847 OMulOp != e; ++OMulOp)
848 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
849 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
850 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
851 if (Mul->getNumOperands() != 2) {
852 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
853 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000854 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000855 }
856 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
857 if (OtherMul->getNumOperands() != 2) {
858 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
859 OtherMul->op_end());
860 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000861 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000862 }
Dan Gohman89f85052007-10-22 18:31:58 +0000863 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
864 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000865 if (Ops.size() == 2) return OuterMul;
866 Ops.erase(Ops.begin()+Idx);
867 Ops.erase(Ops.begin()+OtherMulIdx-1);
868 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000869 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000870 }
871 }
872 }
873 }
874
875 // If there are any add recurrences in the operands list, see if any other
876 // added values are loop invariant. If so, we can fold them into the
877 // recurrence.
878 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
879 ++Idx;
880
881 // Scan over all recurrences, trying to fold loop invariants into them.
882 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
883 // Scan all of the other operands to this add and add them to the vector if
884 // they are loop invariant w.r.t. the recurrence.
885 std::vector<SCEVHandle> LIOps;
886 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
887 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
888 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
889 LIOps.push_back(Ops[i]);
890 Ops.erase(Ops.begin()+i);
891 --i; --e;
892 }
893
894 // If we found some loop invariants, fold them into the recurrence.
895 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +0000896 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000897 LIOps.push_back(AddRec->getStart());
898
899 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +0000900 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000901
Dan Gohman89f85052007-10-22 18:31:58 +0000902 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000903 // If all of the other operands were loop invariant, we are done.
904 if (Ops.size() == 1) return NewRec;
905
906 // Otherwise, add the folded AddRec by the non-liv parts.
907 for (unsigned i = 0;; ++i)
908 if (Ops[i] == AddRec) {
909 Ops[i] = NewRec;
910 break;
911 }
Dan Gohman89f85052007-10-22 18:31:58 +0000912 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000913 }
914
915 // Okay, if there weren't any loop invariants to be folded, check to see if
916 // there are multiple AddRec's with the same loop induction variable being
917 // added together. If so, we can fold them.
918 for (unsigned OtherIdx = Idx+1;
919 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
920 if (OtherIdx != Idx) {
921 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
922 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
923 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
924 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
925 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
926 if (i >= NewOps.size()) {
927 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
928 OtherAddRec->op_end());
929 break;
930 }
Dan Gohman89f85052007-10-22 18:31:58 +0000931 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000932 }
Dan Gohman89f85052007-10-22 18:31:58 +0000933 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934
935 if (Ops.size() == 2) return NewAddRec;
936
937 Ops.erase(Ops.begin()+Idx);
938 Ops.erase(Ops.begin()+OtherIdx-1);
939 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +0000940 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000941 }
942 }
943
944 // Otherwise couldn't fold anything into this recurrence. Move onto the
945 // next one.
946 }
947
948 // Okay, it looks like we really DO need an add expr. Check to see if we
949 // already have one, otherwise create a new one.
950 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
951 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
952 SCEVOps)];
953 if (Result == 0) Result = new SCEVAddExpr(Ops);
954 return Result;
955}
956
957
Dan Gohman89f85052007-10-22 18:31:58 +0000958SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000959 assert(!Ops.empty() && "Cannot get empty mul!");
960
961 // Sort by complexity, this groups all similar expression types together.
962 GroupByComplexity(Ops);
963
964 // If there are any constants, fold them together.
965 unsigned Idx = 0;
966 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
967
968 // C1*(C2+V) -> C1*C2 + C1*V
969 if (Ops.size() == 2)
970 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
971 if (Add->getNumOperands() == 2 &&
972 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +0000973 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
974 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000975
976
977 ++Idx;
978 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
979 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000980 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
981 RHSC->getValue()->getValue());
982 Ops[0] = getConstant(Fold);
983 Ops.erase(Ops.begin()+1); // Erase the folded element
984 if (Ops.size() == 1) return Ops[0];
985 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000986 }
987
988 // If we are left with a constant one being multiplied, strip it off.
989 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
990 Ops.erase(Ops.begin());
991 --Idx;
992 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
993 // If we have a multiply of zero, it will always be zero.
994 return Ops[0];
995 }
996 }
997
998 // Skip over the add expression until we get to a multiply.
999 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1000 ++Idx;
1001
1002 if (Ops.size() == 1)
1003 return Ops[0];
1004
1005 // If there are mul operands inline them all into this expression.
1006 if (Idx < Ops.size()) {
1007 bool DeletedMul = false;
1008 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1009 // If we have an mul, expand the mul operands onto the end of the operands
1010 // list.
1011 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1012 Ops.erase(Ops.begin()+Idx);
1013 DeletedMul = true;
1014 }
1015
1016 // If we deleted at least one mul, we added operands to the end of the list,
1017 // and they are not necessarily sorted. Recurse to resort and resimplify
1018 // any operands we just aquired.
1019 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001020 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001021 }
1022
1023 // If there are any add recurrences in the operands list, see if any other
1024 // added values are loop invariant. If so, we can fold them into the
1025 // recurrence.
1026 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1027 ++Idx;
1028
1029 // Scan over all recurrences, trying to fold loop invariants into them.
1030 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1031 // Scan all of the other operands to this mul and add them to the vector if
1032 // they are loop invariant w.r.t. the recurrence.
1033 std::vector<SCEVHandle> LIOps;
1034 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1035 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1036 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1037 LIOps.push_back(Ops[i]);
1038 Ops.erase(Ops.begin()+i);
1039 --i; --e;
1040 }
1041
1042 // If we found some loop invariants, fold them into the recurrence.
1043 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001044 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001045 std::vector<SCEVHandle> NewOps;
1046 NewOps.reserve(AddRec->getNumOperands());
1047 if (LIOps.size() == 1) {
1048 SCEV *Scale = LIOps[0];
1049 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001050 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001051 } else {
1052 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1053 std::vector<SCEVHandle> MulOps(LIOps);
1054 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001055 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001056 }
1057 }
1058
Dan Gohman89f85052007-10-22 18:31:58 +00001059 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001060
1061 // If all of the other operands were loop invariant, we are done.
1062 if (Ops.size() == 1) return NewRec;
1063
1064 // Otherwise, multiply the folded AddRec by the non-liv parts.
1065 for (unsigned i = 0;; ++i)
1066 if (Ops[i] == AddRec) {
1067 Ops[i] = NewRec;
1068 break;
1069 }
Dan Gohman89f85052007-10-22 18:31:58 +00001070 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001071 }
1072
1073 // Okay, if there weren't any loop invariants to be folded, check to see if
1074 // there are multiple AddRec's with the same loop induction variable being
1075 // multiplied together. If so, we can fold them.
1076 for (unsigned OtherIdx = Idx+1;
1077 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1078 if (OtherIdx != Idx) {
1079 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1080 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1081 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1082 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001083 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001084 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001085 SCEVHandle B = F->getStepRecurrence(*this);
1086 SCEVHandle D = G->getStepRecurrence(*this);
1087 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1088 getMulExpr(G, B),
1089 getMulExpr(B, D));
1090 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1091 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001092 if (Ops.size() == 2) return NewAddRec;
1093
1094 Ops.erase(Ops.begin()+Idx);
1095 Ops.erase(Ops.begin()+OtherIdx-1);
1096 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001097 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001098 }
1099 }
1100
1101 // Otherwise couldn't fold anything into this recurrence. Move onto the
1102 // next one.
1103 }
1104
1105 // Okay, it looks like we really DO need an mul expr. Check to see if we
1106 // already have one, otherwise create a new one.
1107 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1108 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1109 SCEVOps)];
1110 if (Result == 0)
1111 Result = new SCEVMulExpr(Ops);
1112 return Result;
1113}
1114
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001115SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001116 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1117 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001118 return LHS; // X udiv 1 --> x
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001119
1120 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1121 Constant *LHSCV = LHSC->getValue();
1122 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001123 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001124 }
1125 }
1126
Nick Lewycky35b56022009-01-13 09:18:58 +00001127 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1128
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001129 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1130 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001131 return Result;
1132}
1133
1134
1135/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1136/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001137SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001138 const SCEVHandle &Step, const Loop *L) {
1139 std::vector<SCEVHandle> Operands;
1140 Operands.push_back(Start);
1141 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1142 if (StepChrec->getLoop() == L) {
1143 Operands.insert(Operands.end(), StepChrec->op_begin(),
1144 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001145 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146 }
1147
1148 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001149 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001150}
1151
1152/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1153/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001154SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001155 const Loop *L) {
1156 if (Operands.size() == 1) return Operands[0];
1157
Dan Gohman7b560c42008-06-18 16:23:07 +00001158 if (Operands.back()->isZero()) {
1159 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001160 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001161 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001162
Dan Gohman42936882008-08-08 18:33:12 +00001163 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1164 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1165 const Loop* NestedLoop = NestedAR->getLoop();
1166 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1167 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1168 NestedAR->op_end());
1169 SCEVHandle NestedARHandle(NestedAR);
1170 Operands[0] = NestedAR->getStart();
1171 NestedOperands[0] = getAddRecExpr(Operands, L);
1172 return getAddRecExpr(NestedOperands, NestedLoop);
1173 }
1174 }
1175
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001176 SCEVAddRecExpr *&Result =
1177 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1178 Operands.end()))];
1179 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1180 return Result;
1181}
1182
Nick Lewycky711640a2007-11-25 22:41:31 +00001183SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1184 const SCEVHandle &RHS) {
1185 std::vector<SCEVHandle> Ops;
1186 Ops.push_back(LHS);
1187 Ops.push_back(RHS);
1188 return getSMaxExpr(Ops);
1189}
1190
1191SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1192 assert(!Ops.empty() && "Cannot get empty smax!");
1193 if (Ops.size() == 1) return Ops[0];
1194
1195 // Sort by complexity, this groups all similar expression types together.
1196 GroupByComplexity(Ops);
1197
1198 // If there are any constants, fold them together.
1199 unsigned Idx = 0;
1200 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1201 ++Idx;
1202 assert(Idx < Ops.size());
1203 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1204 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001205 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001206 APIntOps::smax(LHSC->getValue()->getValue(),
1207 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001208 Ops[0] = getConstant(Fold);
1209 Ops.erase(Ops.begin()+1); // Erase the folded element
1210 if (Ops.size() == 1) return Ops[0];
1211 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001212 }
1213
1214 // If we are left with a constant -inf, strip it off.
1215 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1216 Ops.erase(Ops.begin());
1217 --Idx;
1218 }
1219 }
1220
1221 if (Ops.size() == 1) return Ops[0];
1222
1223 // Find the first SMax
1224 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1225 ++Idx;
1226
1227 // Check to see if one of the operands is an SMax. If so, expand its operands
1228 // onto our operand list, and recurse to simplify.
1229 if (Idx < Ops.size()) {
1230 bool DeletedSMax = false;
1231 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1232 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1233 Ops.erase(Ops.begin()+Idx);
1234 DeletedSMax = true;
1235 }
1236
1237 if (DeletedSMax)
1238 return getSMaxExpr(Ops);
1239 }
1240
1241 // Okay, check to see if the same value occurs in the operand list twice. If
1242 // so, delete one. Since we sorted the list, these values are required to
1243 // be adjacent.
1244 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1245 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1246 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1247 --i; --e;
1248 }
1249
1250 if (Ops.size() == 1) return Ops[0];
1251
1252 assert(!Ops.empty() && "Reduced smax down to nothing!");
1253
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001254 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001255 // already have one, otherwise create a new one.
1256 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1257 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1258 SCEVOps)];
1259 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1260 return Result;
1261}
1262
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001263SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1264 const SCEVHandle &RHS) {
1265 std::vector<SCEVHandle> Ops;
1266 Ops.push_back(LHS);
1267 Ops.push_back(RHS);
1268 return getUMaxExpr(Ops);
1269}
1270
1271SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1272 assert(!Ops.empty() && "Cannot get empty umax!");
1273 if (Ops.size() == 1) return Ops[0];
1274
1275 // Sort by complexity, this groups all similar expression types together.
1276 GroupByComplexity(Ops);
1277
1278 // If there are any constants, fold them together.
1279 unsigned Idx = 0;
1280 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1281 ++Idx;
1282 assert(Idx < Ops.size());
1283 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1284 // We found two constants, fold them together!
1285 ConstantInt *Fold = ConstantInt::get(
1286 APIntOps::umax(LHSC->getValue()->getValue(),
1287 RHSC->getValue()->getValue()));
1288 Ops[0] = getConstant(Fold);
1289 Ops.erase(Ops.begin()+1); // Erase the folded element
1290 if (Ops.size() == 1) return Ops[0];
1291 LHSC = cast<SCEVConstant>(Ops[0]);
1292 }
1293
1294 // If we are left with a constant zero, strip it off.
1295 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1296 Ops.erase(Ops.begin());
1297 --Idx;
1298 }
1299 }
1300
1301 if (Ops.size() == 1) return Ops[0];
1302
1303 // Find the first UMax
1304 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1305 ++Idx;
1306
1307 // Check to see if one of the operands is a UMax. If so, expand its operands
1308 // onto our operand list, and recurse to simplify.
1309 if (Idx < Ops.size()) {
1310 bool DeletedUMax = false;
1311 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1312 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1313 Ops.erase(Ops.begin()+Idx);
1314 DeletedUMax = true;
1315 }
1316
1317 if (DeletedUMax)
1318 return getUMaxExpr(Ops);
1319 }
1320
1321 // Okay, check to see if the same value occurs in the operand list twice. If
1322 // so, delete one. Since we sorted the list, these values are required to
1323 // be adjacent.
1324 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1325 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1326 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1327 --i; --e;
1328 }
1329
1330 if (Ops.size() == 1) return Ops[0];
1331
1332 assert(!Ops.empty() && "Reduced umax down to nothing!");
1333
1334 // Okay, it looks like we really DO need a umax expr. Check to see if we
1335 // already have one, otherwise create a new one.
1336 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1337 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1338 SCEVOps)];
1339 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1340 return Result;
1341}
1342
Dan Gohman89f85052007-10-22 18:31:58 +00001343SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001344 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001345 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001346 if (isa<ConstantPointerNull>(V))
1347 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001348 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1349 if (Result == 0) Result = new SCEVUnknown(V);
1350 return Result;
1351}
1352
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001353//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001354// Basic SCEV Analysis and PHI Idiom Recognition Code
1355//
1356
1357/// deleteValueFromRecords - This method should be called by the
1358/// client before it removes an instruction from the program, to make sure
1359/// that no dangling references are left around.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001360void ScalarEvolution::deleteValueFromRecords(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361 SmallVector<Value *, 16> Worklist;
1362
1363 if (Scalars.erase(V)) {
1364 if (PHINode *PN = dyn_cast<PHINode>(V))
1365 ConstantEvolutionLoopExitValue.erase(PN);
1366 Worklist.push_back(V);
1367 }
1368
1369 while (!Worklist.empty()) {
1370 Value *VV = Worklist.back();
1371 Worklist.pop_back();
1372
1373 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1374 UI != UE; ++UI) {
1375 Instruction *Inst = cast<Instruction>(*UI);
1376 if (Scalars.erase(Inst)) {
1377 if (PHINode *PN = dyn_cast<PHINode>(VV))
1378 ConstantEvolutionLoopExitValue.erase(PN);
1379 Worklist.push_back(Inst);
1380 }
1381 }
1382 }
1383}
1384
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001385/// isSCEVable - Test if values of the given type are analyzable within
1386/// the SCEV framework. This primarily includes integer types, and it
1387/// can optionally include pointer types if the ScalarEvolution class
1388/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001389bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001390 // Integers are always SCEVable.
1391 if (Ty->isInteger())
1392 return true;
1393
1394 // Pointers are SCEVable if TargetData information is available
1395 // to provide pointer size information.
1396 if (isa<PointerType>(Ty))
1397 return TD != NULL;
1398
1399 // Otherwise it's not SCEVable.
1400 return false;
1401}
1402
1403/// getTypeSizeInBits - Return the size in bits of the specified type,
1404/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001405uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001406 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1407
1408 // If we have a TargetData, use it!
1409 if (TD)
1410 return TD->getTypeSizeInBits(Ty);
1411
1412 // Otherwise, we support only integer types.
1413 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1414 return Ty->getPrimitiveSizeInBits();
1415}
1416
1417/// getEffectiveSCEVType - Return a type with the same bitwidth as
1418/// the given type and which represents how SCEV will treat the given
1419/// type, for which isSCEVable must return true. For pointer types,
1420/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001421const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001422 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1423
1424 if (Ty->isInteger())
1425 return Ty;
1426
1427 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1428 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001429}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001430
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001431SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman0ad08b02009-04-18 17:58:19 +00001432 return UnknownValue;
1433}
1434
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001435/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1436/// expression and create a new one.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001437SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001438 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001439
1440 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1441 if (I != Scalars.end()) return I->second;
1442 SCEVHandle S = createSCEV(V);
1443 Scalars.insert(std::make_pair(V, S));
1444 return S;
1445}
1446
Dan Gohman01c2ee72009-04-16 03:18:22 +00001447/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1448/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001449SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1450 Ty = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001451 Constant *C;
1452 if (Val == 0)
1453 C = Constant::getNullValue(Ty);
1454 else if (Ty->isFloatingPoint())
1455 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1456 APFloat::IEEEdouble, Val));
1457 else
1458 C = ConstantInt::get(Ty, Val);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001459 return getUnknown(C);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001460}
1461
1462/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1463///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001464SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001465 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001466 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001467
1468 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001469 Ty = getEffectiveSCEVType(Ty);
1470 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001471}
1472
1473/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001474SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001475 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001476 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001477
1478 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001479 Ty = getEffectiveSCEVType(Ty);
1480 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001481 return getMinusSCEV(AllOnes, V);
1482}
1483
1484/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1485///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001486SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Dan Gohman01c2ee72009-04-16 03:18:22 +00001487 const SCEVHandle &RHS) {
1488 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001489 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001490}
1491
1492/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1493/// input value to the specified type. If the type must be extended, it is zero
1494/// extended.
1495SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001496ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Dan Gohman01c2ee72009-04-16 03:18:22 +00001497 const Type *Ty) {
1498 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001499 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1500 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001501 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001502 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001503 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001504 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001505 return getTruncateExpr(V, Ty);
1506 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001507}
1508
1509/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1510/// input value to the specified type. If the type must be extended, it is sign
1511/// extended.
1512SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001513ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Dan Gohman01c2ee72009-04-16 03:18:22 +00001514 const Type *Ty) {
1515 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001516 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1517 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001518 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001519 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001520 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001521 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001522 return getTruncateExpr(V, Ty);
1523 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001524}
1525
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001526/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1527/// the specified instruction and replaces any references to the symbolic value
1528/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001529void ScalarEvolution::
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001530ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1531 const SCEVHandle &NewVal) {
1532 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1533 if (SI == Scalars.end()) return;
1534
1535 SCEVHandle NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001536 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001537 if (NV == SI->second) return; // No change.
1538
1539 SI->second = NV; // Update the scalars map!
1540
1541 // Any instruction values that use this instruction might also need to be
1542 // updated!
1543 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1544 UI != E; ++UI)
1545 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1546}
1547
1548/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1549/// a loop header, making it a potential recurrence, or it doesn't.
1550///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001551SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001552 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001553 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001554 if (L->getHeader() == PN->getParent()) {
1555 // If it lives in the loop header, it has two incoming values, one
1556 // from outside the loop, and one from inside.
1557 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1558 unsigned BackEdge = IncomingEdge^1;
1559
1560 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001561 SCEVHandle SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001562 assert(Scalars.find(PN) == Scalars.end() &&
1563 "PHI node already processed?");
1564 Scalars.insert(std::make_pair(PN, SymbolicName));
1565
1566 // Using this symbolic name for the PHI, analyze the value coming around
1567 // the back-edge.
1568 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1569
1570 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1571 // has a special value for the first iteration of the loop.
1572
1573 // If the value coming around the backedge is an add with the symbolic
1574 // value we just inserted, then we found a simple induction variable!
1575 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1576 // If there is a single occurrence of the symbolic value, replace it
1577 // with a recurrence.
1578 unsigned FoundIndex = Add->getNumOperands();
1579 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1580 if (Add->getOperand(i) == SymbolicName)
1581 if (FoundIndex == e) {
1582 FoundIndex = i;
1583 break;
1584 }
1585
1586 if (FoundIndex != Add->getNumOperands()) {
1587 // Create an add with everything but the specified operand.
1588 std::vector<SCEVHandle> Ops;
1589 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1590 if (i != FoundIndex)
1591 Ops.push_back(Add->getOperand(i));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001592 SCEVHandle Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001593
1594 // This is not a valid addrec if the step amount is varying each
1595 // loop iteration, but is not itself an addrec in this loop.
1596 if (Accum->isLoopInvariant(L) ||
1597 (isa<SCEVAddRecExpr>(Accum) &&
1598 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1599 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001600 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001601
1602 // Okay, for the entire analysis of this edge we assumed the PHI
1603 // to be symbolic. We now need to go back and update all of the
1604 // entries for the scalars that use the PHI (except for the PHI
1605 // itself) to use the new analyzed value instead of the "symbolic"
1606 // value.
1607 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1608 return PHISCEV;
1609 }
1610 }
1611 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1612 // Otherwise, this could be a loop like this:
1613 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1614 // In this case, j = {1,+,1} and BEValue is j.
1615 // Because the other in-value of i (0) fits the evolution of BEValue
1616 // i really is an addrec evolution.
1617 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1618 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1619
1620 // If StartVal = j.start - j.stride, we can use StartVal as the
1621 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001622 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00001623 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001624 SCEVHandle PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001625 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001626
1627 // Okay, for the entire analysis of this edge we assumed the PHI
1628 // to be symbolic. We now need to go back and update all of the
1629 // entries for the scalars that use the PHI (except for the PHI
1630 // itself) to use the new analyzed value instead of the "symbolic"
1631 // value.
1632 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1633 return PHISCEV;
1634 }
1635 }
1636 }
1637
1638 return SymbolicName;
1639 }
1640
1641 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001642 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001643}
1644
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001645/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1646/// guaranteed to end in (at every loop iteration). It is, at the same time,
1647/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1648/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001649static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001650 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001651 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001652
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001653 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001654 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1655 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001656
1657 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001658 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1659 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1660 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001661 }
1662
1663 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001664 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1665 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1666 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001667 }
1668
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001669 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001670 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001671 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001672 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001673 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001674 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001675 }
1676
1677 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001678 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001679 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1680 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001681 for (unsigned i = 1, e = M->getNumOperands();
1682 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001683 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001684 BitWidth);
1685 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001686 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001687
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001688 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001689 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001690 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001691 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001692 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001693 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001694 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001695
Nick Lewycky711640a2007-11-25 22:41:31 +00001696 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1697 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001698 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00001699 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001700 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00001701 return MinOpRes;
1702 }
1703
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001704 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1705 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001706 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001707 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001708 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001709 return MinOpRes;
1710 }
1711
Nick Lewycky35b56022009-01-13 09:18:58 +00001712 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001713 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001714}
1715
1716/// createSCEV - We know that there is no SCEV for the specified value.
1717/// Analyze the expression.
1718///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001719SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001720 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001721 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001722
Dan Gohman3996f472008-06-22 19:56:46 +00001723 unsigned Opcode = Instruction::UserOp1;
1724 if (Instruction *I = dyn_cast<Instruction>(V))
1725 Opcode = I->getOpcode();
1726 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1727 Opcode = CE->getOpcode();
1728 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001729 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001730
Dan Gohman3996f472008-06-22 19:56:46 +00001731 User *U = cast<User>(V);
1732 switch (Opcode) {
1733 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001734 return getAddExpr(getSCEV(U->getOperand(0)),
1735 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001736 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001737 return getMulExpr(getSCEV(U->getOperand(0)),
1738 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001739 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001740 return getUDivExpr(getSCEV(U->getOperand(0)),
1741 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001742 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001743 return getMinusSCEV(getSCEV(U->getOperand(0)),
1744 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00001745 case Instruction::And:
1746 // For an expression like x&255 that merely masks off the high bits,
1747 // use zext(trunc(x)) as the SCEV expression.
1748 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1749 const APInt &A = CI->getValue();
1750 unsigned Ones = A.countTrailingOnes();
1751 if (APIntOps::isMask(Ones, A))
1752 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001753 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
1754 IntegerType::get(Ones)),
1755 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00001756 }
1757 break;
Dan Gohman3996f472008-06-22 19:56:46 +00001758 case Instruction::Or:
1759 // If the RHS of the Or is a constant, we may have something like:
1760 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1761 // optimizations will transparently handle this case.
1762 //
1763 // In order for this transformation to be safe, the LHS must be of the
1764 // form X*(2^n) and the Or constant must be less than 2^n.
1765 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1766 SCEVHandle LHS = getSCEV(U->getOperand(0));
1767 const APInt &CIVal = CI->getValue();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001768 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman3996f472008-06-22 19:56:46 +00001769 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001770 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001771 }
Dan Gohman3996f472008-06-22 19:56:46 +00001772 break;
1773 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00001774 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00001775 // If the RHS of the xor is a signbit, then this is just an add.
1776 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00001777 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001778 return getAddExpr(getSCEV(U->getOperand(0)),
1779 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001780
1781 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman3996f472008-06-22 19:56:46 +00001782 else if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001783 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman3996f472008-06-22 19:56:46 +00001784 }
1785 break;
1786
1787 case Instruction::Shl:
1788 // Turn shift left of a constant amount into a multiply.
1789 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1790 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1791 Constant *X = ConstantInt::get(
1792 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001793 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00001794 }
1795 break;
1796
Nick Lewycky7fd27892008-07-07 06:15:49 +00001797 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00001798 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00001799 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1800 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1801 Constant *X = ConstantInt::get(
1802 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001803 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001804 }
1805 break;
1806
Dan Gohman53bf64a2009-04-21 02:26:00 +00001807 case Instruction::AShr:
1808 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
1809 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
1810 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
1811 if (L->getOpcode() == Instruction::Shl &&
1812 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman101a2672009-04-21 20:18:36 +00001813 uint64_t Amt = getTypeSizeInBits(U->getType()) - CI->getZExtValue();
Dan Gohman53bf64a2009-04-21 02:26:00 +00001814 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001815 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00001816 IntegerType::get(Amt)),
1817 U->getType());
1818 }
1819 break;
1820
Dan Gohman3996f472008-06-22 19:56:46 +00001821 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001822 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001823
1824 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001825 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001826
1827 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001828 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001829
1830 case Instruction::BitCast:
1831 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001832 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00001833 return getSCEV(U->getOperand(0));
1834 break;
1835
Dan Gohman01c2ee72009-04-16 03:18:22 +00001836 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001837 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001838 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001839 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00001840
1841 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001842 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001843 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1844 U->getType());
1845
1846 case Instruction::GetElementPtr: {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001847 if (!TD) break; // Without TD we can't analyze pointers.
1848 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001849 Value *Base = U->getOperand(0);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001850 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001851 gep_type_iterator GTI = gep_type_begin(U);
1852 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
1853 E = U->op_end();
1854 I != E; ++I) {
1855 Value *Index = *I;
1856 // Compute the (potentially symbolic) offset in bytes for this index.
1857 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1858 // For a struct, add the member offset.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001859 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001860 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1861 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001862 TotalOffset = getAddExpr(TotalOffset,
1863 getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001864 } else {
1865 // For an array, add the element offset, explicitly scaled.
1866 SCEVHandle LocalOffset = getSCEV(Index);
1867 if (!isa<PointerType>(LocalOffset->getType()))
1868 // Getelementptr indicies are signed.
1869 LocalOffset = getTruncateOrSignExtend(LocalOffset,
1870 IntPtrTy);
1871 LocalOffset =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001872 getMulExpr(LocalOffset,
1873 getIntegerSCEV(TD->getTypePaddedSize(*GTI),
1874 IntPtrTy));
1875 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001876 }
1877 }
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001878 return getAddExpr(getSCEV(Base), TotalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001879 }
1880
Dan Gohman3996f472008-06-22 19:56:46 +00001881 case Instruction::PHI:
1882 return createNodeForPHI(cast<PHINode>(U));
1883
1884 case Instruction::Select:
1885 // This could be a smax or umax that was lowered earlier.
1886 // Try to recover it.
1887 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1888 Value *LHS = ICI->getOperand(0);
1889 Value *RHS = ICI->getOperand(1);
1890 switch (ICI->getPredicate()) {
1891 case ICmpInst::ICMP_SLT:
1892 case ICmpInst::ICMP_SLE:
1893 std::swap(LHS, RHS);
1894 // fall through
1895 case ICmpInst::ICMP_SGT:
1896 case ICmpInst::ICMP_SGE:
1897 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001898 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00001899 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00001900 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001901 return getNotSCEV(getSMaxExpr(
1902 getNotSCEV(getSCEV(LHS)),
1903 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00001904 break;
1905 case ICmpInst::ICMP_ULT:
1906 case ICmpInst::ICMP_ULE:
1907 std::swap(LHS, RHS);
1908 // fall through
1909 case ICmpInst::ICMP_UGT:
1910 case ICmpInst::ICMP_UGE:
1911 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001912 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00001913 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1914 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001915 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
1916 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00001917 break;
1918 default:
1919 break;
1920 }
1921 }
1922
1923 default: // We cannot analyze this expression.
1924 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001925 }
1926
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001927 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001928}
1929
1930
1931
1932//===----------------------------------------------------------------------===//
1933// Iteration Count Computation Code
1934//
1935
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001936/// getBackedgeTakenCount - If the specified loop has a predictable
1937/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
1938/// object. The backedge-taken count is the number of times the loop header
1939/// will be branched to from within the loop. This is one less than the
1940/// trip count of the loop, since it doesn't count the first iteration,
1941/// when the header is branched to from outside the loop.
1942///
1943/// Note that it is not valid to call this method on a loop without a
1944/// loop-invariant backedge-taken count (see
1945/// hasLoopInvariantBackedgeTakenCount).
1946///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001947SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001948 std::map<const Loop*, SCEVHandle>::iterator I = BackedgeTakenCounts.find(L);
1949 if (I == BackedgeTakenCounts.end()) {
1950 SCEVHandle ItCount = ComputeBackedgeTakenCount(L);
1951 I = BackedgeTakenCounts.insert(std::make_pair(L, ItCount)).first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001952 if (ItCount != UnknownValue) {
1953 assert(ItCount->isLoopInvariant(L) &&
1954 "Computed trip count isn't loop invariant for loop!");
1955 ++NumTripCountsComputed;
1956 } else if (isa<PHINode>(L->getHeader()->begin())) {
1957 // Only count loops that have phi nodes as not being computable.
1958 ++NumTripCountsNotComputed;
1959 }
1960 }
1961 return I->second;
1962}
1963
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001964/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00001965/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001966/// ScalarEvolution's ability to compute a trip count, or if the loop
1967/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001968void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001969 BackedgeTakenCounts.erase(L);
Dan Gohmanf3a060a2009-02-17 20:49:49 +00001970}
1971
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001972/// ComputeBackedgeTakenCount - Compute the number of times the backedge
1973/// of the specified loop will execute.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001974SCEVHandle ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001975 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00001976 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001977 L->getExitBlocks(ExitBlocks);
1978 if (ExitBlocks.size() != 1) return UnknownValue;
1979
1980 // Okay, there is one exit block. Try to find the condition that causes the
1981 // loop to be exited.
1982 BasicBlock *ExitBlock = ExitBlocks[0];
1983
1984 BasicBlock *ExitingBlock = 0;
1985 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1986 PI != E; ++PI)
1987 if (L->contains(*PI)) {
1988 if (ExitingBlock == 0)
1989 ExitingBlock = *PI;
1990 else
1991 return UnknownValue; // More than one block exiting!
1992 }
1993 assert(ExitingBlock && "No exits from loop, something is broken!");
1994
1995 // Okay, we've computed the exiting block. See what condition causes us to
1996 // exit.
1997 //
1998 // FIXME: we should be able to handle switch instructions (with a single exit)
1999 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2000 if (ExitBr == 0) return UnknownValue;
2001 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2002
2003 // At this point, we know we have a conditional branch that determines whether
2004 // the loop is exited. However, we don't know if the branch is executed each
2005 // time through the loop. If not, then the execution count of the branch will
2006 // not be equal to the trip count of the loop.
2007 //
2008 // Currently we check for this by checking to see if the Exit branch goes to
2009 // the loop header. If so, we know it will always execute the same number of
2010 // times as the loop. We also handle the case where the exit block *is* the
2011 // loop header. This is common for un-rotated loops. More extensive analysis
2012 // could be done to handle more cases here.
2013 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2014 ExitBr->getSuccessor(1) != L->getHeader() &&
2015 ExitBr->getParent() != L->getHeader())
2016 return UnknownValue;
2017
2018 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2019
Nick Lewyckyb3d24332008-02-21 08:34:02 +00002020 // If it's not an integer comparison then compute it the hard way.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002021 // Note that ICmpInst deals with pointer comparisons too so we must check
2022 // the type of the operand.
2023 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002024 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002025 ExitBr->getSuccessor(0) == ExitBlock);
2026
2027 // If the condition was exit on true, convert the condition to exit on false
2028 ICmpInst::Predicate Cond;
2029 if (ExitBr->getSuccessor(1) == ExitBlock)
2030 Cond = ExitCond->getPredicate();
2031 else
2032 Cond = ExitCond->getInversePredicate();
2033
2034 // Handle common loops like: for (X = "string"; *X; ++X)
2035 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2036 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2037 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002038 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002039 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2040 }
2041
2042 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2043 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2044
2045 // Try to evaluate any dependencies out of the loop.
2046 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2047 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2048 Tmp = getSCEVAtScope(RHS, L);
2049 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2050
2051 // At this point, we would like to compute how many iterations of the
2052 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002053 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2054 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002055 std::swap(LHS, RHS);
2056 Cond = ICmpInst::getSwappedPredicate(Cond);
2057 }
2058
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002059 // If we have a comparison of a chrec against a constant, try to use value
2060 // ranges to answer this query.
2061 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2062 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2063 if (AddRec->getLoop() == L) {
2064 // Form the comparison range using the constant of the correct type so
2065 // that the ConstantRange class knows to do a signed or unsigned
2066 // comparison.
2067 ConstantInt *CompVal = RHSC->getValue();
2068 const Type *RealTy = ExitCond->getOperand(0)->getType();
2069 CompVal = dyn_cast<ConstantInt>(
2070 ConstantExpr::getBitCast(CompVal, RealTy));
2071 if (CompVal) {
2072 // Form the constant range.
2073 ConstantRange CompRange(
2074 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2075
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002076 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002077 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2078 }
2079 }
2080
2081 switch (Cond) {
2082 case ICmpInst::ICMP_NE: { // while (X != Y)
2083 // Convert to: while (X-Y != 0)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002084 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002085 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2086 break;
2087 }
2088 case ICmpInst::ICMP_EQ: {
2089 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002090 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002091 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2092 break;
2093 }
2094 case ICmpInst::ICMP_SLT: {
Nick Lewycky35b56022009-01-13 09:18:58 +00002095 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002096 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2097 break;
2098 }
2099 case ICmpInst::ICMP_SGT: {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002100 SCEVHandle TC = HowManyLessThans(getNotSCEV(LHS),
2101 getNotSCEV(RHS), L, true);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002102 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2103 break;
2104 }
2105 case ICmpInst::ICMP_ULT: {
Nick Lewycky35b56022009-01-13 09:18:58 +00002106 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002107 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2108 break;
2109 }
2110 case ICmpInst::ICMP_UGT: {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002111 SCEVHandle TC = HowManyLessThans(getNotSCEV(LHS),
2112 getNotSCEV(RHS), L, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002113 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2114 break;
2115 }
2116 default:
2117#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002118 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002119 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002120 errs() << "[unsigned] ";
2121 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002122 << Instruction::getOpcodeName(Instruction::ICmp)
2123 << " " << *RHS << "\n";
2124#endif
2125 break;
2126 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002127 return
2128 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2129 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002130}
2131
2132static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002133EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2134 ScalarEvolution &SE) {
2135 SCEVHandle InVal = SE.getConstant(C);
2136 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002137 assert(isa<SCEVConstant>(Val) &&
2138 "Evaluation of SCEV at constant didn't fold correctly?");
2139 return cast<SCEVConstant>(Val)->getValue();
2140}
2141
2142/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2143/// and a GEP expression (missing the pointer index) indexing into it, return
2144/// the addressed element of the initializer or null if the index expression is
2145/// invalid.
2146static Constant *
2147GetAddressedElementFromGlobal(GlobalVariable *GV,
2148 const std::vector<ConstantInt*> &Indices) {
2149 Constant *Init = GV->getInitializer();
2150 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2151 uint64_t Idx = Indices[i]->getZExtValue();
2152 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2153 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2154 Init = cast<Constant>(CS->getOperand(Idx));
2155 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2156 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2157 Init = cast<Constant>(CA->getOperand(Idx));
2158 } else if (isa<ConstantAggregateZero>(Init)) {
2159 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2160 assert(Idx < STy->getNumElements() && "Bad struct index!");
2161 Init = Constant::getNullValue(STy->getElementType(Idx));
2162 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2163 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2164 Init = Constant::getNullValue(ATy->getElementType());
2165 } else {
2166 assert(0 && "Unknown constant aggregate type!");
2167 }
2168 return 0;
2169 } else {
2170 return 0; // Unknown initializer type
2171 }
2172 }
2173 return Init;
2174}
2175
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002176/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2177/// 'icmp op load X, cst', try to see if we can compute the backedge
2178/// execution count.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002179SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002180ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2181 const Loop *L,
2182 ICmpInst::Predicate predicate) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002183 if (LI->isVolatile()) return UnknownValue;
2184
2185 // Check to see if the loaded pointer is a getelementptr of a global.
2186 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2187 if (!GEP) return UnknownValue;
2188
2189 // Make sure that it is really a constant global we are gepping, with an
2190 // initializer, and make sure the first IDX is really 0.
2191 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2192 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2193 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2194 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2195 return UnknownValue;
2196
2197 // Okay, we allow one non-constant index into the GEP instruction.
2198 Value *VarIdx = 0;
2199 std::vector<ConstantInt*> Indexes;
2200 unsigned VarIdxNum = 0;
2201 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2202 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2203 Indexes.push_back(CI);
2204 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2205 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2206 VarIdx = GEP->getOperand(i);
2207 VarIdxNum = i-2;
2208 Indexes.push_back(0);
2209 }
2210
2211 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2212 // Check to see if X is a loop variant variable value now.
2213 SCEVHandle Idx = getSCEV(VarIdx);
2214 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2215 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2216
2217 // We can only recognize very limited forms of loop index expressions, in
2218 // particular, only affine AddRec's like {C1,+,C2}.
2219 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2220 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2221 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2222 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2223 return UnknownValue;
2224
2225 unsigned MaxSteps = MaxBruteForceIterations;
2226 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2227 ConstantInt *ItCst =
2228 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002229 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002230
2231 // Form the GEP offset.
2232 Indexes[VarIdxNum] = Val;
2233
2234 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2235 if (Result == 0) break; // Cannot compute!
2236
2237 // Evaluate the condition for this iteration.
2238 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2239 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2240 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2241#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002242 errs() << "\n***\n*** Computed loop count " << *ItCst
2243 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2244 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002245#endif
2246 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002247 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002248 }
2249 }
2250 return UnknownValue;
2251}
2252
2253
2254/// CanConstantFold - Return true if we can constant fold an instruction of the
2255/// specified type, assuming that all operands were constants.
2256static bool CanConstantFold(const Instruction *I) {
2257 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2258 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2259 return true;
2260
2261 if (const CallInst *CI = dyn_cast<CallInst>(I))
2262 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002263 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002264 return false;
2265}
2266
2267/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2268/// in the loop that V is derived from. We allow arbitrary operations along the
2269/// way, but the operands of an operation must either be constants or a value
2270/// derived from a constant PHI. If this expression does not fit with these
2271/// constraints, return null.
2272static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2273 // If this is not an instruction, or if this is an instruction outside of the
2274 // loop, it can't be derived from a loop PHI.
2275 Instruction *I = dyn_cast<Instruction>(V);
2276 if (I == 0 || !L->contains(I->getParent())) return 0;
2277
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002278 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002279 if (L->getHeader() == I->getParent())
2280 return PN;
2281 else
2282 // We don't currently keep track of the control flow needed to evaluate
2283 // PHIs, so we cannot handle PHIs inside of loops.
2284 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002285 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002286
2287 // If we won't be able to constant fold this expression even if the operands
2288 // are constants, return early.
2289 if (!CanConstantFold(I)) return 0;
2290
2291 // Otherwise, we can evaluate this instruction if all of its operands are
2292 // constant or derived from a PHI node themselves.
2293 PHINode *PHI = 0;
2294 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2295 if (!(isa<Constant>(I->getOperand(Op)) ||
2296 isa<GlobalValue>(I->getOperand(Op)))) {
2297 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2298 if (P == 0) return 0; // Not evolving from PHI
2299 if (PHI == 0)
2300 PHI = P;
2301 else if (PHI != P)
2302 return 0; // Evolving from multiple different PHIs.
2303 }
2304
2305 // This is a expression evolving from a constant PHI!
2306 return PHI;
2307}
2308
2309/// EvaluateExpression - Given an expression that passes the
2310/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2311/// in the loop has the value PHIVal. If we can't fold this expression for some
2312/// reason, return null.
2313static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2314 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002315 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002316 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002317 Instruction *I = cast<Instruction>(V);
2318
2319 std::vector<Constant*> Operands;
2320 Operands.resize(I->getNumOperands());
2321
2322 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2323 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2324 if (Operands[i] == 0) return 0;
2325 }
2326
Chris Lattnerd6e56912007-12-10 22:53:04 +00002327 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2328 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2329 &Operands[0], Operands.size());
2330 else
2331 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2332 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002333}
2334
2335/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2336/// in the header of its containing loop, we know the loop executes a
2337/// constant number of times, and the PHI node is just a recurrence
2338/// involving constants, fold it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002339Constant *ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002340getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002341 std::map<PHINode*, Constant*>::iterator I =
2342 ConstantEvolutionLoopExitValue.find(PN);
2343 if (I != ConstantEvolutionLoopExitValue.end())
2344 return I->second;
2345
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002346 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002347 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2348
2349 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2350
2351 // Since the loop is canonicalized, the PHI node must have two entries. One
2352 // entry must be a constant (coming in from outside of the loop), and the
2353 // second must be derived from the same PHI.
2354 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2355 Constant *StartCST =
2356 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2357 if (StartCST == 0)
2358 return RetVal = 0; // Must be a constant.
2359
2360 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2361 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2362 if (PN2 != PN)
2363 return RetVal = 0; // Not derived from same PHI.
2364
2365 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002366 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002367 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2368
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002369 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002370 unsigned IterationNum = 0;
2371 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2372 if (IterationNum == NumIterations)
2373 return RetVal = PHIVal; // Got exit value!
2374
2375 // Compute the value of the PHI node for the next iteration.
2376 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2377 if (NextPHI == PHIVal)
2378 return RetVal = NextPHI; // Stopped evolving!
2379 if (NextPHI == 0)
2380 return 0; // Couldn't evaluate!
2381 PHIVal = NextPHI;
2382 }
2383}
2384
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002385/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002386/// constant number of times (the condition evolves only from constants),
2387/// try to evaluate a few iterations of the loop until we get the exit
2388/// condition gets a value of ExitWhen (true or false). If we cannot
2389/// evaluate the trip count of the loop, return UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002390SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002391ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002392 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2393 if (PN == 0) return UnknownValue;
2394
2395 // Since the loop is canonicalized, the PHI node must have two entries. One
2396 // entry must be a constant (coming in from outside of the loop), and the
2397 // second must be derived from the same PHI.
2398 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2399 Constant *StartCST =
2400 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2401 if (StartCST == 0) return UnknownValue; // Must be a constant.
2402
2403 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2404 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2405 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2406
2407 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2408 // the loop symbolically to determine when the condition gets a value of
2409 // "ExitWhen".
2410 unsigned IterationNum = 0;
2411 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2412 for (Constant *PHIVal = StartCST;
2413 IterationNum != MaxIterations; ++IterationNum) {
2414 ConstantInt *CondVal =
2415 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2416
2417 // Couldn't symbolically evaluate.
2418 if (!CondVal) return UnknownValue;
2419
2420 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2421 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2422 ++NumBruteForceTripCountsComputed;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002423 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002424 }
2425
2426 // Compute the value of the PHI node for the next iteration.
2427 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2428 if (NextPHI == 0 || NextPHI == PHIVal)
2429 return UnknownValue; // Couldn't evaluate or not making progress...
2430 PHIVal = NextPHI;
2431 }
2432
2433 // Too many iterations were needed to evaluate.
2434 return UnknownValue;
2435}
2436
2437/// getSCEVAtScope - Compute the value of the specified expression within the
2438/// indicated loop (which may be null to indicate in no loop). If the
2439/// expression cannot be evaluated, return UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002440SCEVHandle ScalarEvolution::getSCEVAtScope(SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002441 // FIXME: this should be turned into a virtual method on SCEV!
2442
2443 if (isa<SCEVConstant>(V)) return V;
2444
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002445 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002446 // exit value from the loop without using SCEVs.
2447 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2448 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002449 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002450 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2451 if (PHINode *PN = dyn_cast<PHINode>(I))
2452 if (PN->getParent() == LI->getHeader()) {
2453 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002454 // to see if the loop that contains it has a known backedge-taken
2455 // count. If so, we may be able to force computation of the exit
2456 // value.
2457 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2458 if (SCEVConstant *BTCC =
2459 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002460 // Okay, we know how many times the containing loop executes. If
2461 // this is a constant evolving PHI node, get the final value at
2462 // the specified iteration number.
2463 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002464 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002465 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002466 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002467 }
2468 }
2469
2470 // Okay, this is an expression that we cannot symbolically evaluate
2471 // into a SCEV. Check to see if it's possible to symbolically evaluate
2472 // the arguments into constants, and if so, try to constant propagate the
2473 // result. This is particularly useful for computing loop exit values.
2474 if (CanConstantFold(I)) {
2475 std::vector<Constant*> Operands;
2476 Operands.reserve(I->getNumOperands());
2477 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2478 Value *Op = I->getOperand(i);
2479 if (Constant *C = dyn_cast<Constant>(Op)) {
2480 Operands.push_back(C);
2481 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002482 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00002483 // non-integer and non-pointer, don't even try to analyze them
2484 // with scev techniques.
2485 if (!isa<IntegerType>(Op->getType()) &&
2486 !isa<PointerType>(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00002487 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002488
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002489 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2490 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2491 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2492 Op->getType(),
2493 false));
2494 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2495 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2496 Operands.push_back(ConstantExpr::getIntegerCast(C,
2497 Op->getType(),
2498 false));
2499 else
2500 return V;
2501 } else {
2502 return V;
2503 }
2504 }
2505 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002506
2507 Constant *C;
2508 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2509 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2510 &Operands[0], Operands.size());
2511 else
2512 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2513 &Operands[0], Operands.size());
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002514 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002515 }
2516 }
2517
2518 // This is some other type of SCEVUnknown, just return it.
2519 return V;
2520 }
2521
2522 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2523 // Avoid performing the look-up in the common case where the specified
2524 // expression has no loop-variant portions.
2525 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2526 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2527 if (OpAtScope != Comm->getOperand(i)) {
2528 if (OpAtScope == UnknownValue) return UnknownValue;
2529 // Okay, at least one of these operands is loop variant but might be
2530 // foldable. Build a new instance of the folded commutative expression.
2531 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2532 NewOps.push_back(OpAtScope);
2533
2534 for (++i; i != e; ++i) {
2535 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2536 if (OpAtScope == UnknownValue) return UnknownValue;
2537 NewOps.push_back(OpAtScope);
2538 }
2539 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002540 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002541 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002542 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002543 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002544 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002545 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002546 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002547 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002548 }
2549 }
2550 // If we got here, all operands are loop invariant.
2551 return Comm;
2552 }
2553
Nick Lewycky35b56022009-01-13 09:18:58 +00002554 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2555 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002556 if (LHS == UnknownValue) return LHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002557 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002558 if (RHS == UnknownValue) return RHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002559 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2560 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002561 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002562 }
2563
2564 // If this is a loop recurrence for a loop that does not contain L, then we
2565 // are dealing with the final value computed by the loop.
2566 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2567 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2568 // To evaluate this recurrence, we need to know how many times the AddRec
2569 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002570 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2571 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002572
Eli Friedman7489ec92008-08-04 23:49:06 +00002573 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002574 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002575 }
2576 return UnknownValue;
2577 }
2578
2579 //assert(0 && "Unknown SCEV type!");
2580 return UnknownValue;
2581}
2582
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002583/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2584/// at the specified scope in the program. The L value specifies a loop
2585/// nest to evaluate the expression at, where null is the top-level or a
2586/// specified loop is immediately inside of the loop.
2587///
2588/// This method can be used to compute the exit value for a variable defined
2589/// in a loop by querying what the value will hold in the parent loop.
2590///
2591/// If this value is not computable at this scope, a SCEVCouldNotCompute
2592/// object is returned.
2593SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2594 return getSCEVAtScope(getSCEV(V), L);
2595}
2596
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002597/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2598/// following equation:
2599///
2600/// A * X = B (mod N)
2601///
2602/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2603/// A and B isn't important.
2604///
2605/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2606static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2607 ScalarEvolution &SE) {
2608 uint32_t BW = A.getBitWidth();
2609 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2610 assert(A != 0 && "A must be non-zero.");
2611
2612 // 1. D = gcd(A, N)
2613 //
2614 // The gcd of A and N may have only one prime factor: 2. The number of
2615 // trailing zeros in A is its multiplicity
2616 uint32_t Mult2 = A.countTrailingZeros();
2617 // D = 2^Mult2
2618
2619 // 2. Check if B is divisible by D.
2620 //
2621 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2622 // is not less than multiplicity of this prime factor for D.
2623 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00002624 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002625
2626 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2627 // modulo (N / D).
2628 //
2629 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2630 // bit width during computations.
2631 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2632 APInt Mod(BW + 1, 0);
2633 Mod.set(BW - Mult2); // Mod = N / D
2634 APInt I = AD.multiplicativeInverse(Mod);
2635
2636 // 4. Compute the minimum unsigned root of the equation:
2637 // I * (B / D) mod (N / D)
2638 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2639
2640 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2641 // bits.
2642 return SE.getConstant(Result.trunc(BW));
2643}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002644
2645/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2646/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2647/// might be the same) or two SCEVCouldNotCompute objects.
2648///
2649static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00002650SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002651 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2652 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2653 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2654 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2655
2656 // We currently can only solve this if the coefficients are constants.
2657 if (!LC || !MC || !NC) {
Dan Gohman0ad08b02009-04-18 17:58:19 +00002658 SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002659 return std::make_pair(CNC, CNC);
2660 }
2661
2662 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2663 const APInt &L = LC->getValue()->getValue();
2664 const APInt &M = MC->getValue()->getValue();
2665 const APInt &N = NC->getValue()->getValue();
2666 APInt Two(BitWidth, 2);
2667 APInt Four(BitWidth, 4);
2668
2669 {
2670 using namespace APIntOps;
2671 const APInt& C = L;
2672 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2673 // The B coefficient is M-N/2
2674 APInt B(M);
2675 B -= sdiv(N,Two);
2676
2677 // The A coefficient is N/2
2678 APInt A(N.sdiv(Two));
2679
2680 // Compute the B^2-4ac term.
2681 APInt SqrtTerm(B);
2682 SqrtTerm *= B;
2683 SqrtTerm -= Four * (A * C);
2684
2685 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2686 // integer value or else APInt::sqrt() will assert.
2687 APInt SqrtVal(SqrtTerm.sqrt());
2688
2689 // Compute the two solutions for the quadratic formula.
2690 // The divisions must be performed as signed divisions.
2691 APInt NegB(-B);
2692 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00002693 if (TwoA.isMinValue()) {
Dan Gohman0ad08b02009-04-18 17:58:19 +00002694 SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00002695 return std::make_pair(CNC, CNC);
2696 }
2697
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002698 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2699 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2700
Dan Gohman89f85052007-10-22 18:31:58 +00002701 return std::make_pair(SE.getConstant(Solution1),
2702 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002703 } // end APIntOps namespace
2704}
2705
2706/// HowFarToZero - Return the number of times a backedge comparing the specified
2707/// value to zero will execute. If not computable, return UnknownValue
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002708SCEVHandle ScalarEvolution::HowFarToZero(SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002709 // If the value is a constant
2710 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2711 // If the value is already zero, the branch will execute zero times.
2712 if (C->getValue()->isZero()) return C;
2713 return UnknownValue; // Otherwise it will loop infinitely.
2714 }
2715
2716 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2717 if (!AddRec || AddRec->getLoop() != L)
2718 return UnknownValue;
2719
2720 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002721 // If this is an affine expression, the execution count of this branch is
2722 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002723 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002724 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002725 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002726 // equivalent to:
2727 //
2728 // Step*N = -Start (mod 2^BW)
2729 //
2730 // where BW is the common bit width of Start and Step.
2731
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002732 // Get the initial value for the loop.
2733 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2734 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002735
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002736 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002737
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002738 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002739 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002740
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002741 // First, handle unitary steps.
2742 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002743 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002744 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2745 return Start; // N = Start (as unsigned)
2746
2747 // Then, try to solve the above equation provided that Start is constant.
2748 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2749 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002750 -StartC->getValue()->getValue(),
2751 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002752 }
2753 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2754 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2755 // the quadratic equation to solve it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002756 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
2757 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002758 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2759 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2760 if (R1) {
2761#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002762 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
2763 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002764#endif
2765 // Pick the smallest positive root value.
2766 if (ConstantInt *CB =
2767 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2768 R1->getValue(), R2->getValue()))) {
2769 if (CB->getZExtValue() == false)
2770 std::swap(R1, R2); // R1 is the minimum root now.
2771
2772 // We can only use this value if the chrec ends up with an exact zero
2773 // value at this index. When solving for "X*X != 5", for example, we
2774 // should not accept a root of 2.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002775 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00002776 if (Val->isZero())
2777 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002778 }
2779 }
2780 }
2781
2782 return UnknownValue;
2783}
2784
2785/// HowFarToNonZero - Return the number of times a backedge checking the
2786/// specified value for nonzero will execute. If not computable, return
2787/// UnknownValue
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002788SCEVHandle ScalarEvolution::HowFarToNonZero(SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002789 // Loops that look like: while (X == 0) are very strange indeed. We don't
2790 // handle them yet except for the trivial case. This could be expanded in the
2791 // future as needed.
2792
2793 // If the value is a constant, check to see if it is known to be non-zero
2794 // already. If so, the backedge will execute zero times.
2795 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00002796 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002797 return getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002798 return UnknownValue; // Otherwise it will loop infinitely.
2799 }
2800
2801 // We could implement others, but I really doubt anyone writes loops like
2802 // this, and if they did, they would already be constant folded.
2803 return UnknownValue;
2804}
2805
Dan Gohman1cddf972008-09-15 22:18:04 +00002806/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2807/// (which may not be an immediate predecessor) which has exactly one
2808/// successor from which BB is reachable, or null if no such block is
2809/// found.
2810///
2811BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002812ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1cddf972008-09-15 22:18:04 +00002813 // If the block has a unique predecessor, the predecessor must have
2814 // no other successors from which BB is reachable.
2815 if (BasicBlock *Pred = BB->getSinglePredecessor())
2816 return Pred;
2817
2818 // A loop's header is defined to be a block that dominates the loop.
2819 // If the loop has a preheader, it must be a block that has exactly
2820 // one successor that can reach BB. This is slightly more strict
2821 // than necessary, but works if critical edges are split.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002822 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman1cddf972008-09-15 22:18:04 +00002823 return L->getLoopPreheader();
2824
2825 return 0;
2826}
2827
Dan Gohmancacd2012009-02-12 22:19:27 +00002828/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002829/// a conditional between LHS and RHS.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002830bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohmancacd2012009-02-12 22:19:27 +00002831 ICmpInst::Predicate Pred,
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002832 SCEV *LHS, SCEV *RHS) {
2833 BasicBlock *Preheader = L->getLoopPreheader();
2834 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002835
Dan Gohmanab678fb2008-08-12 20:17:31 +00002836 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohman1cddf972008-09-15 22:18:04 +00002837 // there are predecessors that can be found that have unique successors
2838 // leading to the original header.
2839 for (; Preheader;
2840 PreheaderDest = Preheader,
2841 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00002842
2843 BranchInst *LoopEntryPredicate =
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002844 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00002845 if (!LoopEntryPredicate ||
2846 LoopEntryPredicate->isUnconditional())
2847 continue;
2848
2849 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2850 if (!ICI) continue;
2851
2852 // Now that we found a conditional branch that dominates the loop, check to
2853 // see if it is the comparison we are looking for.
2854 Value *PreCondLHS = ICI->getOperand(0);
2855 Value *PreCondRHS = ICI->getOperand(1);
2856 ICmpInst::Predicate Cond;
2857 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2858 Cond = ICI->getPredicate();
2859 else
2860 Cond = ICI->getInversePredicate();
2861
Dan Gohmancacd2012009-02-12 22:19:27 +00002862 if (Cond == Pred)
2863 ; // An exact match.
2864 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
2865 ; // The actual condition is beyond sufficient.
2866 else
2867 // Check a few special cases.
2868 switch (Cond) {
2869 case ICmpInst::ICMP_UGT:
2870 if (Pred == ICmpInst::ICMP_ULT) {
2871 std::swap(PreCondLHS, PreCondRHS);
2872 Cond = ICmpInst::ICMP_ULT;
2873 break;
2874 }
2875 continue;
2876 case ICmpInst::ICMP_SGT:
2877 if (Pred == ICmpInst::ICMP_SLT) {
2878 std::swap(PreCondLHS, PreCondRHS);
2879 Cond = ICmpInst::ICMP_SLT;
2880 break;
2881 }
2882 continue;
2883 case ICmpInst::ICMP_NE:
2884 // Expressions like (x >u 0) are often canonicalized to (x != 0),
2885 // so check for this case by checking if the NE is comparing against
2886 // a minimum or maximum constant.
2887 if (!ICmpInst::isTrueWhenEqual(Pred))
2888 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
2889 const APInt &A = CI->getValue();
2890 switch (Pred) {
2891 case ICmpInst::ICMP_SLT:
2892 if (A.isMaxSignedValue()) break;
2893 continue;
2894 case ICmpInst::ICMP_SGT:
2895 if (A.isMinSignedValue()) break;
2896 continue;
2897 case ICmpInst::ICMP_ULT:
2898 if (A.isMaxValue()) break;
2899 continue;
2900 case ICmpInst::ICMP_UGT:
2901 if (A.isMinValue()) break;
2902 continue;
2903 default:
2904 continue;
2905 }
2906 Cond = ICmpInst::ICMP_NE;
2907 // NE is symmetric but the original comparison may not be. Swap
2908 // the operands if necessary so that they match below.
2909 if (isa<SCEVConstant>(LHS))
2910 std::swap(PreCondLHS, PreCondRHS);
2911 break;
2912 }
2913 continue;
2914 default:
2915 // We weren't able to reconcile the condition.
2916 continue;
2917 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00002918
2919 if (!PreCondLHS->getType()->isInteger()) continue;
2920
2921 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
2922 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
2923 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002924 (LHS == getNotSCEV(PreCondRHSSCEV) &&
2925 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohmanab678fb2008-08-12 20:17:31 +00002926 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002927 }
2928
Dan Gohmanab678fb2008-08-12 20:17:31 +00002929 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002930}
2931
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002932/// HowManyLessThans - Return the number of times a backedge containing the
2933/// specified less-than comparison will execute. If not computable, return
2934/// UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002935SCEVHandle ScalarEvolution::
Nick Lewycky35b56022009-01-13 09:18:58 +00002936HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002937 // Only handle: "ADDREC < LoopInvariant".
2938 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2939
2940 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2941 if (!AddRec || AddRec->getLoop() != L)
2942 return UnknownValue;
2943
2944 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00002945 // FORNOW: We only support unit strides.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002946 SCEVHandle One = getIntegerSCEV(1, RHS->getType());
Nick Lewycky35b56022009-01-13 09:18:58 +00002947 if (AddRec->getOperand(1) != One)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002948 return UnknownValue;
2949
Nick Lewycky35b56022009-01-13 09:18:58 +00002950 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
2951 // m. So, we count the number of iterations in which {n,+,1} < m is true.
2952 // Note that we cannot simply return max(m-n,0) because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00002953 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002954
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00002955 // First, we get the value of the LHS in the first iteration: n
2956 SCEVHandle Start = AddRec->getOperand(0);
2957
Dan Gohmancacd2012009-02-12 22:19:27 +00002958 if (isLoopGuardedByCond(L,
2959 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002960 getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
Nick Lewycky35b56022009-01-13 09:18:58 +00002961 // Since we know that the condition is true in order to enter the loop,
2962 // we know that it will run exactly m-n times.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002963 return getMinusSCEV(RHS, Start);
Nick Lewycky35b56022009-01-13 09:18:58 +00002964 } else {
2965 // Then, we get the value of the LHS in the first iteration in which the
2966 // above condition doesn't hold. This equals to max(m,n).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002967 SCEVHandle End = isSigned ? getSMaxExpr(RHS, Start)
2968 : getUMaxExpr(RHS, Start);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00002969
Nick Lewycky35b56022009-01-13 09:18:58 +00002970 // Finally, we subtract these two values to get the number of times the
2971 // backedge is executed: max(m,n)-n.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002972 return getMinusSCEV(End, Start);
Nick Lewycky64d1fff2008-12-16 08:30:01 +00002973 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002974 }
2975
2976 return UnknownValue;
2977}
2978
2979/// getNumIterationsInRange - Return the number of iterations of this loop that
2980/// produce values in the specified constant range. Another way of looking at
2981/// this is that it returns the first iteration number where the value is not in
2982/// the condition, thus computing the exit count. If the iteration count can't
2983/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00002984SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2985 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002986 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00002987 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002988
2989 // If the start is a non-zero constant, shift the range to simplify things.
2990 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2991 if (!SC->getValue()->isZero()) {
2992 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00002993 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2994 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002995 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2996 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00002997 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002998 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00002999 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003000 }
3001
3002 // The only time we can solve this is when we have all constant indices.
3003 // Otherwise, we cannot determine the overflow conditions.
3004 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3005 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003006 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003007
3008
3009 // Okay at this point we know that all elements of the chrec are constants and
3010 // that the start element is zero.
3011
3012 // First check to see if the range contains zero. If not, the first
3013 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003014 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003015 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003016 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003017
3018 if (isAffine()) {
3019 // If this is an affine expression then we have this situation:
3020 // Solve {0,+,A} in Range === Ax in Range
3021
3022 // We know that zero is in the range. If A is positive then we know that
3023 // the upper value of the range must be the first possible exit value.
3024 // If A is negative then the lower of the range is the last possible loop
3025 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003026 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003027 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3028 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3029
3030 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003031 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003032 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3033
3034 // Evaluate at the exit value. If we really did fall out of the valid
3035 // range, then we computed our trip count, otherwise wrap around or other
3036 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003037 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003038 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003039 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003040
3041 // Ensure that the previous value is in the range. This is a sanity check.
3042 assert(Range.contains(
3043 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003044 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003045 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003046 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003047 } else if (isQuadratic()) {
3048 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3049 // quadratic equation to solve it. To do this, we must frame our problem in
3050 // terms of figuring out when zero is crossed, instead of when
3051 // Range.getUpper() is crossed.
3052 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003053 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3054 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003055
3056 // Next, solve the constructed addrec
3057 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003058 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003059 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3060 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3061 if (R1) {
3062 // Pick the smallest positive root value.
3063 if (ConstantInt *CB =
3064 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3065 R1->getValue(), R2->getValue()))) {
3066 if (CB->getZExtValue() == false)
3067 std::swap(R1, R2); // R1 is the minimum root now.
3068
3069 // Make sure the root is not off by one. The returned iteration should
3070 // not be in the range, but the previous one should be. When solving
3071 // for "X*X < 5", for example, we should not return a root of 2.
3072 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003073 R1->getValue(),
3074 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003075 if (Range.contains(R1Val->getValue())) {
3076 // The next iteration must be out of the range...
3077 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3078
Dan Gohman89f85052007-10-22 18:31:58 +00003079 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003080 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003081 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003082 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003083 }
3084
3085 // If R1 was not in the range, then it is a good return value. Make
3086 // sure that R1-1 WAS in the range though, just in case.
3087 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003088 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003089 if (Range.contains(R1Val->getValue()))
3090 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003091 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003092 }
3093 }
3094 }
3095
Dan Gohman0ad08b02009-04-18 17:58:19 +00003096 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003097}
3098
3099
3100
3101//===----------------------------------------------------------------------===//
3102// ScalarEvolution Class Implementation
3103//===----------------------------------------------------------------------===//
3104
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003105ScalarEvolution::ScalarEvolution()
3106 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3107}
3108
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003109bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003110 this->F = &F;
3111 LI = &getAnalysis<LoopInfo>();
3112 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003113 return false;
3114}
3115
3116void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003117 Scalars.clear();
3118 BackedgeTakenCounts.clear();
3119 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003120}
3121
3122void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3123 AU.setPreservesAll();
3124 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003125}
3126
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003127bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003128 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003129}
3130
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003131static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003132 const Loop *L) {
3133 // Print all inner loops first
3134 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3135 PrintLoopInfo(OS, SE, *I);
3136
Nick Lewyckye5da1912008-01-02 02:49:20 +00003137 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003138
Devang Patel02451fa2007-08-21 00:31:24 +00003139 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003140 L->getExitBlocks(ExitBlocks);
3141 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003142 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003143
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003144 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3145 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003146 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003147 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003148 }
3149
Nick Lewyckye5da1912008-01-02 02:49:20 +00003150 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003151}
3152
Dan Gohman13058cc2009-04-21 00:47:46 +00003153void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003154 // ScalarEvolution's implementaiton of the print method is to print
3155 // out SCEV values of all instructions that are interesting. Doing
3156 // this potentially causes it to create new SCEV objects though,
3157 // which technically conflicts with the const qualifier. This isn't
3158 // observable from outside the class though (the hasSCEV function
3159 // notwithstanding), so casting away the const isn't dangerous.
3160 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003161
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003162 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003163 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3164 if (I->getType()->isInteger()) {
3165 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003166 OS << " --> ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003167 SCEVHandle SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003168 SV->print(OS);
3169 OS << "\t\t";
3170
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003171 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003172 OS << "Exits: ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003173 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003174 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3175 OS << "<<Unknown>>";
3176 } else {
3177 OS << *ExitValue;
3178 }
3179 }
3180
3181
3182 OS << "\n";
3183 }
3184
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003185 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3186 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3187 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003188}
Dan Gohman13058cc2009-04-21 00:47:46 +00003189
3190void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3191 raw_os_ostream OS(o);
3192 print(OS, M);
3193}