blob: 75331fdab497dcd2d34c64dae726c304ff198210 [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
657 // If the input value is a chrec scev made out of constants, truncate
658 // all of the constants.
659 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
660 std::vector<SCEVHandle> Operands;
661 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
662 // FIXME: This should allow truncation of other expression types!
663 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman89f85052007-10-22 18:31:58 +0000664 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000665 else
666 break;
667 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman89f85052007-10-22 18:31:58 +0000668 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669 }
670
671 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
672 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
673 return Result;
674}
675
Dan Gohman36d40922009-04-16 19:25:55 +0000676SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
677 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000678 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000679 "This is not an extending conversion!");
680
Dan Gohman01c2ee72009-04-16 03:18:22 +0000681 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000682 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000683 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
684 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
685 return getUnknown(C);
686 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000687
688 // FIXME: If the input value is a chrec scev, and we can prove that the value
689 // did not overflow the old, smaller, value, we can zero extend all of the
690 // operands (often constants). This would allow analysis of something like
691 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
692
693 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
694 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
695 return Result;
696}
697
Dan Gohman89f85052007-10-22 18:31:58 +0000698SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000699 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000700 "This is not an extending conversion!");
701
Dan Gohman01c2ee72009-04-16 03:18:22 +0000702 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000703 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000704 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
705 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
706 return getUnknown(C);
707 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000708
709 // FIXME: If the input value is a chrec scev, and we can prove that the value
710 // did not overflow the old, smaller, value, we can sign extend all of the
711 // operands (often constants). This would allow analysis of something like
712 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
713
714 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
715 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
716 return Result;
717}
718
719// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000720SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000721 assert(!Ops.empty() && "Cannot get empty add!");
722 if (Ops.size() == 1) return Ops[0];
723
724 // Sort by complexity, this groups all similar expression types together.
725 GroupByComplexity(Ops);
726
727 // If there are any constants, fold them together.
728 unsigned Idx = 0;
729 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
730 ++Idx;
731 assert(Idx < Ops.size());
732 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
733 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000734 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
735 RHSC->getValue()->getValue());
736 Ops[0] = getConstant(Fold);
737 Ops.erase(Ops.begin()+1); // Erase the folded element
738 if (Ops.size() == 1) return Ops[0];
739 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000740 }
741
742 // If we are left with a constant zero being added, strip it off.
743 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
744 Ops.erase(Ops.begin());
745 --Idx;
746 }
747 }
748
749 if (Ops.size() == 1) return Ops[0];
750
751 // Okay, check to see if the same value occurs in the operand list twice. If
752 // so, merge them together into an multiply expression. Since we sorted the
753 // list, these values are required to be adjacent.
754 const Type *Ty = Ops[0]->getType();
755 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
756 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
757 // Found a match, merge the two values into a multiply, and add any
758 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000759 SCEVHandle Two = getIntegerSCEV(2, Ty);
760 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000761 if (Ops.size() == 2)
762 return Mul;
763 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
764 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000765 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000766 }
767
768 // Now we know the first non-constant operand. Skip past any cast SCEVs.
769 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
770 ++Idx;
771
772 // If there are add operands they would be next.
773 if (Idx < Ops.size()) {
774 bool DeletedAdd = false;
775 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
776 // If we have an add, expand the add operands onto the end of the operands
777 // list.
778 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
779 Ops.erase(Ops.begin()+Idx);
780 DeletedAdd = true;
781 }
782
783 // If we deleted at least one add, we added operands to the end of the list,
784 // and they are not necessarily sorted. Recurse to resort and resimplify
785 // any operands we just aquired.
786 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +0000787 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000788 }
789
790 // Skip over the add expression until we get to a multiply.
791 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
792 ++Idx;
793
794 // If we are adding something to a multiply expression, make sure the
795 // something is not already an operand of the multiply. If so, merge it into
796 // the multiply.
797 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
798 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
799 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
800 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
801 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
802 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
803 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
804 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
805 if (Mul->getNumOperands() != 2) {
806 // If the multiply has more than two operands, we must get the
807 // Y*Z term.
808 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
809 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000810 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000811 }
Dan Gohman89f85052007-10-22 18:31:58 +0000812 SCEVHandle One = getIntegerSCEV(1, Ty);
813 SCEVHandle AddOne = getAddExpr(InnerMul, One);
814 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000815 if (Ops.size() == 2) return OuterMul;
816 if (AddOp < Idx) {
817 Ops.erase(Ops.begin()+AddOp);
818 Ops.erase(Ops.begin()+Idx-1);
819 } else {
820 Ops.erase(Ops.begin()+Idx);
821 Ops.erase(Ops.begin()+AddOp-1);
822 }
823 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000824 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000825 }
826
827 // Check this multiply against other multiplies being added together.
828 for (unsigned OtherMulIdx = Idx+1;
829 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
830 ++OtherMulIdx) {
831 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
832 // If MulOp occurs in OtherMul, we can fold the two multiplies
833 // together.
834 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
835 OMulOp != e; ++OMulOp)
836 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
837 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
838 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
839 if (Mul->getNumOperands() != 2) {
840 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
841 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000842 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000843 }
844 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
845 if (OtherMul->getNumOperands() != 2) {
846 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
847 OtherMul->op_end());
848 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000849 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000850 }
Dan Gohman89f85052007-10-22 18:31:58 +0000851 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
852 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000853 if (Ops.size() == 2) return OuterMul;
854 Ops.erase(Ops.begin()+Idx);
855 Ops.erase(Ops.begin()+OtherMulIdx-1);
856 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000857 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000858 }
859 }
860 }
861 }
862
863 // If there are any add recurrences in the operands list, see if any other
864 // added values are loop invariant. If so, we can fold them into the
865 // recurrence.
866 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
867 ++Idx;
868
869 // Scan over all recurrences, trying to fold loop invariants into them.
870 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
871 // Scan all of the other operands to this add and add them to the vector if
872 // they are loop invariant w.r.t. the recurrence.
873 std::vector<SCEVHandle> LIOps;
874 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
875 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
876 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
877 LIOps.push_back(Ops[i]);
878 Ops.erase(Ops.begin()+i);
879 --i; --e;
880 }
881
882 // If we found some loop invariants, fold them into the recurrence.
883 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +0000884 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000885 LIOps.push_back(AddRec->getStart());
886
887 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +0000888 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000889
Dan Gohman89f85052007-10-22 18:31:58 +0000890 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000891 // If all of the other operands were loop invariant, we are done.
892 if (Ops.size() == 1) return NewRec;
893
894 // Otherwise, add the folded AddRec by the non-liv parts.
895 for (unsigned i = 0;; ++i)
896 if (Ops[i] == AddRec) {
897 Ops[i] = NewRec;
898 break;
899 }
Dan Gohman89f85052007-10-22 18:31:58 +0000900 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000901 }
902
903 // Okay, if there weren't any loop invariants to be folded, check to see if
904 // there are multiple AddRec's with the same loop induction variable being
905 // added together. If so, we can fold them.
906 for (unsigned OtherIdx = Idx+1;
907 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
908 if (OtherIdx != Idx) {
909 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
910 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
911 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
912 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
913 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
914 if (i >= NewOps.size()) {
915 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
916 OtherAddRec->op_end());
917 break;
918 }
Dan Gohman89f85052007-10-22 18:31:58 +0000919 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000920 }
Dan Gohman89f85052007-10-22 18:31:58 +0000921 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000922
923 if (Ops.size() == 2) return NewAddRec;
924
925 Ops.erase(Ops.begin()+Idx);
926 Ops.erase(Ops.begin()+OtherIdx-1);
927 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +0000928 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000929 }
930 }
931
932 // Otherwise couldn't fold anything into this recurrence. Move onto the
933 // next one.
934 }
935
936 // Okay, it looks like we really DO need an add expr. Check to see if we
937 // already have one, otherwise create a new one.
938 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
939 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
940 SCEVOps)];
941 if (Result == 0) Result = new SCEVAddExpr(Ops);
942 return Result;
943}
944
945
Dan Gohman89f85052007-10-22 18:31:58 +0000946SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000947 assert(!Ops.empty() && "Cannot get empty mul!");
948
949 // Sort by complexity, this groups all similar expression types together.
950 GroupByComplexity(Ops);
951
952 // If there are any constants, fold them together.
953 unsigned Idx = 0;
954 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
955
956 // C1*(C2+V) -> C1*C2 + C1*V
957 if (Ops.size() == 2)
958 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
959 if (Add->getNumOperands() == 2 &&
960 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +0000961 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
962 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000963
964
965 ++Idx;
966 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
967 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000968 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
969 RHSC->getValue()->getValue());
970 Ops[0] = getConstant(Fold);
971 Ops.erase(Ops.begin()+1); // Erase the folded element
972 if (Ops.size() == 1) return Ops[0];
973 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000974 }
975
976 // If we are left with a constant one being multiplied, strip it off.
977 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
978 Ops.erase(Ops.begin());
979 --Idx;
980 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
981 // If we have a multiply of zero, it will always be zero.
982 return Ops[0];
983 }
984 }
985
986 // Skip over the add expression until we get to a multiply.
987 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
988 ++Idx;
989
990 if (Ops.size() == 1)
991 return Ops[0];
992
993 // If there are mul operands inline them all into this expression.
994 if (Idx < Ops.size()) {
995 bool DeletedMul = false;
996 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
997 // If we have an mul, expand the mul operands onto the end of the operands
998 // list.
999 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1000 Ops.erase(Ops.begin()+Idx);
1001 DeletedMul = true;
1002 }
1003
1004 // If we deleted at least one mul, we added operands to the end of the list,
1005 // and they are not necessarily sorted. Recurse to resort and resimplify
1006 // any operands we just aquired.
1007 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001008 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001009 }
1010
1011 // If there are any add recurrences in the operands list, see if any other
1012 // added values are loop invariant. If so, we can fold them into the
1013 // recurrence.
1014 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1015 ++Idx;
1016
1017 // Scan over all recurrences, trying to fold loop invariants into them.
1018 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1019 // Scan all of the other operands to this mul and add them to the vector if
1020 // they are loop invariant w.r.t. the recurrence.
1021 std::vector<SCEVHandle> LIOps;
1022 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1023 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1024 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1025 LIOps.push_back(Ops[i]);
1026 Ops.erase(Ops.begin()+i);
1027 --i; --e;
1028 }
1029
1030 // If we found some loop invariants, fold them into the recurrence.
1031 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001032 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001033 std::vector<SCEVHandle> NewOps;
1034 NewOps.reserve(AddRec->getNumOperands());
1035 if (LIOps.size() == 1) {
1036 SCEV *Scale = LIOps[0];
1037 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001038 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001039 } else {
1040 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1041 std::vector<SCEVHandle> MulOps(LIOps);
1042 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001043 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001044 }
1045 }
1046
Dan Gohman89f85052007-10-22 18:31:58 +00001047 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001048
1049 // If all of the other operands were loop invariant, we are done.
1050 if (Ops.size() == 1) return NewRec;
1051
1052 // Otherwise, multiply the folded AddRec by the non-liv parts.
1053 for (unsigned i = 0;; ++i)
1054 if (Ops[i] == AddRec) {
1055 Ops[i] = NewRec;
1056 break;
1057 }
Dan Gohman89f85052007-10-22 18:31:58 +00001058 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059 }
1060
1061 // Okay, if there weren't any loop invariants to be folded, check to see if
1062 // there are multiple AddRec's with the same loop induction variable being
1063 // multiplied together. If so, we can fold them.
1064 for (unsigned OtherIdx = Idx+1;
1065 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1066 if (OtherIdx != Idx) {
1067 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1068 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1069 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1070 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001071 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001072 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001073 SCEVHandle B = F->getStepRecurrence(*this);
1074 SCEVHandle D = G->getStepRecurrence(*this);
1075 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1076 getMulExpr(G, B),
1077 getMulExpr(B, D));
1078 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1079 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001080 if (Ops.size() == 2) return NewAddRec;
1081
1082 Ops.erase(Ops.begin()+Idx);
1083 Ops.erase(Ops.begin()+OtherIdx-1);
1084 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001085 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001086 }
1087 }
1088
1089 // Otherwise couldn't fold anything into this recurrence. Move onto the
1090 // next one.
1091 }
1092
1093 // Okay, it looks like we really DO need an mul expr. Check to see if we
1094 // already have one, otherwise create a new one.
1095 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1096 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1097 SCEVOps)];
1098 if (Result == 0)
1099 Result = new SCEVMulExpr(Ops);
1100 return Result;
1101}
1102
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001103SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001104 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1105 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001106 return LHS; // X udiv 1 --> x
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001107
1108 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1109 Constant *LHSCV = LHSC->getValue();
1110 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001111 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001112 }
1113 }
1114
Nick Lewycky35b56022009-01-13 09:18:58 +00001115 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1116
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001117 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1118 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001119 return Result;
1120}
1121
1122
1123/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1124/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001125SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001126 const SCEVHandle &Step, const Loop *L) {
1127 std::vector<SCEVHandle> Operands;
1128 Operands.push_back(Start);
1129 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1130 if (StepChrec->getLoop() == L) {
1131 Operands.insert(Operands.end(), StepChrec->op_begin(),
1132 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001133 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001134 }
1135
1136 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001137 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001138}
1139
1140/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1141/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001142SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001143 const Loop *L) {
1144 if (Operands.size() == 1) return Operands[0];
1145
Dan Gohman7b560c42008-06-18 16:23:07 +00001146 if (Operands.back()->isZero()) {
1147 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001148 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001149 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001150
Dan Gohman42936882008-08-08 18:33:12 +00001151 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1152 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1153 const Loop* NestedLoop = NestedAR->getLoop();
1154 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1155 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1156 NestedAR->op_end());
1157 SCEVHandle NestedARHandle(NestedAR);
1158 Operands[0] = NestedAR->getStart();
1159 NestedOperands[0] = getAddRecExpr(Operands, L);
1160 return getAddRecExpr(NestedOperands, NestedLoop);
1161 }
1162 }
1163
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001164 SCEVAddRecExpr *&Result =
1165 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1166 Operands.end()))];
1167 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1168 return Result;
1169}
1170
Nick Lewycky711640a2007-11-25 22:41:31 +00001171SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1172 const SCEVHandle &RHS) {
1173 std::vector<SCEVHandle> Ops;
1174 Ops.push_back(LHS);
1175 Ops.push_back(RHS);
1176 return getSMaxExpr(Ops);
1177}
1178
1179SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1180 assert(!Ops.empty() && "Cannot get empty smax!");
1181 if (Ops.size() == 1) return Ops[0];
1182
1183 // Sort by complexity, this groups all similar expression types together.
1184 GroupByComplexity(Ops);
1185
1186 // If there are any constants, fold them together.
1187 unsigned Idx = 0;
1188 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1189 ++Idx;
1190 assert(Idx < Ops.size());
1191 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1192 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001193 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001194 APIntOps::smax(LHSC->getValue()->getValue(),
1195 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001196 Ops[0] = getConstant(Fold);
1197 Ops.erase(Ops.begin()+1); // Erase the folded element
1198 if (Ops.size() == 1) return Ops[0];
1199 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001200 }
1201
1202 // If we are left with a constant -inf, strip it off.
1203 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1204 Ops.erase(Ops.begin());
1205 --Idx;
1206 }
1207 }
1208
1209 if (Ops.size() == 1) return Ops[0];
1210
1211 // Find the first SMax
1212 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1213 ++Idx;
1214
1215 // Check to see if one of the operands is an SMax. If so, expand its operands
1216 // onto our operand list, and recurse to simplify.
1217 if (Idx < Ops.size()) {
1218 bool DeletedSMax = false;
1219 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1220 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1221 Ops.erase(Ops.begin()+Idx);
1222 DeletedSMax = true;
1223 }
1224
1225 if (DeletedSMax)
1226 return getSMaxExpr(Ops);
1227 }
1228
1229 // Okay, check to see if the same value occurs in the operand list twice. If
1230 // so, delete one. Since we sorted the list, these values are required to
1231 // be adjacent.
1232 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1233 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1234 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1235 --i; --e;
1236 }
1237
1238 if (Ops.size() == 1) return Ops[0];
1239
1240 assert(!Ops.empty() && "Reduced smax down to nothing!");
1241
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001242 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001243 // already have one, otherwise create a new one.
1244 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1245 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1246 SCEVOps)];
1247 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1248 return Result;
1249}
1250
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001251SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1252 const SCEVHandle &RHS) {
1253 std::vector<SCEVHandle> Ops;
1254 Ops.push_back(LHS);
1255 Ops.push_back(RHS);
1256 return getUMaxExpr(Ops);
1257}
1258
1259SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1260 assert(!Ops.empty() && "Cannot get empty umax!");
1261 if (Ops.size() == 1) return Ops[0];
1262
1263 // Sort by complexity, this groups all similar expression types together.
1264 GroupByComplexity(Ops);
1265
1266 // If there are any constants, fold them together.
1267 unsigned Idx = 0;
1268 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1269 ++Idx;
1270 assert(Idx < Ops.size());
1271 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1272 // We found two constants, fold them together!
1273 ConstantInt *Fold = ConstantInt::get(
1274 APIntOps::umax(LHSC->getValue()->getValue(),
1275 RHSC->getValue()->getValue()));
1276 Ops[0] = getConstant(Fold);
1277 Ops.erase(Ops.begin()+1); // Erase the folded element
1278 if (Ops.size() == 1) return Ops[0];
1279 LHSC = cast<SCEVConstant>(Ops[0]);
1280 }
1281
1282 // If we are left with a constant zero, strip it off.
1283 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1284 Ops.erase(Ops.begin());
1285 --Idx;
1286 }
1287 }
1288
1289 if (Ops.size() == 1) return Ops[0];
1290
1291 // Find the first UMax
1292 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1293 ++Idx;
1294
1295 // Check to see if one of the operands is a UMax. If so, expand its operands
1296 // onto our operand list, and recurse to simplify.
1297 if (Idx < Ops.size()) {
1298 bool DeletedUMax = false;
1299 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1300 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1301 Ops.erase(Ops.begin()+Idx);
1302 DeletedUMax = true;
1303 }
1304
1305 if (DeletedUMax)
1306 return getUMaxExpr(Ops);
1307 }
1308
1309 // Okay, check to see if the same value occurs in the operand list twice. If
1310 // so, delete one. Since we sorted the list, these values are required to
1311 // be adjacent.
1312 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1313 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1314 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1315 --i; --e;
1316 }
1317
1318 if (Ops.size() == 1) return Ops[0];
1319
1320 assert(!Ops.empty() && "Reduced umax down to nothing!");
1321
1322 // Okay, it looks like we really DO need a umax expr. Check to see if we
1323 // already have one, otherwise create a new one.
1324 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1325 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1326 SCEVOps)];
1327 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1328 return Result;
1329}
1330
Dan Gohman89f85052007-10-22 18:31:58 +00001331SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001332 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001333 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001334 if (isa<ConstantPointerNull>(V))
1335 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001336 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1337 if (Result == 0) Result = new SCEVUnknown(V);
1338 return Result;
1339}
1340
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001341//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001342// Basic SCEV Analysis and PHI Idiom Recognition Code
1343//
1344
1345/// deleteValueFromRecords - This method should be called by the
1346/// client before it removes an instruction from the program, to make sure
1347/// that no dangling references are left around.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001348void ScalarEvolution::deleteValueFromRecords(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349 SmallVector<Value *, 16> Worklist;
1350
1351 if (Scalars.erase(V)) {
1352 if (PHINode *PN = dyn_cast<PHINode>(V))
1353 ConstantEvolutionLoopExitValue.erase(PN);
1354 Worklist.push_back(V);
1355 }
1356
1357 while (!Worklist.empty()) {
1358 Value *VV = Worklist.back();
1359 Worklist.pop_back();
1360
1361 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1362 UI != UE; ++UI) {
1363 Instruction *Inst = cast<Instruction>(*UI);
1364 if (Scalars.erase(Inst)) {
1365 if (PHINode *PN = dyn_cast<PHINode>(VV))
1366 ConstantEvolutionLoopExitValue.erase(PN);
1367 Worklist.push_back(Inst);
1368 }
1369 }
1370 }
1371}
1372
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001373/// isSCEVable - Test if values of the given type are analyzable within
1374/// the SCEV framework. This primarily includes integer types, and it
1375/// can optionally include pointer types if the ScalarEvolution class
1376/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001377bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001378 // Integers are always SCEVable.
1379 if (Ty->isInteger())
1380 return true;
1381
1382 // Pointers are SCEVable if TargetData information is available
1383 // to provide pointer size information.
1384 if (isa<PointerType>(Ty))
1385 return TD != NULL;
1386
1387 // Otherwise it's not SCEVable.
1388 return false;
1389}
1390
1391/// getTypeSizeInBits - Return the size in bits of the specified type,
1392/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001393uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001394 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1395
1396 // If we have a TargetData, use it!
1397 if (TD)
1398 return TD->getTypeSizeInBits(Ty);
1399
1400 // Otherwise, we support only integer types.
1401 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1402 return Ty->getPrimitiveSizeInBits();
1403}
1404
1405/// getEffectiveSCEVType - Return a type with the same bitwidth as
1406/// the given type and which represents how SCEV will treat the given
1407/// type, for which isSCEVable must return true. For pointer types,
1408/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001409const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001410 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1411
1412 if (Ty->isInteger())
1413 return Ty;
1414
1415 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1416 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001417}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001418
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001419SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman0ad08b02009-04-18 17:58:19 +00001420 return UnknownValue;
1421}
1422
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001423/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1424/// expression and create a new one.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001425SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001426 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001427
1428 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1429 if (I != Scalars.end()) return I->second;
1430 SCEVHandle S = createSCEV(V);
1431 Scalars.insert(std::make_pair(V, S));
1432 return S;
1433}
1434
Dan Gohman01c2ee72009-04-16 03:18:22 +00001435/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1436/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001437SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1438 Ty = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001439 Constant *C;
1440 if (Val == 0)
1441 C = Constant::getNullValue(Ty);
1442 else if (Ty->isFloatingPoint())
1443 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1444 APFloat::IEEEdouble, Val));
1445 else
1446 C = ConstantInt::get(Ty, Val);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001447 return getUnknown(C);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001448}
1449
1450/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1451///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001452SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001453 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001454 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001455
1456 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001457 Ty = getEffectiveSCEVType(Ty);
1458 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001459}
1460
1461/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001462SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001463 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001464 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001465
1466 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001467 Ty = getEffectiveSCEVType(Ty);
1468 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001469 return getMinusSCEV(AllOnes, V);
1470}
1471
1472/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1473///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001474SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Dan Gohman01c2ee72009-04-16 03:18:22 +00001475 const SCEVHandle &RHS) {
1476 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001477 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001478}
1479
1480/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1481/// input value to the specified type. If the type must be extended, it is zero
1482/// extended.
1483SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001484ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Dan Gohman01c2ee72009-04-16 03:18:22 +00001485 const Type *Ty) {
1486 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001487 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1488 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001489 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001490 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001491 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001492 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001493 return getTruncateExpr(V, Ty);
1494 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001495}
1496
1497/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1498/// input value to the specified type. If the type must be extended, it is sign
1499/// extended.
1500SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001501ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Dan Gohman01c2ee72009-04-16 03:18:22 +00001502 const Type *Ty) {
1503 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001504 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1505 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001506 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001507 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001508 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001509 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001510 return getTruncateExpr(V, Ty);
1511 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001512}
1513
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001514/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1515/// the specified instruction and replaces any references to the symbolic value
1516/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001517void ScalarEvolution::
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001518ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1519 const SCEVHandle &NewVal) {
1520 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1521 if (SI == Scalars.end()) return;
1522
1523 SCEVHandle NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001524 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001525 if (NV == SI->second) return; // No change.
1526
1527 SI->second = NV; // Update the scalars map!
1528
1529 // Any instruction values that use this instruction might also need to be
1530 // updated!
1531 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1532 UI != E; ++UI)
1533 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1534}
1535
1536/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1537/// a loop header, making it a potential recurrence, or it doesn't.
1538///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001539SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001540 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001541 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001542 if (L->getHeader() == PN->getParent()) {
1543 // If it lives in the loop header, it has two incoming values, one
1544 // from outside the loop, and one from inside.
1545 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1546 unsigned BackEdge = IncomingEdge^1;
1547
1548 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001549 SCEVHandle SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001550 assert(Scalars.find(PN) == Scalars.end() &&
1551 "PHI node already processed?");
1552 Scalars.insert(std::make_pair(PN, SymbolicName));
1553
1554 // Using this symbolic name for the PHI, analyze the value coming around
1555 // the back-edge.
1556 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1557
1558 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1559 // has a special value for the first iteration of the loop.
1560
1561 // If the value coming around the backedge is an add with the symbolic
1562 // value we just inserted, then we found a simple induction variable!
1563 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1564 // If there is a single occurrence of the symbolic value, replace it
1565 // with a recurrence.
1566 unsigned FoundIndex = Add->getNumOperands();
1567 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1568 if (Add->getOperand(i) == SymbolicName)
1569 if (FoundIndex == e) {
1570 FoundIndex = i;
1571 break;
1572 }
1573
1574 if (FoundIndex != Add->getNumOperands()) {
1575 // Create an add with everything but the specified operand.
1576 std::vector<SCEVHandle> Ops;
1577 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1578 if (i != FoundIndex)
1579 Ops.push_back(Add->getOperand(i));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001580 SCEVHandle Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001581
1582 // This is not a valid addrec if the step amount is varying each
1583 // loop iteration, but is not itself an addrec in this loop.
1584 if (Accum->isLoopInvariant(L) ||
1585 (isa<SCEVAddRecExpr>(Accum) &&
1586 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1587 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001588 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001589
1590 // Okay, for the entire analysis of this edge we assumed the PHI
1591 // to be symbolic. We now need to go back and update all of the
1592 // entries for the scalars that use the PHI (except for the PHI
1593 // itself) to use the new analyzed value instead of the "symbolic"
1594 // value.
1595 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1596 return PHISCEV;
1597 }
1598 }
1599 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1600 // Otherwise, this could be a loop like this:
1601 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1602 // In this case, j = {1,+,1} and BEValue is j.
1603 // Because the other in-value of i (0) fits the evolution of BEValue
1604 // i really is an addrec evolution.
1605 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1606 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1607
1608 // If StartVal = j.start - j.stride, we can use StartVal as the
1609 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001610 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00001611 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001612 SCEVHandle PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001613 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001614
1615 // Okay, for the entire analysis of this edge we assumed the PHI
1616 // to be symbolic. We now need to go back and update all of the
1617 // entries for the scalars that use the PHI (except for the PHI
1618 // itself) to use the new analyzed value instead of the "symbolic"
1619 // value.
1620 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1621 return PHISCEV;
1622 }
1623 }
1624 }
1625
1626 return SymbolicName;
1627 }
1628
1629 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001630 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001631}
1632
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001633/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1634/// guaranteed to end in (at every loop iteration). It is, at the same time,
1635/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1636/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001637static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001638 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001639 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001640
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001641 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001642 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1643 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001644
1645 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001646 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1647 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1648 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001649 }
1650
1651 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001652 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1653 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1654 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001655 }
1656
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001657 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001658 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001659 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001660 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001661 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001662 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001663 }
1664
1665 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001666 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001667 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1668 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001669 for (unsigned i = 1, e = M->getNumOperands();
1670 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001671 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001672 BitWidth);
1673 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001674 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001675
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001676 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001677 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001678 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001679 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001680 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001681 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001682 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001683
Nick Lewycky711640a2007-11-25 22:41:31 +00001684 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1685 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001686 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00001687 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001688 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00001689 return MinOpRes;
1690 }
1691
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001692 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1693 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001694 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001695 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001696 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001697 return MinOpRes;
1698 }
1699
Nick Lewycky35b56022009-01-13 09:18:58 +00001700 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001701 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001702}
1703
1704/// createSCEV - We know that there is no SCEV for the specified value.
1705/// Analyze the expression.
1706///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001707SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001708 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001709 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001710
Dan Gohman3996f472008-06-22 19:56:46 +00001711 unsigned Opcode = Instruction::UserOp1;
1712 if (Instruction *I = dyn_cast<Instruction>(V))
1713 Opcode = I->getOpcode();
1714 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1715 Opcode = CE->getOpcode();
1716 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001717 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001718
Dan Gohman3996f472008-06-22 19:56:46 +00001719 User *U = cast<User>(V);
1720 switch (Opcode) {
1721 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001722 return getAddExpr(getSCEV(U->getOperand(0)),
1723 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001724 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001725 return getMulExpr(getSCEV(U->getOperand(0)),
1726 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001727 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001728 return getUDivExpr(getSCEV(U->getOperand(0)),
1729 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001730 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001731 return getMinusSCEV(getSCEV(U->getOperand(0)),
1732 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00001733 case Instruction::And:
1734 // For an expression like x&255 that merely masks off the high bits,
1735 // use zext(trunc(x)) as the SCEV expression.
1736 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1737 const APInt &A = CI->getValue();
1738 unsigned Ones = A.countTrailingOnes();
1739 if (APIntOps::isMask(Ones, A))
1740 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001741 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
1742 IntegerType::get(Ones)),
1743 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00001744 }
1745 break;
Dan Gohman3996f472008-06-22 19:56:46 +00001746 case Instruction::Or:
1747 // If the RHS of the Or is a constant, we may have something like:
1748 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1749 // optimizations will transparently handle this case.
1750 //
1751 // In order for this transformation to be safe, the LHS must be of the
1752 // form X*(2^n) and the Or constant must be less than 2^n.
1753 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1754 SCEVHandle LHS = getSCEV(U->getOperand(0));
1755 const APInt &CIVal = CI->getValue();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001756 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman3996f472008-06-22 19:56:46 +00001757 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001758 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001759 }
Dan Gohman3996f472008-06-22 19:56:46 +00001760 break;
1761 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00001762 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00001763 // If the RHS of the xor is a signbit, then this is just an add.
1764 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00001765 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001766 return getAddExpr(getSCEV(U->getOperand(0)),
1767 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001768
1769 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman3996f472008-06-22 19:56:46 +00001770 else if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001771 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman3996f472008-06-22 19:56:46 +00001772 }
1773 break;
1774
1775 case Instruction::Shl:
1776 // Turn shift left of a constant amount into a multiply.
1777 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1778 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1779 Constant *X = ConstantInt::get(
1780 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001781 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00001782 }
1783 break;
1784
Nick Lewycky7fd27892008-07-07 06:15:49 +00001785 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00001786 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00001787 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1788 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1789 Constant *X = ConstantInt::get(
1790 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001791 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001792 }
1793 break;
1794
Dan Gohman53bf64a2009-04-21 02:26:00 +00001795 case Instruction::AShr:
1796 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
1797 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
1798 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
1799 if (L->getOpcode() == Instruction::Shl &&
1800 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman101a2672009-04-21 20:18:36 +00001801 uint64_t Amt = getTypeSizeInBits(U->getType()) - CI->getZExtValue();
Dan Gohman53bf64a2009-04-21 02:26:00 +00001802 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001803 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00001804 IntegerType::get(Amt)),
1805 U->getType());
1806 }
1807 break;
1808
Dan Gohman3996f472008-06-22 19:56:46 +00001809 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001810 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001811
1812 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001813 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001814
1815 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001816 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001817
1818 case Instruction::BitCast:
1819 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001820 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00001821 return getSCEV(U->getOperand(0));
1822 break;
1823
Dan Gohman01c2ee72009-04-16 03:18:22 +00001824 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001825 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001826 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001827 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00001828
1829 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001830 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001831 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1832 U->getType());
1833
1834 case Instruction::GetElementPtr: {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001835 if (!TD) break; // Without TD we can't analyze pointers.
1836 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001837 Value *Base = U->getOperand(0);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001838 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001839 gep_type_iterator GTI = gep_type_begin(U);
1840 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
1841 E = U->op_end();
1842 I != E; ++I) {
1843 Value *Index = *I;
1844 // Compute the (potentially symbolic) offset in bytes for this index.
1845 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1846 // For a struct, add the member offset.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001847 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001848 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1849 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001850 TotalOffset = getAddExpr(TotalOffset,
1851 getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001852 } else {
1853 // For an array, add the element offset, explicitly scaled.
1854 SCEVHandle LocalOffset = getSCEV(Index);
1855 if (!isa<PointerType>(LocalOffset->getType()))
1856 // Getelementptr indicies are signed.
1857 LocalOffset = getTruncateOrSignExtend(LocalOffset,
1858 IntPtrTy);
1859 LocalOffset =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001860 getMulExpr(LocalOffset,
1861 getIntegerSCEV(TD->getTypePaddedSize(*GTI),
1862 IntPtrTy));
1863 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001864 }
1865 }
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001866 return getAddExpr(getSCEV(Base), TotalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001867 }
1868
Dan Gohman3996f472008-06-22 19:56:46 +00001869 case Instruction::PHI:
1870 return createNodeForPHI(cast<PHINode>(U));
1871
1872 case Instruction::Select:
1873 // This could be a smax or umax that was lowered earlier.
1874 // Try to recover it.
1875 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1876 Value *LHS = ICI->getOperand(0);
1877 Value *RHS = ICI->getOperand(1);
1878 switch (ICI->getPredicate()) {
1879 case ICmpInst::ICMP_SLT:
1880 case ICmpInst::ICMP_SLE:
1881 std::swap(LHS, RHS);
1882 // fall through
1883 case ICmpInst::ICMP_SGT:
1884 case ICmpInst::ICMP_SGE:
1885 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001886 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00001887 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00001888 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001889 return getNotSCEV(getSMaxExpr(
1890 getNotSCEV(getSCEV(LHS)),
1891 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00001892 break;
1893 case ICmpInst::ICMP_ULT:
1894 case ICmpInst::ICMP_ULE:
1895 std::swap(LHS, RHS);
1896 // fall through
1897 case ICmpInst::ICMP_UGT:
1898 case ICmpInst::ICMP_UGE:
1899 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001900 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00001901 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1902 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001903 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
1904 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00001905 break;
1906 default:
1907 break;
1908 }
1909 }
1910
1911 default: // We cannot analyze this expression.
1912 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001913 }
1914
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001915 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001916}
1917
1918
1919
1920//===----------------------------------------------------------------------===//
1921// Iteration Count Computation Code
1922//
1923
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001924/// getBackedgeTakenCount - If the specified loop has a predictable
1925/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
1926/// object. The backedge-taken count is the number of times the loop header
1927/// will be branched to from within the loop. This is one less than the
1928/// trip count of the loop, since it doesn't count the first iteration,
1929/// when the header is branched to from outside the loop.
1930///
1931/// Note that it is not valid to call this method on a loop without a
1932/// loop-invariant backedge-taken count (see
1933/// hasLoopInvariantBackedgeTakenCount).
1934///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001935SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001936 std::map<const Loop*, SCEVHandle>::iterator I = BackedgeTakenCounts.find(L);
1937 if (I == BackedgeTakenCounts.end()) {
1938 SCEVHandle ItCount = ComputeBackedgeTakenCount(L);
1939 I = BackedgeTakenCounts.insert(std::make_pair(L, ItCount)).first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001940 if (ItCount != UnknownValue) {
1941 assert(ItCount->isLoopInvariant(L) &&
1942 "Computed trip count isn't loop invariant for loop!");
1943 ++NumTripCountsComputed;
1944 } else if (isa<PHINode>(L->getHeader()->begin())) {
1945 // Only count loops that have phi nodes as not being computable.
1946 ++NumTripCountsNotComputed;
1947 }
1948 }
1949 return I->second;
1950}
1951
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001952/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00001953/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001954/// ScalarEvolution's ability to compute a trip count, or if the loop
1955/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001956void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001957 BackedgeTakenCounts.erase(L);
Dan Gohmanf3a060a2009-02-17 20:49:49 +00001958}
1959
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001960/// ComputeBackedgeTakenCount - Compute the number of times the backedge
1961/// of the specified loop will execute.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001962SCEVHandle ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001963 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00001964 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001965 L->getExitBlocks(ExitBlocks);
1966 if (ExitBlocks.size() != 1) return UnknownValue;
1967
1968 // Okay, there is one exit block. Try to find the condition that causes the
1969 // loop to be exited.
1970 BasicBlock *ExitBlock = ExitBlocks[0];
1971
1972 BasicBlock *ExitingBlock = 0;
1973 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1974 PI != E; ++PI)
1975 if (L->contains(*PI)) {
1976 if (ExitingBlock == 0)
1977 ExitingBlock = *PI;
1978 else
1979 return UnknownValue; // More than one block exiting!
1980 }
1981 assert(ExitingBlock && "No exits from loop, something is broken!");
1982
1983 // Okay, we've computed the exiting block. See what condition causes us to
1984 // exit.
1985 //
1986 // FIXME: we should be able to handle switch instructions (with a single exit)
1987 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1988 if (ExitBr == 0) return UnknownValue;
1989 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1990
1991 // At this point, we know we have a conditional branch that determines whether
1992 // the loop is exited. However, we don't know if the branch is executed each
1993 // time through the loop. If not, then the execution count of the branch will
1994 // not be equal to the trip count of the loop.
1995 //
1996 // Currently we check for this by checking to see if the Exit branch goes to
1997 // the loop header. If so, we know it will always execute the same number of
1998 // times as the loop. We also handle the case where the exit block *is* the
1999 // loop header. This is common for un-rotated loops. More extensive analysis
2000 // could be done to handle more cases here.
2001 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2002 ExitBr->getSuccessor(1) != L->getHeader() &&
2003 ExitBr->getParent() != L->getHeader())
2004 return UnknownValue;
2005
2006 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2007
Nick Lewyckyb3d24332008-02-21 08:34:02 +00002008 // If it's not an integer comparison then compute it the hard way.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002009 // Note that ICmpInst deals with pointer comparisons too so we must check
2010 // the type of the operand.
2011 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002012 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002013 ExitBr->getSuccessor(0) == ExitBlock);
2014
2015 // If the condition was exit on true, convert the condition to exit on false
2016 ICmpInst::Predicate Cond;
2017 if (ExitBr->getSuccessor(1) == ExitBlock)
2018 Cond = ExitCond->getPredicate();
2019 else
2020 Cond = ExitCond->getInversePredicate();
2021
2022 // Handle common loops like: for (X = "string"; *X; ++X)
2023 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2024 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2025 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002026 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002027 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2028 }
2029
2030 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2031 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2032
2033 // Try to evaluate any dependencies out of the loop.
2034 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2035 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2036 Tmp = getSCEVAtScope(RHS, L);
2037 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2038
2039 // At this point, we would like to compute how many iterations of the
2040 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002041 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2042 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002043 std::swap(LHS, RHS);
2044 Cond = ICmpInst::getSwappedPredicate(Cond);
2045 }
2046
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002047 // If we have a comparison of a chrec against a constant, try to use value
2048 // ranges to answer this query.
2049 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2050 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2051 if (AddRec->getLoop() == L) {
2052 // Form the comparison range using the constant of the correct type so
2053 // that the ConstantRange class knows to do a signed or unsigned
2054 // comparison.
2055 ConstantInt *CompVal = RHSC->getValue();
2056 const Type *RealTy = ExitCond->getOperand(0)->getType();
2057 CompVal = dyn_cast<ConstantInt>(
2058 ConstantExpr::getBitCast(CompVal, RealTy));
2059 if (CompVal) {
2060 // Form the constant range.
2061 ConstantRange CompRange(
2062 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2063
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002064 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002065 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2066 }
2067 }
2068
2069 switch (Cond) {
2070 case ICmpInst::ICMP_NE: { // while (X != Y)
2071 // Convert to: while (X-Y != 0)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002072 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002073 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2074 break;
2075 }
2076 case ICmpInst::ICMP_EQ: {
2077 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002078 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002079 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2080 break;
2081 }
2082 case ICmpInst::ICMP_SLT: {
Nick Lewycky35b56022009-01-13 09:18:58 +00002083 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002084 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2085 break;
2086 }
2087 case ICmpInst::ICMP_SGT: {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002088 SCEVHandle TC = HowManyLessThans(getNotSCEV(LHS),
2089 getNotSCEV(RHS), L, true);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002090 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2091 break;
2092 }
2093 case ICmpInst::ICMP_ULT: {
Nick Lewycky35b56022009-01-13 09:18:58 +00002094 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002095 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2096 break;
2097 }
2098 case ICmpInst::ICMP_UGT: {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002099 SCEVHandle TC = HowManyLessThans(getNotSCEV(LHS),
2100 getNotSCEV(RHS), L, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002101 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2102 break;
2103 }
2104 default:
2105#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002106 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002107 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002108 errs() << "[unsigned] ";
2109 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002110 << Instruction::getOpcodeName(Instruction::ICmp)
2111 << " " << *RHS << "\n";
2112#endif
2113 break;
2114 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002115 return
2116 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2117 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002118}
2119
2120static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002121EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2122 ScalarEvolution &SE) {
2123 SCEVHandle InVal = SE.getConstant(C);
2124 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002125 assert(isa<SCEVConstant>(Val) &&
2126 "Evaluation of SCEV at constant didn't fold correctly?");
2127 return cast<SCEVConstant>(Val)->getValue();
2128}
2129
2130/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2131/// and a GEP expression (missing the pointer index) indexing into it, return
2132/// the addressed element of the initializer or null if the index expression is
2133/// invalid.
2134static Constant *
2135GetAddressedElementFromGlobal(GlobalVariable *GV,
2136 const std::vector<ConstantInt*> &Indices) {
2137 Constant *Init = GV->getInitializer();
2138 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2139 uint64_t Idx = Indices[i]->getZExtValue();
2140 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2141 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2142 Init = cast<Constant>(CS->getOperand(Idx));
2143 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2144 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2145 Init = cast<Constant>(CA->getOperand(Idx));
2146 } else if (isa<ConstantAggregateZero>(Init)) {
2147 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2148 assert(Idx < STy->getNumElements() && "Bad struct index!");
2149 Init = Constant::getNullValue(STy->getElementType(Idx));
2150 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2151 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2152 Init = Constant::getNullValue(ATy->getElementType());
2153 } else {
2154 assert(0 && "Unknown constant aggregate type!");
2155 }
2156 return 0;
2157 } else {
2158 return 0; // Unknown initializer type
2159 }
2160 }
2161 return Init;
2162}
2163
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002164/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2165/// 'icmp op load X, cst', try to see if we can compute the backedge
2166/// execution count.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002167SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002168ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2169 const Loop *L,
2170 ICmpInst::Predicate predicate) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002171 if (LI->isVolatile()) return UnknownValue;
2172
2173 // Check to see if the loaded pointer is a getelementptr of a global.
2174 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2175 if (!GEP) return UnknownValue;
2176
2177 // Make sure that it is really a constant global we are gepping, with an
2178 // initializer, and make sure the first IDX is really 0.
2179 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2180 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2181 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2182 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2183 return UnknownValue;
2184
2185 // Okay, we allow one non-constant index into the GEP instruction.
2186 Value *VarIdx = 0;
2187 std::vector<ConstantInt*> Indexes;
2188 unsigned VarIdxNum = 0;
2189 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2190 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2191 Indexes.push_back(CI);
2192 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2193 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2194 VarIdx = GEP->getOperand(i);
2195 VarIdxNum = i-2;
2196 Indexes.push_back(0);
2197 }
2198
2199 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2200 // Check to see if X is a loop variant variable value now.
2201 SCEVHandle Idx = getSCEV(VarIdx);
2202 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2203 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2204
2205 // We can only recognize very limited forms of loop index expressions, in
2206 // particular, only affine AddRec's like {C1,+,C2}.
2207 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2208 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2209 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2210 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2211 return UnknownValue;
2212
2213 unsigned MaxSteps = MaxBruteForceIterations;
2214 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2215 ConstantInt *ItCst =
2216 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002217 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002218
2219 // Form the GEP offset.
2220 Indexes[VarIdxNum] = Val;
2221
2222 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2223 if (Result == 0) break; // Cannot compute!
2224
2225 // Evaluate the condition for this iteration.
2226 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2227 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2228 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2229#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002230 errs() << "\n***\n*** Computed loop count " << *ItCst
2231 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2232 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002233#endif
2234 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002235 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002236 }
2237 }
2238 return UnknownValue;
2239}
2240
2241
2242/// CanConstantFold - Return true if we can constant fold an instruction of the
2243/// specified type, assuming that all operands were constants.
2244static bool CanConstantFold(const Instruction *I) {
2245 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2246 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2247 return true;
2248
2249 if (const CallInst *CI = dyn_cast<CallInst>(I))
2250 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002251 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002252 return false;
2253}
2254
2255/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2256/// in the loop that V is derived from. We allow arbitrary operations along the
2257/// way, but the operands of an operation must either be constants or a value
2258/// derived from a constant PHI. If this expression does not fit with these
2259/// constraints, return null.
2260static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2261 // If this is not an instruction, or if this is an instruction outside of the
2262 // loop, it can't be derived from a loop PHI.
2263 Instruction *I = dyn_cast<Instruction>(V);
2264 if (I == 0 || !L->contains(I->getParent())) return 0;
2265
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002266 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002267 if (L->getHeader() == I->getParent())
2268 return PN;
2269 else
2270 // We don't currently keep track of the control flow needed to evaluate
2271 // PHIs, so we cannot handle PHIs inside of loops.
2272 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002273 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002274
2275 // If we won't be able to constant fold this expression even if the operands
2276 // are constants, return early.
2277 if (!CanConstantFold(I)) return 0;
2278
2279 // Otherwise, we can evaluate this instruction if all of its operands are
2280 // constant or derived from a PHI node themselves.
2281 PHINode *PHI = 0;
2282 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2283 if (!(isa<Constant>(I->getOperand(Op)) ||
2284 isa<GlobalValue>(I->getOperand(Op)))) {
2285 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2286 if (P == 0) return 0; // Not evolving from PHI
2287 if (PHI == 0)
2288 PHI = P;
2289 else if (PHI != P)
2290 return 0; // Evolving from multiple different PHIs.
2291 }
2292
2293 // This is a expression evolving from a constant PHI!
2294 return PHI;
2295}
2296
2297/// EvaluateExpression - Given an expression that passes the
2298/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2299/// in the loop has the value PHIVal. If we can't fold this expression for some
2300/// reason, return null.
2301static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2302 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002303 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002304 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002305 Instruction *I = cast<Instruction>(V);
2306
2307 std::vector<Constant*> Operands;
2308 Operands.resize(I->getNumOperands());
2309
2310 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2311 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2312 if (Operands[i] == 0) return 0;
2313 }
2314
Chris Lattnerd6e56912007-12-10 22:53:04 +00002315 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2316 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2317 &Operands[0], Operands.size());
2318 else
2319 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2320 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002321}
2322
2323/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2324/// in the header of its containing loop, we know the loop executes a
2325/// constant number of times, and the PHI node is just a recurrence
2326/// involving constants, fold it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002327Constant *ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002328getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002329 std::map<PHINode*, Constant*>::iterator I =
2330 ConstantEvolutionLoopExitValue.find(PN);
2331 if (I != ConstantEvolutionLoopExitValue.end())
2332 return I->second;
2333
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002334 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002335 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2336
2337 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2338
2339 // Since the loop is canonicalized, the PHI node must have two entries. One
2340 // entry must be a constant (coming in from outside of the loop), and the
2341 // second must be derived from the same PHI.
2342 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2343 Constant *StartCST =
2344 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2345 if (StartCST == 0)
2346 return RetVal = 0; // Must be a constant.
2347
2348 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2349 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2350 if (PN2 != PN)
2351 return RetVal = 0; // Not derived from same PHI.
2352
2353 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002354 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002355 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2356
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002357 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002358 unsigned IterationNum = 0;
2359 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2360 if (IterationNum == NumIterations)
2361 return RetVal = PHIVal; // Got exit value!
2362
2363 // Compute the value of the PHI node for the next iteration.
2364 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2365 if (NextPHI == PHIVal)
2366 return RetVal = NextPHI; // Stopped evolving!
2367 if (NextPHI == 0)
2368 return 0; // Couldn't evaluate!
2369 PHIVal = NextPHI;
2370 }
2371}
2372
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002373/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002374/// constant number of times (the condition evolves only from constants),
2375/// try to evaluate a few iterations of the loop until we get the exit
2376/// condition gets a value of ExitWhen (true or false). If we cannot
2377/// evaluate the trip count of the loop, return UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002378SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002379ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002380 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2381 if (PN == 0) return UnknownValue;
2382
2383 // Since the loop is canonicalized, the PHI node must have two entries. One
2384 // entry must be a constant (coming in from outside of the loop), and the
2385 // second must be derived from the same PHI.
2386 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2387 Constant *StartCST =
2388 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2389 if (StartCST == 0) return UnknownValue; // Must be a constant.
2390
2391 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2392 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2393 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2394
2395 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2396 // the loop symbolically to determine when the condition gets a value of
2397 // "ExitWhen".
2398 unsigned IterationNum = 0;
2399 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2400 for (Constant *PHIVal = StartCST;
2401 IterationNum != MaxIterations; ++IterationNum) {
2402 ConstantInt *CondVal =
2403 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2404
2405 // Couldn't symbolically evaluate.
2406 if (!CondVal) return UnknownValue;
2407
2408 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2409 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2410 ++NumBruteForceTripCountsComputed;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002411 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002412 }
2413
2414 // Compute the value of the PHI node for the next iteration.
2415 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2416 if (NextPHI == 0 || NextPHI == PHIVal)
2417 return UnknownValue; // Couldn't evaluate or not making progress...
2418 PHIVal = NextPHI;
2419 }
2420
2421 // Too many iterations were needed to evaluate.
2422 return UnknownValue;
2423}
2424
2425/// getSCEVAtScope - Compute the value of the specified expression within the
2426/// indicated loop (which may be null to indicate in no loop). If the
2427/// expression cannot be evaluated, return UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002428SCEVHandle ScalarEvolution::getSCEVAtScope(SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002429 // FIXME: this should be turned into a virtual method on SCEV!
2430
2431 if (isa<SCEVConstant>(V)) return V;
2432
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002433 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002434 // exit value from the loop without using SCEVs.
2435 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2436 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002437 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002438 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2439 if (PHINode *PN = dyn_cast<PHINode>(I))
2440 if (PN->getParent() == LI->getHeader()) {
2441 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002442 // to see if the loop that contains it has a known backedge-taken
2443 // count. If so, we may be able to force computation of the exit
2444 // value.
2445 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2446 if (SCEVConstant *BTCC =
2447 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002448 // Okay, we know how many times the containing loop executes. If
2449 // this is a constant evolving PHI node, get the final value at
2450 // the specified iteration number.
2451 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002452 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002453 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002454 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002455 }
2456 }
2457
2458 // Okay, this is an expression that we cannot symbolically evaluate
2459 // into a SCEV. Check to see if it's possible to symbolically evaluate
2460 // the arguments into constants, and if so, try to constant propagate the
2461 // result. This is particularly useful for computing loop exit values.
2462 if (CanConstantFold(I)) {
2463 std::vector<Constant*> Operands;
2464 Operands.reserve(I->getNumOperands());
2465 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2466 Value *Op = I->getOperand(i);
2467 if (Constant *C = dyn_cast<Constant>(Op)) {
2468 Operands.push_back(C);
2469 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002470 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00002471 // non-integer and non-pointer, don't even try to analyze them
2472 // with scev techniques.
2473 if (!isa<IntegerType>(Op->getType()) &&
2474 !isa<PointerType>(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00002475 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002476
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002477 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2478 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2479 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2480 Op->getType(),
2481 false));
2482 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2483 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2484 Operands.push_back(ConstantExpr::getIntegerCast(C,
2485 Op->getType(),
2486 false));
2487 else
2488 return V;
2489 } else {
2490 return V;
2491 }
2492 }
2493 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002494
2495 Constant *C;
2496 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2497 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2498 &Operands[0], Operands.size());
2499 else
2500 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2501 &Operands[0], Operands.size());
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002502 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002503 }
2504 }
2505
2506 // This is some other type of SCEVUnknown, just return it.
2507 return V;
2508 }
2509
2510 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2511 // Avoid performing the look-up in the common case where the specified
2512 // expression has no loop-variant portions.
2513 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2514 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2515 if (OpAtScope != Comm->getOperand(i)) {
2516 if (OpAtScope == UnknownValue) return UnknownValue;
2517 // Okay, at least one of these operands is loop variant but might be
2518 // foldable. Build a new instance of the folded commutative expression.
2519 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2520 NewOps.push_back(OpAtScope);
2521
2522 for (++i; i != e; ++i) {
2523 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2524 if (OpAtScope == UnknownValue) return UnknownValue;
2525 NewOps.push_back(OpAtScope);
2526 }
2527 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002528 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002529 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002530 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002531 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002532 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002533 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002534 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002535 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002536 }
2537 }
2538 // If we got here, all operands are loop invariant.
2539 return Comm;
2540 }
2541
Nick Lewycky35b56022009-01-13 09:18:58 +00002542 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2543 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002544 if (LHS == UnknownValue) return LHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002545 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002546 if (RHS == UnknownValue) return RHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002547 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2548 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002549 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002550 }
2551
2552 // If this is a loop recurrence for a loop that does not contain L, then we
2553 // are dealing with the final value computed by the loop.
2554 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2555 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2556 // To evaluate this recurrence, we need to know how many times the AddRec
2557 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002558 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2559 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002560
Eli Friedman7489ec92008-08-04 23:49:06 +00002561 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002562 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002563 }
2564 return UnknownValue;
2565 }
2566
2567 //assert(0 && "Unknown SCEV type!");
2568 return UnknownValue;
2569}
2570
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002571/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2572/// at the specified scope in the program. The L value specifies a loop
2573/// nest to evaluate the expression at, where null is the top-level or a
2574/// specified loop is immediately inside of the loop.
2575///
2576/// This method can be used to compute the exit value for a variable defined
2577/// in a loop by querying what the value will hold in the parent loop.
2578///
2579/// If this value is not computable at this scope, a SCEVCouldNotCompute
2580/// object is returned.
2581SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2582 return getSCEVAtScope(getSCEV(V), L);
2583}
2584
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002585/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2586/// following equation:
2587///
2588/// A * X = B (mod N)
2589///
2590/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2591/// A and B isn't important.
2592///
2593/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2594static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2595 ScalarEvolution &SE) {
2596 uint32_t BW = A.getBitWidth();
2597 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2598 assert(A != 0 && "A must be non-zero.");
2599
2600 // 1. D = gcd(A, N)
2601 //
2602 // The gcd of A and N may have only one prime factor: 2. The number of
2603 // trailing zeros in A is its multiplicity
2604 uint32_t Mult2 = A.countTrailingZeros();
2605 // D = 2^Mult2
2606
2607 // 2. Check if B is divisible by D.
2608 //
2609 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2610 // is not less than multiplicity of this prime factor for D.
2611 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00002612 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002613
2614 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2615 // modulo (N / D).
2616 //
2617 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2618 // bit width during computations.
2619 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2620 APInt Mod(BW + 1, 0);
2621 Mod.set(BW - Mult2); // Mod = N / D
2622 APInt I = AD.multiplicativeInverse(Mod);
2623
2624 // 4. Compute the minimum unsigned root of the equation:
2625 // I * (B / D) mod (N / D)
2626 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2627
2628 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2629 // bits.
2630 return SE.getConstant(Result.trunc(BW));
2631}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002632
2633/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2634/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2635/// might be the same) or two SCEVCouldNotCompute objects.
2636///
2637static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00002638SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002639 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2640 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2641 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2642 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2643
2644 // We currently can only solve this if the coefficients are constants.
2645 if (!LC || !MC || !NC) {
Dan Gohman0ad08b02009-04-18 17:58:19 +00002646 SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002647 return std::make_pair(CNC, CNC);
2648 }
2649
2650 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2651 const APInt &L = LC->getValue()->getValue();
2652 const APInt &M = MC->getValue()->getValue();
2653 const APInt &N = NC->getValue()->getValue();
2654 APInt Two(BitWidth, 2);
2655 APInt Four(BitWidth, 4);
2656
2657 {
2658 using namespace APIntOps;
2659 const APInt& C = L;
2660 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2661 // The B coefficient is M-N/2
2662 APInt B(M);
2663 B -= sdiv(N,Two);
2664
2665 // The A coefficient is N/2
2666 APInt A(N.sdiv(Two));
2667
2668 // Compute the B^2-4ac term.
2669 APInt SqrtTerm(B);
2670 SqrtTerm *= B;
2671 SqrtTerm -= Four * (A * C);
2672
2673 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2674 // integer value or else APInt::sqrt() will assert.
2675 APInt SqrtVal(SqrtTerm.sqrt());
2676
2677 // Compute the two solutions for the quadratic formula.
2678 // The divisions must be performed as signed divisions.
2679 APInt NegB(-B);
2680 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00002681 if (TwoA.isMinValue()) {
Dan Gohman0ad08b02009-04-18 17:58:19 +00002682 SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00002683 return std::make_pair(CNC, CNC);
2684 }
2685
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002686 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2687 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2688
Dan Gohman89f85052007-10-22 18:31:58 +00002689 return std::make_pair(SE.getConstant(Solution1),
2690 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002691 } // end APIntOps namespace
2692}
2693
2694/// HowFarToZero - Return the number of times a backedge comparing the specified
2695/// value to zero will execute. If not computable, return UnknownValue
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002696SCEVHandle ScalarEvolution::HowFarToZero(SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002697 // If the value is a constant
2698 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2699 // If the value is already zero, the branch will execute zero times.
2700 if (C->getValue()->isZero()) return C;
2701 return UnknownValue; // Otherwise it will loop infinitely.
2702 }
2703
2704 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2705 if (!AddRec || AddRec->getLoop() != L)
2706 return UnknownValue;
2707
2708 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002709 // If this is an affine expression, the execution count of this branch is
2710 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002711 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002712 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002713 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002714 // equivalent to:
2715 //
2716 // Step*N = -Start (mod 2^BW)
2717 //
2718 // where BW is the common bit width of Start and Step.
2719
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002720 // Get the initial value for the loop.
2721 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2722 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002723
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002724 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002725
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002726 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002727 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002728
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002729 // First, handle unitary steps.
2730 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002731 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002732 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2733 return Start; // N = Start (as unsigned)
2734
2735 // Then, try to solve the above equation provided that Start is constant.
2736 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2737 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002738 -StartC->getValue()->getValue(),
2739 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002740 }
2741 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2742 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2743 // the quadratic equation to solve it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002744 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
2745 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002746 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2747 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2748 if (R1) {
2749#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002750 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
2751 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002752#endif
2753 // Pick the smallest positive root value.
2754 if (ConstantInt *CB =
2755 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2756 R1->getValue(), R2->getValue()))) {
2757 if (CB->getZExtValue() == false)
2758 std::swap(R1, R2); // R1 is the minimum root now.
2759
2760 // We can only use this value if the chrec ends up with an exact zero
2761 // value at this index. When solving for "X*X != 5", for example, we
2762 // should not accept a root of 2.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002763 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00002764 if (Val->isZero())
2765 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002766 }
2767 }
2768 }
2769
2770 return UnknownValue;
2771}
2772
2773/// HowFarToNonZero - Return the number of times a backedge checking the
2774/// specified value for nonzero will execute. If not computable, return
2775/// UnknownValue
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002776SCEVHandle ScalarEvolution::HowFarToNonZero(SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002777 // Loops that look like: while (X == 0) are very strange indeed. We don't
2778 // handle them yet except for the trivial case. This could be expanded in the
2779 // future as needed.
2780
2781 // If the value is a constant, check to see if it is known to be non-zero
2782 // already. If so, the backedge will execute zero times.
2783 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00002784 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002785 return getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002786 return UnknownValue; // Otherwise it will loop infinitely.
2787 }
2788
2789 // We could implement others, but I really doubt anyone writes loops like
2790 // this, and if they did, they would already be constant folded.
2791 return UnknownValue;
2792}
2793
Dan Gohman1cddf972008-09-15 22:18:04 +00002794/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2795/// (which may not be an immediate predecessor) which has exactly one
2796/// successor from which BB is reachable, or null if no such block is
2797/// found.
2798///
2799BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002800ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1cddf972008-09-15 22:18:04 +00002801 // If the block has a unique predecessor, the predecessor must have
2802 // no other successors from which BB is reachable.
2803 if (BasicBlock *Pred = BB->getSinglePredecessor())
2804 return Pred;
2805
2806 // A loop's header is defined to be a block that dominates the loop.
2807 // If the loop has a preheader, it must be a block that has exactly
2808 // one successor that can reach BB. This is slightly more strict
2809 // than necessary, but works if critical edges are split.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002810 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman1cddf972008-09-15 22:18:04 +00002811 return L->getLoopPreheader();
2812
2813 return 0;
2814}
2815
Dan Gohmancacd2012009-02-12 22:19:27 +00002816/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002817/// a conditional between LHS and RHS.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002818bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohmancacd2012009-02-12 22:19:27 +00002819 ICmpInst::Predicate Pred,
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002820 SCEV *LHS, SCEV *RHS) {
2821 BasicBlock *Preheader = L->getLoopPreheader();
2822 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002823
Dan Gohmanab678fb2008-08-12 20:17:31 +00002824 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohman1cddf972008-09-15 22:18:04 +00002825 // there are predecessors that can be found that have unique successors
2826 // leading to the original header.
2827 for (; Preheader;
2828 PreheaderDest = Preheader,
2829 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00002830
2831 BranchInst *LoopEntryPredicate =
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002832 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00002833 if (!LoopEntryPredicate ||
2834 LoopEntryPredicate->isUnconditional())
2835 continue;
2836
2837 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2838 if (!ICI) continue;
2839
2840 // Now that we found a conditional branch that dominates the loop, check to
2841 // see if it is the comparison we are looking for.
2842 Value *PreCondLHS = ICI->getOperand(0);
2843 Value *PreCondRHS = ICI->getOperand(1);
2844 ICmpInst::Predicate Cond;
2845 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2846 Cond = ICI->getPredicate();
2847 else
2848 Cond = ICI->getInversePredicate();
2849
Dan Gohmancacd2012009-02-12 22:19:27 +00002850 if (Cond == Pred)
2851 ; // An exact match.
2852 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
2853 ; // The actual condition is beyond sufficient.
2854 else
2855 // Check a few special cases.
2856 switch (Cond) {
2857 case ICmpInst::ICMP_UGT:
2858 if (Pred == ICmpInst::ICMP_ULT) {
2859 std::swap(PreCondLHS, PreCondRHS);
2860 Cond = ICmpInst::ICMP_ULT;
2861 break;
2862 }
2863 continue;
2864 case ICmpInst::ICMP_SGT:
2865 if (Pred == ICmpInst::ICMP_SLT) {
2866 std::swap(PreCondLHS, PreCondRHS);
2867 Cond = ICmpInst::ICMP_SLT;
2868 break;
2869 }
2870 continue;
2871 case ICmpInst::ICMP_NE:
2872 // Expressions like (x >u 0) are often canonicalized to (x != 0),
2873 // so check for this case by checking if the NE is comparing against
2874 // a minimum or maximum constant.
2875 if (!ICmpInst::isTrueWhenEqual(Pred))
2876 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
2877 const APInt &A = CI->getValue();
2878 switch (Pred) {
2879 case ICmpInst::ICMP_SLT:
2880 if (A.isMaxSignedValue()) break;
2881 continue;
2882 case ICmpInst::ICMP_SGT:
2883 if (A.isMinSignedValue()) break;
2884 continue;
2885 case ICmpInst::ICMP_ULT:
2886 if (A.isMaxValue()) break;
2887 continue;
2888 case ICmpInst::ICMP_UGT:
2889 if (A.isMinValue()) break;
2890 continue;
2891 default:
2892 continue;
2893 }
2894 Cond = ICmpInst::ICMP_NE;
2895 // NE is symmetric but the original comparison may not be. Swap
2896 // the operands if necessary so that they match below.
2897 if (isa<SCEVConstant>(LHS))
2898 std::swap(PreCondLHS, PreCondRHS);
2899 break;
2900 }
2901 continue;
2902 default:
2903 // We weren't able to reconcile the condition.
2904 continue;
2905 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00002906
2907 if (!PreCondLHS->getType()->isInteger()) continue;
2908
2909 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
2910 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
2911 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002912 (LHS == getNotSCEV(PreCondRHSSCEV) &&
2913 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohmanab678fb2008-08-12 20:17:31 +00002914 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002915 }
2916
Dan Gohmanab678fb2008-08-12 20:17:31 +00002917 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002918}
2919
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002920/// HowManyLessThans - Return the number of times a backedge containing the
2921/// specified less-than comparison will execute. If not computable, return
2922/// UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002923SCEVHandle ScalarEvolution::
Nick Lewycky35b56022009-01-13 09:18:58 +00002924HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002925 // Only handle: "ADDREC < LoopInvariant".
2926 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2927
2928 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2929 if (!AddRec || AddRec->getLoop() != L)
2930 return UnknownValue;
2931
2932 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00002933 // FORNOW: We only support unit strides.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002934 SCEVHandle One = getIntegerSCEV(1, RHS->getType());
Nick Lewycky35b56022009-01-13 09:18:58 +00002935 if (AddRec->getOperand(1) != One)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002936 return UnknownValue;
2937
Nick Lewycky35b56022009-01-13 09:18:58 +00002938 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
2939 // m. So, we count the number of iterations in which {n,+,1} < m is true.
2940 // Note that we cannot simply return max(m-n,0) because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00002941 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002942
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00002943 // First, we get the value of the LHS in the first iteration: n
2944 SCEVHandle Start = AddRec->getOperand(0);
2945
Dan Gohmancacd2012009-02-12 22:19:27 +00002946 if (isLoopGuardedByCond(L,
2947 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002948 getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
Nick Lewycky35b56022009-01-13 09:18:58 +00002949 // Since we know that the condition is true in order to enter the loop,
2950 // we know that it will run exactly m-n times.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002951 return getMinusSCEV(RHS, Start);
Nick Lewycky35b56022009-01-13 09:18:58 +00002952 } else {
2953 // Then, we get the value of the LHS in the first iteration in which the
2954 // above condition doesn't hold. This equals to max(m,n).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002955 SCEVHandle End = isSigned ? getSMaxExpr(RHS, Start)
2956 : getUMaxExpr(RHS, Start);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00002957
Nick Lewycky35b56022009-01-13 09:18:58 +00002958 // Finally, we subtract these two values to get the number of times the
2959 // backedge is executed: max(m,n)-n.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002960 return getMinusSCEV(End, Start);
Nick Lewycky64d1fff2008-12-16 08:30:01 +00002961 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002962 }
2963
2964 return UnknownValue;
2965}
2966
2967/// getNumIterationsInRange - Return the number of iterations of this loop that
2968/// produce values in the specified constant range. Another way of looking at
2969/// this is that it returns the first iteration number where the value is not in
2970/// the condition, thus computing the exit count. If the iteration count can't
2971/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00002972SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2973 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002974 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00002975 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002976
2977 // If the start is a non-zero constant, shift the range to simplify things.
2978 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2979 if (!SC->getValue()->isZero()) {
2980 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00002981 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2982 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002983 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2984 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00002985 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002986 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00002987 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002988 }
2989
2990 // The only time we can solve this is when we have all constant indices.
2991 // Otherwise, we cannot determine the overflow conditions.
2992 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2993 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00002994 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002995
2996
2997 // Okay at this point we know that all elements of the chrec are constants and
2998 // that the start element is zero.
2999
3000 // First check to see if the range contains zero. If not, the first
3001 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003002 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003003 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003004 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003005
3006 if (isAffine()) {
3007 // If this is an affine expression then we have this situation:
3008 // Solve {0,+,A} in Range === Ax in Range
3009
3010 // We know that zero is in the range. If A is positive then we know that
3011 // the upper value of the range must be the first possible exit value.
3012 // If A is negative then the lower of the range is the last possible loop
3013 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003014 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003015 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3016 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3017
3018 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003019 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003020 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3021
3022 // Evaluate at the exit value. If we really did fall out of the valid
3023 // range, then we computed our trip count, otherwise wrap around or other
3024 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003025 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003026 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003027 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003028
3029 // Ensure that the previous value is in the range. This is a sanity check.
3030 assert(Range.contains(
3031 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003032 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003033 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003034 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003035 } else if (isQuadratic()) {
3036 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3037 // quadratic equation to solve it. To do this, we must frame our problem in
3038 // terms of figuring out when zero is crossed, instead of when
3039 // Range.getUpper() is crossed.
3040 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003041 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3042 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003043
3044 // Next, solve the constructed addrec
3045 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003046 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003047 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3048 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3049 if (R1) {
3050 // Pick the smallest positive root value.
3051 if (ConstantInt *CB =
3052 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3053 R1->getValue(), R2->getValue()))) {
3054 if (CB->getZExtValue() == false)
3055 std::swap(R1, R2); // R1 is the minimum root now.
3056
3057 // Make sure the root is not off by one. The returned iteration should
3058 // not be in the range, but the previous one should be. When solving
3059 // for "X*X < 5", for example, we should not return a root of 2.
3060 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003061 R1->getValue(),
3062 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003063 if (Range.contains(R1Val->getValue())) {
3064 // The next iteration must be out of the range...
3065 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3066
Dan Gohman89f85052007-10-22 18:31:58 +00003067 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003068 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003069 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003070 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003071 }
3072
3073 // If R1 was not in the range, then it is a good return value. Make
3074 // sure that R1-1 WAS in the range though, just in case.
3075 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003076 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003077 if (Range.contains(R1Val->getValue()))
3078 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003079 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003080 }
3081 }
3082 }
3083
Dan Gohman0ad08b02009-04-18 17:58:19 +00003084 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003085}
3086
3087
3088
3089//===----------------------------------------------------------------------===//
3090// ScalarEvolution Class Implementation
3091//===----------------------------------------------------------------------===//
3092
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003093ScalarEvolution::ScalarEvolution()
3094 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3095}
3096
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003097bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003098 this->F = &F;
3099 LI = &getAnalysis<LoopInfo>();
3100 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003101 return false;
3102}
3103
3104void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003105 Scalars.clear();
3106 BackedgeTakenCounts.clear();
3107 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003108}
3109
3110void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3111 AU.setPreservesAll();
3112 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003113}
3114
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003115bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003116 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003117}
3118
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003119static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003120 const Loop *L) {
3121 // Print all inner loops first
3122 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3123 PrintLoopInfo(OS, SE, *I);
3124
Nick Lewyckye5da1912008-01-02 02:49:20 +00003125 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003126
Devang Patel02451fa2007-08-21 00:31:24 +00003127 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003128 L->getExitBlocks(ExitBlocks);
3129 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003130 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003131
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003132 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3133 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003134 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003135 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003136 }
3137
Nick Lewyckye5da1912008-01-02 02:49:20 +00003138 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003139}
3140
Dan Gohman13058cc2009-04-21 00:47:46 +00003141void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003142 // ScalarEvolution's implementaiton of the print method is to print
3143 // out SCEV values of all instructions that are interesting. Doing
3144 // this potentially causes it to create new SCEV objects though,
3145 // which technically conflicts with the const qualifier. This isn't
3146 // observable from outside the class though (the hasSCEV function
3147 // notwithstanding), so casting away the const isn't dangerous.
3148 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003149
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003150 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003151 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3152 if (I->getType()->isInteger()) {
3153 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003154 OS << " --> ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003155 SCEVHandle SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003156 SV->print(OS);
3157 OS << "\t\t";
3158
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003159 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003160 OS << "Exits: ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003161 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003162 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3163 OS << "<<Unknown>>";
3164 } else {
3165 OS << *ExitValue;
3166 }
3167 }
3168
3169
3170 OS << "\n";
3171 }
3172
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003173 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3174 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3175 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003176}
Dan Gohman13058cc2009-04-21 00:47:46 +00003177
3178void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3179 raw_os_ostream OS(o);
3180 print(OS, M);
3181}