blob: a3a6ff33332e0ded0e19d207c17b9f542e086263 [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"
82#include "llvm/Support/Streams.h"
83#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 {
118 print(cerr);
Nick Lewycky41153462009-01-16 17:07:22 +0000119 cerr << '\n';
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000120}
121
Dan Gohman7b560c42008-06-18 16:23:07 +0000122bool SCEV::isZero() const {
123 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
124 return SC->getValue()->isZero();
125 return false;
126}
127
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128
129SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
130
131bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
132 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
133 return false;
134}
135
136const Type *SCEVCouldNotCompute::getType() const {
137 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
138 return 0;
139}
140
141bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
142 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
143 return false;
144}
145
146SCEVHandle SCEVCouldNotCompute::
147replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000148 const SCEVHandle &Conc,
149 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150 return this;
151}
152
153void SCEVCouldNotCompute::print(std::ostream &OS) const {
154 OS << "***COULDNOTCOMPUTE***";
155}
156
157bool SCEVCouldNotCompute::classof(const SCEV *S) {
158 return S->getSCEVType() == scCouldNotCompute;
159}
160
161
162// SCEVConstants - Only allow the creation of one SCEVConstant for any
163// particular value. Don't use a SCEVHandle here, or else the object will
164// never be deleted!
165static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
166
167
168SCEVConstant::~SCEVConstant() {
169 SCEVConstants->erase(V);
170}
171
Dan Gohman89f85052007-10-22 18:31:58 +0000172SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000173 SCEVConstant *&R = (*SCEVConstants)[V];
174 if (R == 0) R = new SCEVConstant(V);
175 return R;
176}
177
Dan Gohman89f85052007-10-22 18:31:58 +0000178SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
179 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000180}
181
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000182const Type *SCEVConstant::getType() const { return V->getType(); }
183
184void SCEVConstant::print(std::ostream &OS) const {
185 WriteAsOperand(OS, V, false);
186}
187
188// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
189// particular input. Don't use a SCEVHandle here, or else the object will
190// never be deleted!
191static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
192 SCEVTruncateExpr*> > SCEVTruncates;
193
194SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
195 : SCEV(scTruncate), Op(op), Ty(ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000196 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
197 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198 "Cannot truncate non-integer value!");
Dan Gohman01c2ee72009-04-16 03:18:22 +0000199 assert((!Op->getType()->isInteger() || !Ty->isInteger() ||
200 Op->getType()->getPrimitiveSizeInBits() >
201 Ty->getPrimitiveSizeInBits()) &&
202 "This is not a truncating conversion!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203}
204
205SCEVTruncateExpr::~SCEVTruncateExpr() {
206 SCEVTruncates->erase(std::make_pair(Op, Ty));
207}
208
Evan Cheng98c073b2009-02-17 00:13:06 +0000209bool SCEVTruncateExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
210 return Op->dominates(BB, DT);
211}
212
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000213void SCEVTruncateExpr::print(std::ostream &OS) const {
214 OS << "(truncate " << *Op << " to " << *Ty << ")";
215}
216
217// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
218// particular input. Don't use a SCEVHandle here, or else the object will never
219// be deleted!
220static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
221 SCEVZeroExtendExpr*> > SCEVZeroExtends;
222
223SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
224 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000225 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
226 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000227 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228}
229
230SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
231 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
232}
233
Evan Cheng98c073b2009-02-17 00:13:06 +0000234bool SCEVZeroExtendExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
235 return Op->dominates(BB, DT);
236}
237
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238void SCEVZeroExtendExpr::print(std::ostream &OS) const {
239 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
240}
241
242// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
243// particular input. Don't use a SCEVHandle here, or else the object will never
244// be deleted!
245static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
246 SCEVSignExtendExpr*> > SCEVSignExtends;
247
248SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
249 : SCEV(scSignExtend), Op(op), Ty(ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000250 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
251 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252 "Cannot sign extend non-integer value!");
253 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
254 && "This is not an extending conversion!");
255}
256
257SCEVSignExtendExpr::~SCEVSignExtendExpr() {
258 SCEVSignExtends->erase(std::make_pair(Op, Ty));
259}
260
Evan Cheng98c073b2009-02-17 00:13:06 +0000261bool SCEVSignExtendExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
262 return Op->dominates(BB, DT);
263}
264
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000265void SCEVSignExtendExpr::print(std::ostream &OS) const {
266 OS << "(signextend " << *Op << " to " << *Ty << ")";
267}
268
269// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
270// particular input. Don't use a SCEVHandle here, or else the object will never
271// be deleted!
272static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
273 SCEVCommutativeExpr*> > SCEVCommExprs;
274
275SCEVCommutativeExpr::~SCEVCommutativeExpr() {
276 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
277 std::vector<SCEV*>(Operands.begin(),
278 Operands.end())));
279}
280
281void SCEVCommutativeExpr::print(std::ostream &OS) const {
282 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
283 const char *OpStr = getOperationStr();
284 OS << "(" << *Operands[0];
285 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
286 OS << OpStr << *Operands[i];
287 OS << ")";
288}
289
290SCEVHandle SCEVCommutativeExpr::
291replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000292 const SCEVHandle &Conc,
293 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000295 SCEVHandle H =
296 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000297 if (H != getOperand(i)) {
298 std::vector<SCEVHandle> NewOps;
299 NewOps.reserve(getNumOperands());
300 for (unsigned j = 0; j != i; ++j)
301 NewOps.push_back(getOperand(j));
302 NewOps.push_back(H);
303 for (++i; i != e; ++i)
304 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000305 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000306
307 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000308 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000310 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000311 else if (isa<SCEVSMaxExpr>(this))
312 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000313 else if (isa<SCEVUMaxExpr>(this))
314 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000315 else
316 assert(0 && "Unknown commutative expr!");
317 }
318 }
319 return this;
320}
321
Evan Cheng98c073b2009-02-17 00:13:06 +0000322bool SCEVCommutativeExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
323 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
324 if (!getOperand(i)->dominates(BB, DT))
325 return false;
326 }
327 return true;
328}
329
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000331// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000332// input. Don't use a SCEVHandle here, or else the object will never be
333// deleted!
334static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000335 SCEVUDivExpr*> > SCEVUDivs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000337SCEVUDivExpr::~SCEVUDivExpr() {
338 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000339}
340
Evan Cheng98c073b2009-02-17 00:13:06 +0000341bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
342 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
343}
344
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000345void SCEVUDivExpr::print(std::ostream &OS) const {
346 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347}
348
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000349const Type *SCEVUDivExpr::getType() const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000350 return LHS->getType();
351}
352
353// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
354// particular input. Don't use a SCEVHandle here, or else the object will never
355// be deleted!
356static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
357 SCEVAddRecExpr*> > SCEVAddRecExprs;
358
359SCEVAddRecExpr::~SCEVAddRecExpr() {
360 SCEVAddRecExprs->erase(std::make_pair(L,
361 std::vector<SCEV*>(Operands.begin(),
362 Operands.end())));
363}
364
Evan Cheng98c073b2009-02-17 00:13:06 +0000365bool SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
366 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
367 if (!getOperand(i)->dominates(BB, DT))
368 return false;
369 }
370 return true;
371}
372
373
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000374SCEVHandle SCEVAddRecExpr::
375replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000376 const SCEVHandle &Conc,
377 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000379 SCEVHandle H =
380 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000381 if (H != getOperand(i)) {
382 std::vector<SCEVHandle> NewOps;
383 NewOps.reserve(getNumOperands());
384 for (unsigned j = 0; j != i; ++j)
385 NewOps.push_back(getOperand(j));
386 NewOps.push_back(H);
387 for (++i; i != e; ++i)
388 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000389 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000390
Dan Gohman89f85052007-10-22 18:31:58 +0000391 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000392 }
393 }
394 return this;
395}
396
397
398bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
399 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
400 // contain L and if the start is invariant.
401 return !QueryLoop->contains(L->getHeader()) &&
402 getOperand(0)->isLoopInvariant(QueryLoop);
403}
404
405
406void SCEVAddRecExpr::print(std::ostream &OS) const {
407 OS << "{" << *Operands[0];
408 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
409 OS << ",+," << *Operands[i];
410 OS << "}<" << L->getHeader()->getName() + ">";
411}
412
413// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
414// value. Don't use a SCEVHandle here, or else the object will never be
415// deleted!
416static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
417
418SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
419
420bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
421 // All non-instruction values are loop invariant. All instructions are loop
422 // invariant if they are not contained in the specified loop.
423 if (Instruction *I = dyn_cast<Instruction>(V))
424 return !L->contains(I->getParent());
425 return true;
426}
427
Evan Cheng98c073b2009-02-17 00:13:06 +0000428bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
429 if (Instruction *I = dyn_cast<Instruction>(getValue()))
430 return DT->dominates(I->getParent(), BB);
431 return true;
432}
433
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000434const Type *SCEVUnknown::getType() const {
435 return V->getType();
436}
437
438void SCEVUnknown::print(std::ostream &OS) const {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000439 if (isa<PointerType>(V->getType()))
440 OS << "(ptrtoint " << *V->getType() << " ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000441 WriteAsOperand(OS, V, false);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000442 if (isa<PointerType>(V->getType()))
443 OS << " to iPTR)";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000444}
445
446//===----------------------------------------------------------------------===//
447// SCEV Utilities
448//===----------------------------------------------------------------------===//
449
450namespace {
451 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
452 /// than the complexity of the RHS. This comparator is used to canonicalize
453 /// expressions.
454 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000455 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000456 return LHS->getSCEVType() < RHS->getSCEVType();
457 }
458 };
459}
460
461/// GroupByComplexity - Given a list of SCEV objects, order them by their
462/// complexity, and group objects of the same complexity together by value.
463/// When this routine is finished, we know that any duplicates in the vector are
464/// consecutive and that complexity is monotonically increasing.
465///
466/// Note that we go take special precautions to ensure that we get determinstic
467/// results from this routine. In other words, we don't want the results of
468/// this to depend on where the addresses of various SCEV objects happened to
469/// land in memory.
470///
471static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
472 if (Ops.size() < 2) return; // Noop
473 if (Ops.size() == 2) {
474 // This is the common case, which also happens to be trivially simple.
475 // Special case it.
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000476 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000477 std::swap(Ops[0], Ops[1]);
478 return;
479 }
480
481 // Do the rough sort by complexity.
482 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
483
484 // Now that we are sorted by complexity, group elements of the same
485 // complexity. Note that this is, at worst, N^2, but the vector is likely to
486 // be extremely short in practice. Note that we take this approach because we
487 // do not want to depend on the addresses of the objects we are grouping.
488 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
489 SCEV *S = Ops[i];
490 unsigned Complexity = S->getSCEVType();
491
492 // If there are any objects of the same complexity and same value as this
493 // one, group them.
494 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
495 if (Ops[j] == S) { // Found a duplicate.
496 // Move it to immediately after i'th element.
497 std::swap(Ops[i+1], Ops[j]);
498 ++i; // no need to rescan it.
499 if (i == e-2) return; // Done!
500 }
501 }
502 }
503}
504
505
506
507//===----------------------------------------------------------------------===//
508// Simple SCEV method implementations
509//===----------------------------------------------------------------------===//
510
Eli Friedman7489ec92008-08-04 23:49:06 +0000511/// BinomialCoefficient - Compute BC(It, K). The result has width W.
512// Assume, K > 0.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000513static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000514 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000515 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000516 // Handle the simplest case efficiently.
517 if (K == 1)
518 return SE.getTruncateOrZeroExtend(It, ResultTy);
519
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000520 // We are using the following formula for BC(It, K):
521 //
522 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
523 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000524 // Suppose, W is the bitwidth of the return value. We must be prepared for
525 // overflow. Hence, we must assure that the result of our computation is
526 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
527 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000528 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000529 // However, this code doesn't use exactly that formula; the formula it uses
530 // is something like the following, where T is the number of factors of 2 in
531 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
532 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000533 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000534 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000535 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000536 // This formula is trivially equivalent to the previous formula. However,
537 // this formula can be implemented much more efficiently. The trick is that
538 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
539 // arithmetic. To do exact division in modular arithmetic, all we have
540 // to do is multiply by the inverse. Therefore, this step can be done at
541 // width W.
542 //
543 // The next issue is how to safely do the division by 2^T. The way this
544 // is done is by doing the multiplication step at a width of at least W + T
545 // bits. This way, the bottom W+T bits of the product are accurate. Then,
546 // when we perform the division by 2^T (which is equivalent to a right shift
547 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
548 // truncated out after the division by 2^T.
549 //
550 // In comparison to just directly using the first formula, this technique
551 // is much more efficient; using the first formula requires W * K bits,
552 // but this formula less than W + K bits. Also, the first formula requires
553 // a division step, whereas this formula only requires multiplies and shifts.
554 //
555 // It doesn't matter whether the subtraction step is done in the calculation
556 // width or the input iteration count's width; if the subtraction overflows,
557 // the result must be zero anyway. We prefer here to do it in the width of
558 // the induction variable because it helps a lot for certain cases; CodeGen
559 // isn't smart enough to ignore the overflow, which leads to much less
560 // efficient code if the width of the subtraction is wider than the native
561 // register width.
562 //
563 // (It's possible to not widen at all by pulling out factors of 2 before
564 // the multiplication; for example, K=2 can be calculated as
565 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
566 // extra arithmetic, so it's not an obvious win, and it gets
567 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000568
Eli Friedman7489ec92008-08-04 23:49:06 +0000569 // Protection from insane SCEVs; this bound is conservative,
570 // but it probably doesn't matter.
571 if (K > 1000)
572 return new SCEVCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000573
Dan Gohman01c2ee72009-04-16 03:18:22 +0000574 unsigned W = SE.getTargetData().getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000575
Eli Friedman7489ec92008-08-04 23:49:06 +0000576 // Calculate K! / 2^T and T; we divide out the factors of two before
577 // multiplying for calculating K! / 2^T to avoid overflow.
578 // Other overflow doesn't matter because we only care about the bottom
579 // W bits of the result.
580 APInt OddFactorial(W, 1);
581 unsigned T = 1;
582 for (unsigned i = 3; i <= K; ++i) {
583 APInt Mult(W, i);
584 unsigned TwoFactors = Mult.countTrailingZeros();
585 T += TwoFactors;
586 Mult = Mult.lshr(TwoFactors);
587 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000588 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000589
Eli Friedman7489ec92008-08-04 23:49:06 +0000590 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000591 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000592
593 // Calcuate 2^T, at width T+W.
594 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
595
596 // Calculate the multiplicative inverse of K! / 2^T;
597 // this multiplication factor will perform the exact division by
598 // K! / 2^T.
599 APInt Mod = APInt::getSignedMinValue(W+1);
600 APInt MultiplyFactor = OddFactorial.zext(W+1);
601 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
602 MultiplyFactor = MultiplyFactor.trunc(W);
603
604 // Calculate the product, at width T+W
605 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
606 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
607 for (unsigned i = 1; i != K; ++i) {
608 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
609 Dividend = SE.getMulExpr(Dividend,
610 SE.getTruncateOrZeroExtend(S, CalculationTy));
611 }
612
613 // Divide by 2^T
614 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
615
616 // Truncate the result, and divide by K! / 2^T.
617
618 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
619 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000620}
621
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000622/// evaluateAtIteration - Return the value of this chain of recurrences at
623/// the specified iteration number. We can evaluate this recurrence by
624/// multiplying each element in the chain by the binomial coefficient
625/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
626///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000627/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000629/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000630///
Dan Gohman89f85052007-10-22 18:31:58 +0000631SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
632 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000633 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000634 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000635 // The computation is correct in the face of overflow provided that the
636 // multiplication is performed _after_ the evaluation of the binomial
637 // coefficient.
Dan Gohman01c2ee72009-04-16 03:18:22 +0000638 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000639 if (isa<SCEVCouldNotCompute>(Coeff))
640 return Coeff;
641
642 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000643 }
644 return Result;
645}
646
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000647//===----------------------------------------------------------------------===//
648// SCEV Expression folder implementations
649//===----------------------------------------------------------------------===//
650
Dan Gohman89f85052007-10-22 18:31:58 +0000651SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000652 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000653 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000654 ConstantExpr::getTrunc(SC->getValue(), Ty));
655
656 // If the input value is a chrec scev made out of constants, truncate
657 // all of the constants.
658 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
659 std::vector<SCEVHandle> Operands;
660 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
661 // FIXME: This should allow truncation of other expression types!
662 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman89f85052007-10-22 18:31:58 +0000663 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664 else
665 break;
666 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman89f85052007-10-22 18:31:58 +0000667 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000668 }
669
670 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
671 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
672 return Result;
673}
674
Dan Gohman36d40922009-04-16 19:25:55 +0000675SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
676 const Type *Ty) {
677 assert(getTargetData().getTypeSizeInBits(Op->getType()) <
678 getTargetData().getTypeSizeInBits(Ty) &&
679 "This is not an extending conversion!");
680
Dan Gohman01c2ee72009-04-16 03:18:22 +0000681 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
682 const Type *IntTy = Ty;
683 if (isa<PointerType>(IntTy)) IntTy = getTargetData().getIntPtrType();
684 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
685 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
686 return getUnknown(C);
687 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000688
689 // FIXME: If the input value is a chrec scev, and we can prove that the value
690 // did not overflow the old, smaller, value, we can zero extend all of the
691 // operands (often constants). This would allow analysis of something like
692 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
693
694 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
695 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
696 return Result;
697}
698
Dan Gohman89f85052007-10-22 18:31:58 +0000699SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000700 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
701 const Type *IntTy = Ty;
702 if (isa<PointerType>(IntTy)) IntTy = getTargetData().getIntPtrType();
703 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
704 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
705 return getUnknown(C);
706 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000707
708 // FIXME: If the input value is a chrec scev, and we can prove that the value
709 // did not overflow the old, smaller, value, we can sign extend all of the
710 // operands (often constants). This would allow analysis of something like
711 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
712
713 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
714 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
715 return Result;
716}
717
718// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000719SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000720 assert(!Ops.empty() && "Cannot get empty add!");
721 if (Ops.size() == 1) return Ops[0];
722
723 // Sort by complexity, this groups all similar expression types together.
724 GroupByComplexity(Ops);
725
726 // If there are any constants, fold them together.
727 unsigned Idx = 0;
728 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
729 ++Idx;
730 assert(Idx < Ops.size());
731 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
732 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000733 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
734 RHSC->getValue()->getValue());
735 Ops[0] = getConstant(Fold);
736 Ops.erase(Ops.begin()+1); // Erase the folded element
737 if (Ops.size() == 1) return Ops[0];
738 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000739 }
740
741 // If we are left with a constant zero being added, strip it off.
742 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
743 Ops.erase(Ops.begin());
744 --Idx;
745 }
746 }
747
748 if (Ops.size() == 1) return Ops[0];
749
750 // Okay, check to see if the same value occurs in the operand list twice. If
751 // so, merge them together into an multiply expression. Since we sorted the
752 // list, these values are required to be adjacent.
753 const Type *Ty = Ops[0]->getType();
754 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
755 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
756 // Found a match, merge the two values into a multiply, and add any
757 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000758 SCEVHandle Two = getIntegerSCEV(2, Ty);
759 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000760 if (Ops.size() == 2)
761 return Mul;
762 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
763 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000764 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000765 }
766
767 // Now we know the first non-constant operand. Skip past any cast SCEVs.
768 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
769 ++Idx;
770
771 // If there are add operands they would be next.
772 if (Idx < Ops.size()) {
773 bool DeletedAdd = false;
774 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
775 // If we have an add, expand the add operands onto the end of the operands
776 // list.
777 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
778 Ops.erase(Ops.begin()+Idx);
779 DeletedAdd = true;
780 }
781
782 // If we deleted at least one add, we added operands to the end of the list,
783 // and they are not necessarily sorted. Recurse to resort and resimplify
784 // any operands we just aquired.
785 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +0000786 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000787 }
788
789 // Skip over the add expression until we get to a multiply.
790 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
791 ++Idx;
792
793 // If we are adding something to a multiply expression, make sure the
794 // something is not already an operand of the multiply. If so, merge it into
795 // the multiply.
796 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
797 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
798 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
799 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
800 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
801 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
802 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
803 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
804 if (Mul->getNumOperands() != 2) {
805 // If the multiply has more than two operands, we must get the
806 // Y*Z term.
807 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
808 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000809 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000810 }
Dan Gohman89f85052007-10-22 18:31:58 +0000811 SCEVHandle One = getIntegerSCEV(1, Ty);
812 SCEVHandle AddOne = getAddExpr(InnerMul, One);
813 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000814 if (Ops.size() == 2) return OuterMul;
815 if (AddOp < Idx) {
816 Ops.erase(Ops.begin()+AddOp);
817 Ops.erase(Ops.begin()+Idx-1);
818 } else {
819 Ops.erase(Ops.begin()+Idx);
820 Ops.erase(Ops.begin()+AddOp-1);
821 }
822 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000823 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000824 }
825
826 // Check this multiply against other multiplies being added together.
827 for (unsigned OtherMulIdx = Idx+1;
828 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
829 ++OtherMulIdx) {
830 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
831 // If MulOp occurs in OtherMul, we can fold the two multiplies
832 // together.
833 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
834 OMulOp != e; ++OMulOp)
835 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
836 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
837 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
838 if (Mul->getNumOperands() != 2) {
839 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
840 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000841 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000842 }
843 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
844 if (OtherMul->getNumOperands() != 2) {
845 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
846 OtherMul->op_end());
847 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000848 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849 }
Dan Gohman89f85052007-10-22 18:31:58 +0000850 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
851 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000852 if (Ops.size() == 2) return OuterMul;
853 Ops.erase(Ops.begin()+Idx);
854 Ops.erase(Ops.begin()+OtherMulIdx-1);
855 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000856 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000857 }
858 }
859 }
860 }
861
862 // If there are any add recurrences in the operands list, see if any other
863 // added values are loop invariant. If so, we can fold them into the
864 // recurrence.
865 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
866 ++Idx;
867
868 // Scan over all recurrences, trying to fold loop invariants into them.
869 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
870 // Scan all of the other operands to this add and add them to the vector if
871 // they are loop invariant w.r.t. the recurrence.
872 std::vector<SCEVHandle> LIOps;
873 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
874 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
875 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
876 LIOps.push_back(Ops[i]);
877 Ops.erase(Ops.begin()+i);
878 --i; --e;
879 }
880
881 // If we found some loop invariants, fold them into the recurrence.
882 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +0000883 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000884 LIOps.push_back(AddRec->getStart());
885
886 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +0000887 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000888
Dan Gohman89f85052007-10-22 18:31:58 +0000889 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000890 // If all of the other operands were loop invariant, we are done.
891 if (Ops.size() == 1) return NewRec;
892
893 // Otherwise, add the folded AddRec by the non-liv parts.
894 for (unsigned i = 0;; ++i)
895 if (Ops[i] == AddRec) {
896 Ops[i] = NewRec;
897 break;
898 }
Dan Gohman89f85052007-10-22 18:31:58 +0000899 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000900 }
901
902 // Okay, if there weren't any loop invariants to be folded, check to see if
903 // there are multiple AddRec's with the same loop induction variable being
904 // added together. If so, we can fold them.
905 for (unsigned OtherIdx = Idx+1;
906 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
907 if (OtherIdx != Idx) {
908 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
909 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
910 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
911 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
912 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
913 if (i >= NewOps.size()) {
914 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
915 OtherAddRec->op_end());
916 break;
917 }
Dan Gohman89f85052007-10-22 18:31:58 +0000918 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000919 }
Dan Gohman89f85052007-10-22 18:31:58 +0000920 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000921
922 if (Ops.size() == 2) return NewAddRec;
923
924 Ops.erase(Ops.begin()+Idx);
925 Ops.erase(Ops.begin()+OtherIdx-1);
926 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +0000927 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000928 }
929 }
930
931 // Otherwise couldn't fold anything into this recurrence. Move onto the
932 // next one.
933 }
934
935 // Okay, it looks like we really DO need an add expr. Check to see if we
936 // already have one, otherwise create a new one.
937 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
938 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
939 SCEVOps)];
940 if (Result == 0) Result = new SCEVAddExpr(Ops);
941 return Result;
942}
943
944
Dan Gohman89f85052007-10-22 18:31:58 +0000945SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000946 assert(!Ops.empty() && "Cannot get empty mul!");
947
948 // Sort by complexity, this groups all similar expression types together.
949 GroupByComplexity(Ops);
950
951 // If there are any constants, fold them together.
952 unsigned Idx = 0;
953 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
954
955 // C1*(C2+V) -> C1*C2 + C1*V
956 if (Ops.size() == 2)
957 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
958 if (Add->getNumOperands() == 2 &&
959 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +0000960 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
961 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000962
963
964 ++Idx;
965 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
966 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000967 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
968 RHSC->getValue()->getValue());
969 Ops[0] = getConstant(Fold);
970 Ops.erase(Ops.begin()+1); // Erase the folded element
971 if (Ops.size() == 1) return Ops[0];
972 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000973 }
974
975 // If we are left with a constant one being multiplied, strip it off.
976 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
977 Ops.erase(Ops.begin());
978 --Idx;
979 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
980 // If we have a multiply of zero, it will always be zero.
981 return Ops[0];
982 }
983 }
984
985 // Skip over the add expression until we get to a multiply.
986 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
987 ++Idx;
988
989 if (Ops.size() == 1)
990 return Ops[0];
991
992 // If there are mul operands inline them all into this expression.
993 if (Idx < Ops.size()) {
994 bool DeletedMul = false;
995 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
996 // If we have an mul, expand the mul operands onto the end of the operands
997 // list.
998 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
999 Ops.erase(Ops.begin()+Idx);
1000 DeletedMul = true;
1001 }
1002
1003 // If we deleted at least one mul, we added operands to the end of the list,
1004 // and they are not necessarily sorted. Recurse to resort and resimplify
1005 // any operands we just aquired.
1006 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001007 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001008 }
1009
1010 // If there are any add recurrences in the operands list, see if any other
1011 // added values are loop invariant. If so, we can fold them into the
1012 // recurrence.
1013 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1014 ++Idx;
1015
1016 // Scan over all recurrences, trying to fold loop invariants into them.
1017 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1018 // Scan all of the other operands to this mul and add them to the vector if
1019 // they are loop invariant w.r.t. the recurrence.
1020 std::vector<SCEVHandle> LIOps;
1021 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1022 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1023 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1024 LIOps.push_back(Ops[i]);
1025 Ops.erase(Ops.begin()+i);
1026 --i; --e;
1027 }
1028
1029 // If we found some loop invariants, fold them into the recurrence.
1030 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001031 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001032 std::vector<SCEVHandle> NewOps;
1033 NewOps.reserve(AddRec->getNumOperands());
1034 if (LIOps.size() == 1) {
1035 SCEV *Scale = LIOps[0];
1036 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001037 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001038 } else {
1039 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1040 std::vector<SCEVHandle> MulOps(LIOps);
1041 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001042 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043 }
1044 }
1045
Dan Gohman89f85052007-10-22 18:31:58 +00001046 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001047
1048 // If all of the other operands were loop invariant, we are done.
1049 if (Ops.size() == 1) return NewRec;
1050
1051 // Otherwise, multiply the folded AddRec by the non-liv parts.
1052 for (unsigned i = 0;; ++i)
1053 if (Ops[i] == AddRec) {
1054 Ops[i] = NewRec;
1055 break;
1056 }
Dan Gohman89f85052007-10-22 18:31:58 +00001057 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001058 }
1059
1060 // Okay, if there weren't any loop invariants to be folded, check to see if
1061 // there are multiple AddRec's with the same loop induction variable being
1062 // multiplied together. If so, we can fold them.
1063 for (unsigned OtherIdx = Idx+1;
1064 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1065 if (OtherIdx != Idx) {
1066 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1067 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1068 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1069 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001070 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001071 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001072 SCEVHandle B = F->getStepRecurrence(*this);
1073 SCEVHandle D = G->getStepRecurrence(*this);
1074 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1075 getMulExpr(G, B),
1076 getMulExpr(B, D));
1077 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1078 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001079 if (Ops.size() == 2) return NewAddRec;
1080
1081 Ops.erase(Ops.begin()+Idx);
1082 Ops.erase(Ops.begin()+OtherIdx-1);
1083 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001084 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001085 }
1086 }
1087
1088 // Otherwise couldn't fold anything into this recurrence. Move onto the
1089 // next one.
1090 }
1091
1092 // Okay, it looks like we really DO need an mul expr. Check to see if we
1093 // already have one, otherwise create a new one.
1094 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1095 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1096 SCEVOps)];
1097 if (Result == 0)
1098 Result = new SCEVMulExpr(Ops);
1099 return Result;
1100}
1101
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001102SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1104 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001105 return LHS; // X udiv 1 --> x
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001106
1107 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1108 Constant *LHSCV = LHSC->getValue();
1109 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001110 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001111 }
1112 }
1113
Nick Lewycky35b56022009-01-13 09:18:58 +00001114 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1115
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001116 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1117 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001118 return Result;
1119}
1120
1121
1122/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1123/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001124SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001125 const SCEVHandle &Step, const Loop *L) {
1126 std::vector<SCEVHandle> Operands;
1127 Operands.push_back(Start);
1128 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1129 if (StepChrec->getLoop() == L) {
1130 Operands.insert(Operands.end(), StepChrec->op_begin(),
1131 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001132 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001133 }
1134
1135 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001136 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001137}
1138
1139/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1140/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001141SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001142 const Loop *L) {
1143 if (Operands.size() == 1) return Operands[0];
1144
Dan Gohman7b560c42008-06-18 16:23:07 +00001145 if (Operands.back()->isZero()) {
1146 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001147 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001148 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001149
Dan Gohman42936882008-08-08 18:33:12 +00001150 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1151 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1152 const Loop* NestedLoop = NestedAR->getLoop();
1153 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1154 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1155 NestedAR->op_end());
1156 SCEVHandle NestedARHandle(NestedAR);
1157 Operands[0] = NestedAR->getStart();
1158 NestedOperands[0] = getAddRecExpr(Operands, L);
1159 return getAddRecExpr(NestedOperands, NestedLoop);
1160 }
1161 }
1162
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001163 SCEVAddRecExpr *&Result =
1164 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1165 Operands.end()))];
1166 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1167 return Result;
1168}
1169
Nick Lewycky711640a2007-11-25 22:41:31 +00001170SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1171 const SCEVHandle &RHS) {
1172 std::vector<SCEVHandle> Ops;
1173 Ops.push_back(LHS);
1174 Ops.push_back(RHS);
1175 return getSMaxExpr(Ops);
1176}
1177
1178SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1179 assert(!Ops.empty() && "Cannot get empty smax!");
1180 if (Ops.size() == 1) return Ops[0];
1181
1182 // Sort by complexity, this groups all similar expression types together.
1183 GroupByComplexity(Ops);
1184
1185 // If there are any constants, fold them together.
1186 unsigned Idx = 0;
1187 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1188 ++Idx;
1189 assert(Idx < Ops.size());
1190 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1191 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001192 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001193 APIntOps::smax(LHSC->getValue()->getValue(),
1194 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001195 Ops[0] = getConstant(Fold);
1196 Ops.erase(Ops.begin()+1); // Erase the folded element
1197 if (Ops.size() == 1) return Ops[0];
1198 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001199 }
1200
1201 // If we are left with a constant -inf, strip it off.
1202 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1203 Ops.erase(Ops.begin());
1204 --Idx;
1205 }
1206 }
1207
1208 if (Ops.size() == 1) return Ops[0];
1209
1210 // Find the first SMax
1211 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1212 ++Idx;
1213
1214 // Check to see if one of the operands is an SMax. If so, expand its operands
1215 // onto our operand list, and recurse to simplify.
1216 if (Idx < Ops.size()) {
1217 bool DeletedSMax = false;
1218 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1219 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1220 Ops.erase(Ops.begin()+Idx);
1221 DeletedSMax = true;
1222 }
1223
1224 if (DeletedSMax)
1225 return getSMaxExpr(Ops);
1226 }
1227
1228 // Okay, check to see if the same value occurs in the operand list twice. If
1229 // so, delete one. Since we sorted the list, these values are required to
1230 // be adjacent.
1231 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1232 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1233 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1234 --i; --e;
1235 }
1236
1237 if (Ops.size() == 1) return Ops[0];
1238
1239 assert(!Ops.empty() && "Reduced smax down to nothing!");
1240
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001241 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001242 // already have one, otherwise create a new one.
1243 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1244 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1245 SCEVOps)];
1246 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1247 return Result;
1248}
1249
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001250SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1251 const SCEVHandle &RHS) {
1252 std::vector<SCEVHandle> Ops;
1253 Ops.push_back(LHS);
1254 Ops.push_back(RHS);
1255 return getUMaxExpr(Ops);
1256}
1257
1258SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1259 assert(!Ops.empty() && "Cannot get empty umax!");
1260 if (Ops.size() == 1) return Ops[0];
1261
1262 // Sort by complexity, this groups all similar expression types together.
1263 GroupByComplexity(Ops);
1264
1265 // If there are any constants, fold them together.
1266 unsigned Idx = 0;
1267 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1268 ++Idx;
1269 assert(Idx < Ops.size());
1270 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1271 // We found two constants, fold them together!
1272 ConstantInt *Fold = ConstantInt::get(
1273 APIntOps::umax(LHSC->getValue()->getValue(),
1274 RHSC->getValue()->getValue()));
1275 Ops[0] = getConstant(Fold);
1276 Ops.erase(Ops.begin()+1); // Erase the folded element
1277 if (Ops.size() == 1) return Ops[0];
1278 LHSC = cast<SCEVConstant>(Ops[0]);
1279 }
1280
1281 // If we are left with a constant zero, strip it off.
1282 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1283 Ops.erase(Ops.begin());
1284 --Idx;
1285 }
1286 }
1287
1288 if (Ops.size() == 1) return Ops[0];
1289
1290 // Find the first UMax
1291 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1292 ++Idx;
1293
1294 // Check to see if one of the operands is a UMax. If so, expand its operands
1295 // onto our operand list, and recurse to simplify.
1296 if (Idx < Ops.size()) {
1297 bool DeletedUMax = false;
1298 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1299 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1300 Ops.erase(Ops.begin()+Idx);
1301 DeletedUMax = true;
1302 }
1303
1304 if (DeletedUMax)
1305 return getUMaxExpr(Ops);
1306 }
1307
1308 // Okay, check to see if the same value occurs in the operand list twice. If
1309 // so, delete one. Since we sorted the list, these values are required to
1310 // be adjacent.
1311 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1312 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1313 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1314 --i; --e;
1315 }
1316
1317 if (Ops.size() == 1) return Ops[0];
1318
1319 assert(!Ops.empty() && "Reduced umax down to nothing!");
1320
1321 // Okay, it looks like we really DO need a umax expr. Check to see if we
1322 // already have one, otherwise create a new one.
1323 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1324 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1325 SCEVOps)];
1326 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1327 return Result;
1328}
1329
Dan Gohman89f85052007-10-22 18:31:58 +00001330SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001331 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001332 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001333 if (isa<ConstantPointerNull>(V))
1334 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001335 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1336 if (Result == 0) Result = new SCEVUnknown(V);
1337 return Result;
1338}
1339
1340
1341//===----------------------------------------------------------------------===//
1342// ScalarEvolutionsImpl Definition and Implementation
1343//===----------------------------------------------------------------------===//
1344//
1345/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1346/// evolution code.
1347///
1348namespace {
1349 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohman89f85052007-10-22 18:31:58 +00001350 /// SE - A reference to the public ScalarEvolution object.
1351 ScalarEvolution &SE;
1352
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001353 /// F - The function we are analyzing.
1354 ///
1355 Function &F;
1356
1357 /// LI - The loop information for the function we are currently analyzing.
1358 ///
1359 LoopInfo &LI;
1360
Dan Gohman01c2ee72009-04-16 03:18:22 +00001361 /// TD - The target data information for the target we are targetting.
1362 ///
1363 TargetData &TD;
1364
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001365 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1366 /// things.
1367 SCEVHandle UnknownValue;
1368
1369 /// Scalars - This is a cache of the scalars we have analyzed so far.
1370 ///
1371 std::map<Value*, SCEVHandle> Scalars;
1372
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001373 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
1374 /// this function as they are computed.
1375 std::map<const Loop*, SCEVHandle> BackedgeTakenCounts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001376
1377 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1378 /// the PHI instructions that we attempt to compute constant evolutions for.
1379 /// This allows us to avoid potentially expensive recomputation of these
1380 /// properties. An instruction maps to null if we are unable to compute its
1381 /// exit value.
1382 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1383
1384 public:
Dan Gohman01c2ee72009-04-16 03:18:22 +00001385 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li,
1386 TargetData &td)
1387 : SE(se), F(f), LI(li), TD(td), UnknownValue(new SCEVCouldNotCompute()) {}
1388
1389 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
1390 /// specified signed integer value and return a SCEV for the constant.
1391 SCEVHandle getIntegerSCEV(int Val, const Type *Ty);
1392
1393 /// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1394 ///
1395 SCEVHandle getNegativeSCEV(const SCEVHandle &V);
1396
1397 /// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
1398 ///
1399 SCEVHandle getNotSCEV(const SCEVHandle &V);
1400
1401 /// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1402 ///
1403 SCEVHandle getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS);
1404
1405 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
1406 /// of the input value to the specified type. If the type must be extended,
1407 /// it is zero extended.
1408 SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty);
1409
1410 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
1411 /// of the input value to the specified type. If the type must be extended,
1412 /// it is sign extended.
1413 SCEVHandle getTruncateOrSignExtend(const SCEVHandle &V, const Type *Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001414
1415 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1416 /// expression and create a new one.
1417 SCEVHandle getSCEV(Value *V);
1418
1419 /// hasSCEV - Return true if the SCEV for this value has already been
1420 /// computed.
1421 bool hasSCEV(Value *V) const {
1422 return Scalars.count(V);
1423 }
1424
1425 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1426 /// the specified value.
1427 void setSCEV(Value *V, const SCEVHandle &H) {
1428 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1429 assert(isNew && "This entry already existed!");
Devang Patelfc736502008-11-11 19:17:41 +00001430 isNew = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001431 }
1432
1433
1434 /// getSCEVAtScope - Compute the value of the specified expression within
1435 /// the indicated loop (which may be null to indicate in no loop). If the
1436 /// expression cannot be evaluated, return UnknownValue itself.
1437 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1438
1439
Dan Gohmancacd2012009-02-12 22:19:27 +00001440 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
1441 /// a conditional between LHS and RHS.
1442 bool isLoopGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
1443 SCEV *LHS, SCEV *RHS);
1444
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001445 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
1446 /// has an analyzable loop-invariant backedge-taken count.
1447 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001448
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001449 /// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00001450 /// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001451 /// ScalarEvolution's ability to compute a trip count, or if the loop
1452 /// is deleted.
1453 void forgetLoopBackedgeTakenCount(const Loop *L);
Dan Gohmanf3a060a2009-02-17 20:49:49 +00001454
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001455 /// getBackedgeTakenCount - If the specified loop has a predictable
1456 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
1457 /// object. The backedge-taken count is the number of times the loop header
1458 /// will be branched to from within the loop. This is one less than the
1459 /// trip count of the loop, since it doesn't count the first iteration,
1460 /// when the header is branched to from outside the loop.
1461 ///
1462 /// Note that it is not valid to call this method on a loop without a
1463 /// loop-invariant backedge-taken count (see
1464 /// hasLoopInvariantBackedgeTakenCount).
1465 ///
1466 SCEVHandle getBackedgeTakenCount(const Loop *L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001467
1468 /// deleteValueFromRecords - This method should be called by the
1469 /// client before it removes a value from the program, to make sure
1470 /// that no dangling references are left around.
1471 void deleteValueFromRecords(Value *V);
1472
Dan Gohman01c2ee72009-04-16 03:18:22 +00001473 /// getTargetData - Return the TargetData.
1474 const TargetData &getTargetData() const;
1475
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001476 private:
1477 /// createSCEV - We know that there is no SCEV for the specified value.
1478 /// Analyze the expression.
1479 SCEVHandle createSCEV(Value *V);
1480
1481 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1482 /// SCEVs.
1483 SCEVHandle createNodeForPHI(PHINode *PN);
1484
1485 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1486 /// for the specified instruction and replaces any references to the
1487 /// symbolic value SymName with the specified value. This is used during
1488 /// PHI resolution.
1489 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1490 const SCEVHandle &SymName,
1491 const SCEVHandle &NewVal);
1492
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001493 /// ComputeBackedgeTakenCount - Compute the number of times the specified
1494 /// loop will iterate.
1495 SCEVHandle ComputeBackedgeTakenCount(const Loop *L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001496
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001497 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition
1498 /// of 'icmp op load X, cst', try to see if we can compute the trip count.
1499 SCEVHandle
1500 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI,
1501 Constant *RHS,
1502 const Loop *L,
1503 ICmpInst::Predicate p);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001504
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001505 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute
1506 /// a constant number of times (the condition evolves only from constants),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001507 /// try to evaluate a few iterations of the loop until we get the exit
1508 /// condition gets a value of ExitWhen (true or false). If we cannot
1509 /// evaluate the trip count of the loop, return UnknownValue.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001510 SCEVHandle ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond,
1511 bool ExitWhen);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001512
1513 /// HowFarToZero - Return the number of times a backedge comparing the
1514 /// specified value to zero will execute. If not computable, return
1515 /// UnknownValue.
1516 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1517
1518 /// HowFarToNonZero - Return the number of times a backedge checking the
1519 /// specified value for nonzero will execute. If not computable, return
1520 /// UnknownValue.
1521 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1522
1523 /// HowManyLessThans - Return the number of times a backedge containing the
1524 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyb7c28942007-08-06 19:21:00 +00001525 /// UnknownValue. isSigned specifies whether the less-than is signed.
1526 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
Nick Lewycky35b56022009-01-13 09:18:58 +00001527 bool isSigned);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001528
Dan Gohman1cddf972008-09-15 22:18:04 +00001529 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
1530 /// (which may not be an immediate predecessor) which has exactly one
1531 /// successor from which BB is reachable, or null if no such block is
1532 /// found.
1533 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1534
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001535 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1536 /// in the header of its containing loop, we know the loop executes a
1537 /// constant number of times, and the PHI node is just a recurrence
1538 /// involving constants, fold it.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00001539 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001540 const Loop *L);
1541 };
1542}
1543
1544//===----------------------------------------------------------------------===//
1545// Basic SCEV Analysis and PHI Idiom Recognition Code
1546//
1547
1548/// deleteValueFromRecords - This method should be called by the
1549/// client before it removes an instruction from the program, to make sure
1550/// that no dangling references are left around.
1551void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1552 SmallVector<Value *, 16> Worklist;
1553
1554 if (Scalars.erase(V)) {
1555 if (PHINode *PN = dyn_cast<PHINode>(V))
1556 ConstantEvolutionLoopExitValue.erase(PN);
1557 Worklist.push_back(V);
1558 }
1559
1560 while (!Worklist.empty()) {
1561 Value *VV = Worklist.back();
1562 Worklist.pop_back();
1563
1564 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1565 UI != UE; ++UI) {
1566 Instruction *Inst = cast<Instruction>(*UI);
1567 if (Scalars.erase(Inst)) {
1568 if (PHINode *PN = dyn_cast<PHINode>(VV))
1569 ConstantEvolutionLoopExitValue.erase(PN);
1570 Worklist.push_back(Inst);
1571 }
1572 }
1573 }
1574}
1575
Dan Gohman01c2ee72009-04-16 03:18:22 +00001576const TargetData &ScalarEvolutionsImpl::getTargetData() const {
1577 return TD;
1578}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001579
1580/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1581/// expression and create a new one.
1582SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1583 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1584
1585 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1586 if (I != Scalars.end()) return I->second;
1587 SCEVHandle S = createSCEV(V);
1588 Scalars.insert(std::make_pair(V, S));
1589 return S;
1590}
1591
Dan Gohman01c2ee72009-04-16 03:18:22 +00001592/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1593/// specified signed integer value and return a SCEV for the constant.
1594SCEVHandle ScalarEvolutionsImpl::getIntegerSCEV(int Val, const Type *Ty) {
1595 if (isa<PointerType>(Ty))
1596 Ty = TD.getIntPtrType();
1597 Constant *C;
1598 if (Val == 0)
1599 C = Constant::getNullValue(Ty);
1600 else if (Ty->isFloatingPoint())
1601 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1602 APFloat::IEEEdouble, Val));
1603 else
1604 C = ConstantInt::get(Ty, Val);
1605 return SE.getUnknown(C);
1606}
1607
1608/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1609///
1610SCEVHandle ScalarEvolutionsImpl::getNegativeSCEV(const SCEVHandle &V) {
1611 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1612 return SE.getUnknown(ConstantExpr::getNeg(VC->getValue()));
1613
1614 const Type *Ty = V->getType();
1615 if (isa<PointerType>(Ty))
1616 Ty = TD.getIntPtrType();
1617 return SE.getMulExpr(V, SE.getConstant(ConstantInt::getAllOnesValue(Ty)));
1618}
1619
1620/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
1621SCEVHandle ScalarEvolutionsImpl::getNotSCEV(const SCEVHandle &V) {
1622 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
1623 return SE.getUnknown(ConstantExpr::getNot(VC->getValue()));
1624
1625 const Type *Ty = V->getType();
1626 if (isa<PointerType>(Ty))
1627 Ty = TD.getIntPtrType();
1628 SCEVHandle AllOnes = SE.getConstant(ConstantInt::getAllOnesValue(Ty));
1629 return getMinusSCEV(AllOnes, V);
1630}
1631
1632/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1633///
1634SCEVHandle ScalarEvolutionsImpl::getMinusSCEV(const SCEVHandle &LHS,
1635 const SCEVHandle &RHS) {
1636 // X - Y --> X + -Y
1637 return SE.getAddExpr(LHS, SE.getNegativeSCEV(RHS));
1638}
1639
1640/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1641/// input value to the specified type. If the type must be extended, it is zero
1642/// extended.
1643SCEVHandle
1644ScalarEvolutionsImpl::getTruncateOrZeroExtend(const SCEVHandle &V,
1645 const Type *Ty) {
1646 const Type *SrcTy = V->getType();
1647 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
1648 (Ty->isInteger() || isa<PointerType>(Ty)) &&
1649 "Cannot truncate or zero extend with non-integer arguments!");
1650 if (TD.getTypeSizeInBits(SrcTy) == TD.getTypeSizeInBits(Ty))
1651 return V; // No conversion
1652 if (TD.getTypeSizeInBits(SrcTy) > TD.getTypeSizeInBits(Ty))
1653 return SE.getTruncateExpr(V, Ty);
1654 return SE.getZeroExtendExpr(V, Ty);
1655}
1656
1657/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1658/// input value to the specified type. If the type must be extended, it is sign
1659/// extended.
1660SCEVHandle
1661ScalarEvolutionsImpl::getTruncateOrSignExtend(const SCEVHandle &V,
1662 const Type *Ty) {
1663 const Type *SrcTy = V->getType();
1664 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
1665 (Ty->isInteger() || isa<PointerType>(Ty)) &&
1666 "Cannot truncate or zero extend with non-integer arguments!");
1667 if (TD.getTypeSizeInBits(SrcTy) == TD.getTypeSizeInBits(Ty))
1668 return V; // No conversion
1669 if (TD.getTypeSizeInBits(SrcTy) > TD.getTypeSizeInBits(Ty))
1670 return SE.getTruncateExpr(V, Ty);
1671 return SE.getSignExtendExpr(V, Ty);
1672}
1673
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001674/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1675/// the specified instruction and replaces any references to the symbolic value
1676/// SymName with the specified value. This is used during PHI resolution.
1677void ScalarEvolutionsImpl::
1678ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1679 const SCEVHandle &NewVal) {
1680 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1681 if (SI == Scalars.end()) return;
1682
1683 SCEVHandle NV =
Dan Gohman89f85052007-10-22 18:31:58 +00001684 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001685 if (NV == SI->second) return; // No change.
1686
1687 SI->second = NV; // Update the scalars map!
1688
1689 // Any instruction values that use this instruction might also need to be
1690 // updated!
1691 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1692 UI != E; ++UI)
1693 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1694}
1695
1696/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1697/// a loop header, making it a potential recurrence, or it doesn't.
1698///
1699SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1700 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1701 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1702 if (L->getHeader() == PN->getParent()) {
1703 // If it lives in the loop header, it has two incoming values, one
1704 // from outside the loop, and one from inside.
1705 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1706 unsigned BackEdge = IncomingEdge^1;
1707
1708 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman89f85052007-10-22 18:31:58 +00001709 SCEVHandle SymbolicName = SE.getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001710 assert(Scalars.find(PN) == Scalars.end() &&
1711 "PHI node already processed?");
1712 Scalars.insert(std::make_pair(PN, SymbolicName));
1713
1714 // Using this symbolic name for the PHI, analyze the value coming around
1715 // the back-edge.
1716 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1717
1718 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1719 // has a special value for the first iteration of the loop.
1720
1721 // If the value coming around the backedge is an add with the symbolic
1722 // value we just inserted, then we found a simple induction variable!
1723 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1724 // If there is a single occurrence of the symbolic value, replace it
1725 // with a recurrence.
1726 unsigned FoundIndex = Add->getNumOperands();
1727 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1728 if (Add->getOperand(i) == SymbolicName)
1729 if (FoundIndex == e) {
1730 FoundIndex = i;
1731 break;
1732 }
1733
1734 if (FoundIndex != Add->getNumOperands()) {
1735 // Create an add with everything but the specified operand.
1736 std::vector<SCEVHandle> Ops;
1737 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1738 if (i != FoundIndex)
1739 Ops.push_back(Add->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001740 SCEVHandle Accum = SE.getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001741
1742 // This is not a valid addrec if the step amount is varying each
1743 // loop iteration, but is not itself an addrec in this loop.
1744 if (Accum->isLoopInvariant(L) ||
1745 (isa<SCEVAddRecExpr>(Accum) &&
1746 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1747 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman89f85052007-10-22 18:31:58 +00001748 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001749
1750 // Okay, for the entire analysis of this edge we assumed the PHI
1751 // to be symbolic. We now need to go back and update all of the
1752 // entries for the scalars that use the PHI (except for the PHI
1753 // itself) to use the new analyzed value instead of the "symbolic"
1754 // value.
1755 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1756 return PHISCEV;
1757 }
1758 }
1759 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1760 // Otherwise, this could be a loop like this:
1761 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1762 // In this case, j = {1,+,1} and BEValue is j.
1763 // Because the other in-value of i (0) fits the evolution of BEValue
1764 // i really is an addrec evolution.
1765 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1766 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1767
1768 // If StartVal = j.start - j.stride, we can use StartVal as the
1769 // initial step of the addrec evolution.
Dan Gohman89f85052007-10-22 18:31:58 +00001770 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1771 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001772 SCEVHandle PHISCEV =
Dan Gohman89f85052007-10-22 18:31:58 +00001773 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001774
1775 // Okay, for the entire analysis of this edge we assumed the PHI
1776 // to be symbolic. We now need to go back and update all of the
1777 // entries for the scalars that use the PHI (except for the PHI
1778 // itself) to use the new analyzed value instead of the "symbolic"
1779 // value.
1780 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1781 return PHISCEV;
1782 }
1783 }
1784 }
1785
1786 return SymbolicName;
1787 }
1788
1789 // If it's not a loop phi, we can't handle it yet.
Dan Gohman89f85052007-10-22 18:31:58 +00001790 return SE.getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001791}
1792
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001793/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1794/// guaranteed to end in (at every loop iteration). It is, at the same time,
1795/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1796/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001797static uint32_t GetMinTrailingZeros(SCEVHandle S, const TargetData &TD) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001798 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001799 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001800
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001801 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001802 return std::min(GetMinTrailingZeros(T->getOperand(), TD),
1803 (uint32_t)TD.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001804
1805 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001806 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), TD);
1807 return OpRes == TD.getTypeSizeInBits(E->getOperand()->getType()) ?
1808 TD.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001809 }
1810
1811 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001812 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), TD);
1813 return OpRes == TD.getTypeSizeInBits(E->getOperand()->getType()) ?
1814 TD.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001815 }
1816
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001817 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001818 // The result is the min of all operands results.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001819 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), TD);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001820 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman01c2ee72009-04-16 03:18:22 +00001821 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), TD));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001822 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001823 }
1824
1825 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001826 // The result is the sum of all operands results.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001827 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), TD);
1828 uint32_t BitWidth = TD.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001829 for (unsigned i = 1, e = M->getNumOperands();
1830 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman01c2ee72009-04-16 03:18:22 +00001831 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), TD),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001832 BitWidth);
1833 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001834 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001835
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001836 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001837 // The result is the min of all operands results.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001838 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), TD);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001839 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman01c2ee72009-04-16 03:18:22 +00001840 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), TD));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001841 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001842 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001843
Nick Lewycky711640a2007-11-25 22:41:31 +00001844 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1845 // The result is the min of all operands results.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001846 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), TD);
Nick Lewycky711640a2007-11-25 22:41:31 +00001847 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman01c2ee72009-04-16 03:18:22 +00001848 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), TD));
Nick Lewycky711640a2007-11-25 22:41:31 +00001849 return MinOpRes;
1850 }
1851
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001852 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1853 // The result is the min of all operands results.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001854 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), TD);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001855 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman01c2ee72009-04-16 03:18:22 +00001856 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), TD));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001857 return MinOpRes;
1858 }
1859
Nick Lewycky35b56022009-01-13 09:18:58 +00001860 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001861 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001862}
1863
1864/// createSCEV - We know that there is no SCEV for the specified value.
1865/// Analyze the expression.
1866///
1867SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001868 if (!isa<IntegerType>(V->getType()) &&
1869 !isa<PointerType>(V->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00001870 return SE.getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001871
Dan Gohman3996f472008-06-22 19:56:46 +00001872 unsigned Opcode = Instruction::UserOp1;
1873 if (Instruction *I = dyn_cast<Instruction>(V))
1874 Opcode = I->getOpcode();
1875 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1876 Opcode = CE->getOpcode();
1877 else
1878 return SE.getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001879
Dan Gohman3996f472008-06-22 19:56:46 +00001880 User *U = cast<User>(V);
1881 switch (Opcode) {
1882 case Instruction::Add:
1883 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1884 getSCEV(U->getOperand(1)));
1885 case Instruction::Mul:
1886 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1887 getSCEV(U->getOperand(1)));
1888 case Instruction::UDiv:
1889 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1890 getSCEV(U->getOperand(1)));
1891 case Instruction::Sub:
1892 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1893 getSCEV(U->getOperand(1)));
1894 case Instruction::Or:
1895 // If the RHS of the Or is a constant, we may have something like:
1896 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1897 // optimizations will transparently handle this case.
1898 //
1899 // In order for this transformation to be safe, the LHS must be of the
1900 // form X*(2^n) and the Or constant must be less than 2^n.
1901 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1902 SCEVHandle LHS = getSCEV(U->getOperand(0));
1903 const APInt &CIVal = CI->getValue();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001904 if (GetMinTrailingZeros(LHS, TD) >=
Dan Gohman3996f472008-06-22 19:56:46 +00001905 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1906 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001907 }
Dan Gohman3996f472008-06-22 19:56:46 +00001908 break;
1909 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00001910 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00001911 // If the RHS of the xor is a signbit, then this is just an add.
1912 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00001913 if (CI->getValue().isSignBit())
1914 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1915 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001916
1917 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman3996f472008-06-22 19:56:46 +00001918 else if (CI->isAllOnesValue())
1919 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1920 }
1921 break;
1922
1923 case Instruction::Shl:
1924 // Turn shift left of a constant amount into a multiply.
1925 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1926 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1927 Constant *X = ConstantInt::get(
1928 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1929 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1930 }
1931 break;
1932
Nick Lewycky7fd27892008-07-07 06:15:49 +00001933 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00001934 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00001935 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1936 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1937 Constant *X = ConstantInt::get(
1938 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1939 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1940 }
1941 break;
1942
Dan Gohman3996f472008-06-22 19:56:46 +00001943 case Instruction::Trunc:
1944 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1945
1946 case Instruction::ZExt:
1947 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1948
1949 case Instruction::SExt:
1950 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1951
1952 case Instruction::BitCast:
1953 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohman01c2ee72009-04-16 03:18:22 +00001954 if ((U->getType()->isInteger() ||
1955 isa<PointerType>(U->getType())) &&
1956 (U->getOperand(0)->getType()->isInteger() ||
1957 isa<PointerType>(U->getOperand(0)->getType())))
Dan Gohman3996f472008-06-22 19:56:46 +00001958 return getSCEV(U->getOperand(0));
1959 break;
1960
Dan Gohman01c2ee72009-04-16 03:18:22 +00001961 case Instruction::IntToPtr:
1962 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1963 TD.getIntPtrType());
1964
1965 case Instruction::PtrToInt:
1966 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1967 U->getType());
1968
1969 case Instruction::GetElementPtr: {
1970 const Type *IntPtrTy = TD.getIntPtrType();
1971 Value *Base = U->getOperand(0);
1972 SCEVHandle TotalOffset = SE.getIntegerSCEV(0, IntPtrTy);
1973 gep_type_iterator GTI = gep_type_begin(U);
1974 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
1975 E = U->op_end();
1976 I != E; ++I) {
1977 Value *Index = *I;
1978 // Compute the (potentially symbolic) offset in bytes for this index.
1979 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1980 // For a struct, add the member offset.
1981 const StructLayout &SL = *TD.getStructLayout(STy);
1982 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1983 uint64_t Offset = SL.getElementOffset(FieldNo);
1984 TotalOffset = SE.getAddExpr(TotalOffset,
1985 SE.getIntegerSCEV(Offset, IntPtrTy));
1986 } else {
1987 // For an array, add the element offset, explicitly scaled.
1988 SCEVHandle LocalOffset = getSCEV(Index);
1989 if (!isa<PointerType>(LocalOffset->getType()))
1990 // Getelementptr indicies are signed.
1991 LocalOffset = getTruncateOrSignExtend(LocalOffset,
1992 IntPtrTy);
1993 LocalOffset =
1994 SE.getMulExpr(LocalOffset,
1995 SE.getIntegerSCEV(TD.getTypePaddedSize(*GTI),
1996 IntPtrTy));
1997 TotalOffset = SE.getAddExpr(TotalOffset, LocalOffset);
1998 }
1999 }
2000 return SE.getAddExpr(getSCEV(Base), TotalOffset);
2001 }
2002
Dan Gohman3996f472008-06-22 19:56:46 +00002003 case Instruction::PHI:
2004 return createNodeForPHI(cast<PHINode>(U));
2005
2006 case Instruction::Select:
2007 // This could be a smax or umax that was lowered earlier.
2008 // Try to recover it.
2009 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2010 Value *LHS = ICI->getOperand(0);
2011 Value *RHS = ICI->getOperand(1);
2012 switch (ICI->getPredicate()) {
2013 case ICmpInst::ICMP_SLT:
2014 case ICmpInst::ICMP_SLE:
2015 std::swap(LHS, RHS);
2016 // fall through
2017 case ICmpInst::ICMP_SGT:
2018 case ICmpInst::ICMP_SGE:
2019 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2020 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
2021 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00002022 // ~smax(~x, ~y) == smin(x, y).
2023 return SE.getNotSCEV(SE.getSMaxExpr(
2024 SE.getNotSCEV(getSCEV(LHS)),
2025 SE.getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002026 break;
2027 case ICmpInst::ICMP_ULT:
2028 case ICmpInst::ICMP_ULE:
2029 std::swap(LHS, RHS);
2030 // fall through
2031 case ICmpInst::ICMP_UGT:
2032 case ICmpInst::ICMP_UGE:
2033 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
2034 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
2035 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2036 // ~umax(~x, ~y) == umin(x, y)
2037 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
2038 SE.getNotSCEV(getSCEV(RHS))));
2039 break;
2040 default:
2041 break;
2042 }
2043 }
2044
2045 default: // We cannot analyze this expression.
2046 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002047 }
2048
Dan Gohman89f85052007-10-22 18:31:58 +00002049 return SE.getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002050}
2051
2052
2053
2054//===----------------------------------------------------------------------===//
2055// Iteration Count Computation Code
2056//
2057
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002058/// getBackedgeTakenCount - If the specified loop has a predictable
2059/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2060/// object. The backedge-taken count is the number of times the loop header
2061/// will be branched to from within the loop. This is one less than the
2062/// trip count of the loop, since it doesn't count the first iteration,
2063/// when the header is branched to from outside the loop.
2064///
2065/// Note that it is not valid to call this method on a loop without a
2066/// loop-invariant backedge-taken count (see
2067/// hasLoopInvariantBackedgeTakenCount).
2068///
2069SCEVHandle ScalarEvolutionsImpl::getBackedgeTakenCount(const Loop *L) {
2070 std::map<const Loop*, SCEVHandle>::iterator I = BackedgeTakenCounts.find(L);
2071 if (I == BackedgeTakenCounts.end()) {
2072 SCEVHandle ItCount = ComputeBackedgeTakenCount(L);
2073 I = BackedgeTakenCounts.insert(std::make_pair(L, ItCount)).first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002074 if (ItCount != UnknownValue) {
2075 assert(ItCount->isLoopInvariant(L) &&
2076 "Computed trip count isn't loop invariant for loop!");
2077 ++NumTripCountsComputed;
2078 } else if (isa<PHINode>(L->getHeader()->begin())) {
2079 // Only count loops that have phi nodes as not being computable.
2080 ++NumTripCountsNotComputed;
2081 }
2082 }
2083 return I->second;
2084}
2085
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002086/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002087/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002088/// ScalarEvolution's ability to compute a trip count, or if the loop
2089/// is deleted.
2090void ScalarEvolutionsImpl::forgetLoopBackedgeTakenCount(const Loop *L) {
2091 BackedgeTakenCounts.erase(L);
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002092}
2093
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002094/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2095/// of the specified loop will execute.
2096SCEVHandle ScalarEvolutionsImpl::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002097 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00002098 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002099 L->getExitBlocks(ExitBlocks);
2100 if (ExitBlocks.size() != 1) return UnknownValue;
2101
2102 // Okay, there is one exit block. Try to find the condition that causes the
2103 // loop to be exited.
2104 BasicBlock *ExitBlock = ExitBlocks[0];
2105
2106 BasicBlock *ExitingBlock = 0;
2107 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2108 PI != E; ++PI)
2109 if (L->contains(*PI)) {
2110 if (ExitingBlock == 0)
2111 ExitingBlock = *PI;
2112 else
2113 return UnknownValue; // More than one block exiting!
2114 }
2115 assert(ExitingBlock && "No exits from loop, something is broken!");
2116
2117 // Okay, we've computed the exiting block. See what condition causes us to
2118 // exit.
2119 //
2120 // FIXME: we should be able to handle switch instructions (with a single exit)
2121 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2122 if (ExitBr == 0) return UnknownValue;
2123 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2124
2125 // At this point, we know we have a conditional branch that determines whether
2126 // the loop is exited. However, we don't know if the branch is executed each
2127 // time through the loop. If not, then the execution count of the branch will
2128 // not be equal to the trip count of the loop.
2129 //
2130 // Currently we check for this by checking to see if the Exit branch goes to
2131 // the loop header. If so, we know it will always execute the same number of
2132 // times as the loop. We also handle the case where the exit block *is* the
2133 // loop header. This is common for un-rotated loops. More extensive analysis
2134 // could be done to handle more cases here.
2135 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2136 ExitBr->getSuccessor(1) != L->getHeader() &&
2137 ExitBr->getParent() != L->getHeader())
2138 return UnknownValue;
2139
2140 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2141
Nick Lewyckyb3d24332008-02-21 08:34:02 +00002142 // If it's not an integer comparison then compute it the hard way.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002143 // Note that ICmpInst deals with pointer comparisons too so we must check
2144 // the type of the operand.
2145 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002146 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002147 ExitBr->getSuccessor(0) == ExitBlock);
2148
2149 // If the condition was exit on true, convert the condition to exit on false
2150 ICmpInst::Predicate Cond;
2151 if (ExitBr->getSuccessor(1) == ExitBlock)
2152 Cond = ExitCond->getPredicate();
2153 else
2154 Cond = ExitCond->getInversePredicate();
2155
2156 // Handle common loops like: for (X = "string"; *X; ++X)
2157 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2158 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2159 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002160 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002161 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2162 }
2163
2164 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2165 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2166
2167 // Try to evaluate any dependencies out of the loop.
2168 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2169 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2170 Tmp = getSCEVAtScope(RHS, L);
2171 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2172
2173 // At this point, we would like to compute how many iterations of the
2174 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002175 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2176 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002177 std::swap(LHS, RHS);
2178 Cond = ICmpInst::getSwappedPredicate(Cond);
2179 }
2180
2181 // FIXME: think about handling pointer comparisons! i.e.:
2182 // while (P != P+100) ++P;
2183
2184 // If we have a comparison of a chrec against a constant, try to use value
2185 // ranges to answer this query.
2186 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2187 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2188 if (AddRec->getLoop() == L) {
2189 // Form the comparison range using the constant of the correct type so
2190 // that the ConstantRange class knows to do a signed or unsigned
2191 // comparison.
2192 ConstantInt *CompVal = RHSC->getValue();
2193 const Type *RealTy = ExitCond->getOperand(0)->getType();
2194 CompVal = dyn_cast<ConstantInt>(
2195 ConstantExpr::getBitCast(CompVal, RealTy));
2196 if (CompVal) {
2197 // Form the constant range.
2198 ConstantRange CompRange(
2199 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2200
Dan Gohman89f85052007-10-22 18:31:58 +00002201 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002202 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2203 }
2204 }
2205
2206 switch (Cond) {
2207 case ICmpInst::ICMP_NE: { // while (X != Y)
2208 // Convert to: while (X-Y != 0)
Dan Gohman89f85052007-10-22 18:31:58 +00002209 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002210 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2211 break;
2212 }
2213 case ICmpInst::ICMP_EQ: {
2214 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman89f85052007-10-22 18:31:58 +00002215 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002216 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2217 break;
2218 }
2219 case ICmpInst::ICMP_SLT: {
Nick Lewycky35b56022009-01-13 09:18:58 +00002220 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002221 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2222 break;
2223 }
2224 case ICmpInst::ICMP_SGT: {
Eli Friedman0dcd4ed2008-07-30 00:04:08 +00002225 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky35b56022009-01-13 09:18:58 +00002226 SE.getNotSCEV(RHS), L, true);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002227 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2228 break;
2229 }
2230 case ICmpInst::ICMP_ULT: {
Nick Lewycky35b56022009-01-13 09:18:58 +00002231 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002232 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2233 break;
2234 }
2235 case ICmpInst::ICMP_UGT: {
Dale Johannesend721b952008-04-20 16:58:57 +00002236 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky35b56022009-01-13 09:18:58 +00002237 SE.getNotSCEV(RHS), L, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002238 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2239 break;
2240 }
2241 default:
2242#if 0
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002243 cerr << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002244 if (ExitCond->getOperand(0)->getType()->isUnsigned())
2245 cerr << "[unsigned] ";
2246 cerr << *LHS << " "
2247 << Instruction::getOpcodeName(Instruction::ICmp)
2248 << " " << *RHS << "\n";
2249#endif
2250 break;
2251 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002252 return
2253 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2254 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002255}
2256
2257static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002258EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2259 ScalarEvolution &SE) {
2260 SCEVHandle InVal = SE.getConstant(C);
2261 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002262 assert(isa<SCEVConstant>(Val) &&
2263 "Evaluation of SCEV at constant didn't fold correctly?");
2264 return cast<SCEVConstant>(Val)->getValue();
2265}
2266
2267/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2268/// and a GEP expression (missing the pointer index) indexing into it, return
2269/// the addressed element of the initializer or null if the index expression is
2270/// invalid.
2271static Constant *
2272GetAddressedElementFromGlobal(GlobalVariable *GV,
2273 const std::vector<ConstantInt*> &Indices) {
2274 Constant *Init = GV->getInitializer();
2275 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2276 uint64_t Idx = Indices[i]->getZExtValue();
2277 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2278 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2279 Init = cast<Constant>(CS->getOperand(Idx));
2280 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2281 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2282 Init = cast<Constant>(CA->getOperand(Idx));
2283 } else if (isa<ConstantAggregateZero>(Init)) {
2284 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2285 assert(Idx < STy->getNumElements() && "Bad struct index!");
2286 Init = Constant::getNullValue(STy->getElementType(Idx));
2287 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2288 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2289 Init = Constant::getNullValue(ATy->getElementType());
2290 } else {
2291 assert(0 && "Unknown constant aggregate type!");
2292 }
2293 return 0;
2294 } else {
2295 return 0; // Unknown initializer type
2296 }
2297 }
2298 return Init;
2299}
2300
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002301/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2302/// 'icmp op load X, cst', try to see if we can compute the backedge
2303/// execution count.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002304SCEVHandle ScalarEvolutionsImpl::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002305ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2306 const Loop *L,
2307 ICmpInst::Predicate predicate) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002308 if (LI->isVolatile()) return UnknownValue;
2309
2310 // Check to see if the loaded pointer is a getelementptr of a global.
2311 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2312 if (!GEP) return UnknownValue;
2313
2314 // Make sure that it is really a constant global we are gepping, with an
2315 // initializer, and make sure the first IDX is really 0.
2316 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2317 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2318 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2319 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2320 return UnknownValue;
2321
2322 // Okay, we allow one non-constant index into the GEP instruction.
2323 Value *VarIdx = 0;
2324 std::vector<ConstantInt*> Indexes;
2325 unsigned VarIdxNum = 0;
2326 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2327 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2328 Indexes.push_back(CI);
2329 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2330 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2331 VarIdx = GEP->getOperand(i);
2332 VarIdxNum = i-2;
2333 Indexes.push_back(0);
2334 }
2335
2336 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2337 // Check to see if X is a loop variant variable value now.
2338 SCEVHandle Idx = getSCEV(VarIdx);
2339 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2340 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2341
2342 // We can only recognize very limited forms of loop index expressions, in
2343 // particular, only affine AddRec's like {C1,+,C2}.
2344 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2345 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2346 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2347 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2348 return UnknownValue;
2349
2350 unsigned MaxSteps = MaxBruteForceIterations;
2351 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2352 ConstantInt *ItCst =
2353 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohman89f85052007-10-22 18:31:58 +00002354 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002355
2356 // Form the GEP offset.
2357 Indexes[VarIdxNum] = Val;
2358
2359 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2360 if (Result == 0) break; // Cannot compute!
2361
2362 // Evaluate the condition for this iteration.
2363 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2364 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2365 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2366#if 0
2367 cerr << "\n***\n*** Computed loop count " << *ItCst
2368 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2369 << "***\n";
2370#endif
2371 ++NumArrayLenItCounts;
Dan Gohman89f85052007-10-22 18:31:58 +00002372 return SE.getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002373 }
2374 }
2375 return UnknownValue;
2376}
2377
2378
2379/// CanConstantFold - Return true if we can constant fold an instruction of the
2380/// specified type, assuming that all operands were constants.
2381static bool CanConstantFold(const Instruction *I) {
2382 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2383 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2384 return true;
2385
2386 if (const CallInst *CI = dyn_cast<CallInst>(I))
2387 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002388 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002389 return false;
2390}
2391
2392/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2393/// in the loop that V is derived from. We allow arbitrary operations along the
2394/// way, but the operands of an operation must either be constants or a value
2395/// derived from a constant PHI. If this expression does not fit with these
2396/// constraints, return null.
2397static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2398 // If this is not an instruction, or if this is an instruction outside of the
2399 // loop, it can't be derived from a loop PHI.
2400 Instruction *I = dyn_cast<Instruction>(V);
2401 if (I == 0 || !L->contains(I->getParent())) return 0;
2402
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002403 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002404 if (L->getHeader() == I->getParent())
2405 return PN;
2406 else
2407 // We don't currently keep track of the control flow needed to evaluate
2408 // PHIs, so we cannot handle PHIs inside of loops.
2409 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002410 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002411
2412 // If we won't be able to constant fold this expression even if the operands
2413 // are constants, return early.
2414 if (!CanConstantFold(I)) return 0;
2415
2416 // Otherwise, we can evaluate this instruction if all of its operands are
2417 // constant or derived from a PHI node themselves.
2418 PHINode *PHI = 0;
2419 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2420 if (!(isa<Constant>(I->getOperand(Op)) ||
2421 isa<GlobalValue>(I->getOperand(Op)))) {
2422 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2423 if (P == 0) return 0; // Not evolving from PHI
2424 if (PHI == 0)
2425 PHI = P;
2426 else if (PHI != P)
2427 return 0; // Evolving from multiple different PHIs.
2428 }
2429
2430 // This is a expression evolving from a constant PHI!
2431 return PHI;
2432}
2433
2434/// EvaluateExpression - Given an expression that passes the
2435/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2436/// in the loop has the value PHIVal. If we can't fold this expression for some
2437/// reason, return null.
2438static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2439 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002440 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002441 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002442 Instruction *I = cast<Instruction>(V);
2443
2444 std::vector<Constant*> Operands;
2445 Operands.resize(I->getNumOperands());
2446
2447 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2448 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2449 if (Operands[i] == 0) return 0;
2450 }
2451
Chris Lattnerd6e56912007-12-10 22:53:04 +00002452 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2453 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2454 &Operands[0], Operands.size());
2455 else
2456 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2457 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002458}
2459
2460/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2461/// in the header of its containing loop, we know the loop executes a
2462/// constant number of times, and the PHI node is just a recurrence
2463/// involving constants, fold it.
2464Constant *ScalarEvolutionsImpl::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002465getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002466 std::map<PHINode*, Constant*>::iterator I =
2467 ConstantEvolutionLoopExitValue.find(PN);
2468 if (I != ConstantEvolutionLoopExitValue.end())
2469 return I->second;
2470
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002471 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002472 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2473
2474 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2475
2476 // Since the loop is canonicalized, the PHI node must have two entries. One
2477 // entry must be a constant (coming in from outside of the loop), and the
2478 // second must be derived from the same PHI.
2479 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2480 Constant *StartCST =
2481 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2482 if (StartCST == 0)
2483 return RetVal = 0; // Must be a constant.
2484
2485 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2486 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2487 if (PN2 != PN)
2488 return RetVal = 0; // Not derived from same PHI.
2489
2490 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002491 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002492 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2493
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002494 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002495 unsigned IterationNum = 0;
2496 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2497 if (IterationNum == NumIterations)
2498 return RetVal = PHIVal; // Got exit value!
2499
2500 // Compute the value of the PHI node for the next iteration.
2501 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2502 if (NextPHI == PHIVal)
2503 return RetVal = NextPHI; // Stopped evolving!
2504 if (NextPHI == 0)
2505 return 0; // Couldn't evaluate!
2506 PHIVal = NextPHI;
2507 }
2508}
2509
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002510/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002511/// constant number of times (the condition evolves only from constants),
2512/// try to evaluate a few iterations of the loop until we get the exit
2513/// condition gets a value of ExitWhen (true or false). If we cannot
2514/// evaluate the trip count of the loop, return UnknownValue.
2515SCEVHandle ScalarEvolutionsImpl::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002516ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002517 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2518 if (PN == 0) return UnknownValue;
2519
2520 // Since the loop is canonicalized, the PHI node must have two entries. One
2521 // entry must be a constant (coming in from outside of the loop), and the
2522 // second must be derived from the same PHI.
2523 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2524 Constant *StartCST =
2525 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2526 if (StartCST == 0) return UnknownValue; // Must be a constant.
2527
2528 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2529 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2530 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2531
2532 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2533 // the loop symbolically to determine when the condition gets a value of
2534 // "ExitWhen".
2535 unsigned IterationNum = 0;
2536 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2537 for (Constant *PHIVal = StartCST;
2538 IterationNum != MaxIterations; ++IterationNum) {
2539 ConstantInt *CondVal =
2540 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2541
2542 // Couldn't symbolically evaluate.
2543 if (!CondVal) return UnknownValue;
2544
2545 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2546 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2547 ++NumBruteForceTripCountsComputed;
Dan Gohman89f85052007-10-22 18:31:58 +00002548 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002549 }
2550
2551 // Compute the value of the PHI node for the next iteration.
2552 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2553 if (NextPHI == 0 || NextPHI == PHIVal)
2554 return UnknownValue; // Couldn't evaluate or not making progress...
2555 PHIVal = NextPHI;
2556 }
2557
2558 // Too many iterations were needed to evaluate.
2559 return UnknownValue;
2560}
2561
2562/// getSCEVAtScope - Compute the value of the specified expression within the
2563/// indicated loop (which may be null to indicate in no loop). If the
2564/// expression cannot be evaluated, return UnknownValue.
2565SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2566 // FIXME: this should be turned into a virtual method on SCEV!
2567
2568 if (isa<SCEVConstant>(V)) return V;
2569
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002570 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002571 // exit value from the loop without using SCEVs.
2572 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2573 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2574 const Loop *LI = this->LI[I->getParent()];
2575 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2576 if (PHINode *PN = dyn_cast<PHINode>(I))
2577 if (PN->getParent() == LI->getHeader()) {
2578 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002579 // to see if the loop that contains it has a known backedge-taken
2580 // count. If so, we may be able to force computation of the exit
2581 // value.
2582 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
2583 if (SCEVConstant *BTCC =
2584 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002585 // Okay, we know how many times the containing loop executes. If
2586 // this is a constant evolving PHI node, get the final value at
2587 // the specified iteration number.
2588 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002589 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002590 LI);
Dan Gohman89f85052007-10-22 18:31:58 +00002591 if (RV) return SE.getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002592 }
2593 }
2594
2595 // Okay, this is an expression that we cannot symbolically evaluate
2596 // into a SCEV. Check to see if it's possible to symbolically evaluate
2597 // the arguments into constants, and if so, try to constant propagate the
2598 // result. This is particularly useful for computing loop exit values.
2599 if (CanConstantFold(I)) {
2600 std::vector<Constant*> Operands;
2601 Operands.reserve(I->getNumOperands());
2602 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2603 Value *Op = I->getOperand(i);
2604 if (Constant *C = dyn_cast<Constant>(Op)) {
2605 Operands.push_back(C);
2606 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002607 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00002608 // non-integer and non-pointer, don't even try to analyze them
2609 // with scev techniques.
2610 if (!isa<IntegerType>(Op->getType()) &&
2611 !isa<PointerType>(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00002612 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002613
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002614 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2615 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2616 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2617 Op->getType(),
2618 false));
2619 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2620 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2621 Operands.push_back(ConstantExpr::getIntegerCast(C,
2622 Op->getType(),
2623 false));
2624 else
2625 return V;
2626 } else {
2627 return V;
2628 }
2629 }
2630 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002631
2632 Constant *C;
2633 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2634 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2635 &Operands[0], Operands.size());
2636 else
2637 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2638 &Operands[0], Operands.size());
Dan Gohman89f85052007-10-22 18:31:58 +00002639 return SE.getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002640 }
2641 }
2642
2643 // This is some other type of SCEVUnknown, just return it.
2644 return V;
2645 }
2646
2647 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2648 // Avoid performing the look-up in the common case where the specified
2649 // expression has no loop-variant portions.
2650 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2651 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2652 if (OpAtScope != Comm->getOperand(i)) {
2653 if (OpAtScope == UnknownValue) return UnknownValue;
2654 // Okay, at least one of these operands is loop variant but might be
2655 // foldable. Build a new instance of the folded commutative expression.
2656 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2657 NewOps.push_back(OpAtScope);
2658
2659 for (++i; i != e; ++i) {
2660 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2661 if (OpAtScope == UnknownValue) return UnknownValue;
2662 NewOps.push_back(OpAtScope);
2663 }
2664 if (isa<SCEVAddExpr>(Comm))
Dan Gohman89f85052007-10-22 18:31:58 +00002665 return SE.getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002666 if (isa<SCEVMulExpr>(Comm))
2667 return SE.getMulExpr(NewOps);
2668 if (isa<SCEVSMaxExpr>(Comm))
2669 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002670 if (isa<SCEVUMaxExpr>(Comm))
2671 return SE.getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002672 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002673 }
2674 }
2675 // If we got here, all operands are loop invariant.
2676 return Comm;
2677 }
2678
Nick Lewycky35b56022009-01-13 09:18:58 +00002679 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2680 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002681 if (LHS == UnknownValue) return LHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002682 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002683 if (RHS == UnknownValue) return RHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002684 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2685 return Div; // must be loop invariant
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00002686 return SE.getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002687 }
2688
2689 // If this is a loop recurrence for a loop that does not contain L, then we
2690 // are dealing with the final value computed by the loop.
2691 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2692 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2693 // To evaluate this recurrence, we need to know how many times the AddRec
2694 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002695 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2696 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002697
Eli Friedman7489ec92008-08-04 23:49:06 +00002698 // Then, evaluate the AddRec.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002699 return AddRec->evaluateAtIteration(BackedgeTakenCount, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002700 }
2701 return UnknownValue;
2702 }
2703
2704 //assert(0 && "Unknown SCEV type!");
2705 return UnknownValue;
2706}
2707
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002708/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2709/// following equation:
2710///
2711/// A * X = B (mod N)
2712///
2713/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2714/// A and B isn't important.
2715///
2716/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2717static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2718 ScalarEvolution &SE) {
2719 uint32_t BW = A.getBitWidth();
2720 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2721 assert(A != 0 && "A must be non-zero.");
2722
2723 // 1. D = gcd(A, N)
2724 //
2725 // The gcd of A and N may have only one prime factor: 2. The number of
2726 // trailing zeros in A is its multiplicity
2727 uint32_t Mult2 = A.countTrailingZeros();
2728 // D = 2^Mult2
2729
2730 // 2. Check if B is divisible by D.
2731 //
2732 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2733 // is not less than multiplicity of this prime factor for D.
2734 if (B.countTrailingZeros() < Mult2)
2735 return new SCEVCouldNotCompute();
2736
2737 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2738 // modulo (N / D).
2739 //
2740 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2741 // bit width during computations.
2742 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2743 APInt Mod(BW + 1, 0);
2744 Mod.set(BW - Mult2); // Mod = N / D
2745 APInt I = AD.multiplicativeInverse(Mod);
2746
2747 // 4. Compute the minimum unsigned root of the equation:
2748 // I * (B / D) mod (N / D)
2749 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2750
2751 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2752 // bits.
2753 return SE.getConstant(Result.trunc(BW));
2754}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002755
2756/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2757/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2758/// might be the same) or two SCEVCouldNotCompute objects.
2759///
2760static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00002761SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002762 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2763 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2764 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2765 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2766
2767 // We currently can only solve this if the coefficients are constants.
2768 if (!LC || !MC || !NC) {
2769 SCEV *CNC = new SCEVCouldNotCompute();
2770 return std::make_pair(CNC, CNC);
2771 }
2772
2773 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2774 const APInt &L = LC->getValue()->getValue();
2775 const APInt &M = MC->getValue()->getValue();
2776 const APInt &N = NC->getValue()->getValue();
2777 APInt Two(BitWidth, 2);
2778 APInt Four(BitWidth, 4);
2779
2780 {
2781 using namespace APIntOps;
2782 const APInt& C = L;
2783 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2784 // The B coefficient is M-N/2
2785 APInt B(M);
2786 B -= sdiv(N,Two);
2787
2788 // The A coefficient is N/2
2789 APInt A(N.sdiv(Two));
2790
2791 // Compute the B^2-4ac term.
2792 APInt SqrtTerm(B);
2793 SqrtTerm *= B;
2794 SqrtTerm -= Four * (A * C);
2795
2796 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2797 // integer value or else APInt::sqrt() will assert.
2798 APInt SqrtVal(SqrtTerm.sqrt());
2799
2800 // Compute the two solutions for the quadratic formula.
2801 // The divisions must be performed as signed divisions.
2802 APInt NegB(-B);
2803 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00002804 if (TwoA.isMinValue()) {
2805 SCEV *CNC = new SCEVCouldNotCompute();
2806 return std::make_pair(CNC, CNC);
2807 }
2808
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002809 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2810 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2811
Dan Gohman89f85052007-10-22 18:31:58 +00002812 return std::make_pair(SE.getConstant(Solution1),
2813 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002814 } // end APIntOps namespace
2815}
2816
2817/// HowFarToZero - Return the number of times a backedge comparing the specified
2818/// value to zero will execute. If not computable, return UnknownValue
2819SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2820 // If the value is a constant
2821 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2822 // If the value is already zero, the branch will execute zero times.
2823 if (C->getValue()->isZero()) return C;
2824 return UnknownValue; // Otherwise it will loop infinitely.
2825 }
2826
2827 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2828 if (!AddRec || AddRec->getLoop() != L)
2829 return UnknownValue;
2830
2831 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002832 // If this is an affine expression, the execution count of this branch is
2833 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002834 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002835 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002836 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002837 // equivalent to:
2838 //
2839 // Step*N = -Start (mod 2^BW)
2840 //
2841 // where BW is the common bit width of Start and Step.
2842
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002843 // Get the initial value for the loop.
2844 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2845 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002846
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002847 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002848
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002849 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002850 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002851
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002852 // First, handle unitary steps.
2853 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2854 return SE.getNegativeSCEV(Start); // N = -Start (as unsigned)
2855 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2856 return Start; // N = Start (as unsigned)
2857
2858 // Then, try to solve the above equation provided that Start is constant.
2859 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2860 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2861 -StartC->getValue()->getValue(),SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002862 }
2863 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2864 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2865 // the quadratic equation to solve it.
Dan Gohman89f85052007-10-22 18:31:58 +00002866 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002867 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2868 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2869 if (R1) {
2870#if 0
2871 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2872 << " sol#2: " << *R2 << "\n";
2873#endif
2874 // Pick the smallest positive root value.
2875 if (ConstantInt *CB =
2876 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2877 R1->getValue(), R2->getValue()))) {
2878 if (CB->getZExtValue() == false)
2879 std::swap(R1, R2); // R1 is the minimum root now.
2880
2881 // We can only use this value if the chrec ends up with an exact zero
2882 // value at this index. When solving for "X*X != 5", for example, we
2883 // should not accept a root of 2.
Dan Gohman89f85052007-10-22 18:31:58 +00002884 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Dan Gohman7b560c42008-06-18 16:23:07 +00002885 if (Val->isZero())
2886 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002887 }
2888 }
2889 }
2890
2891 return UnknownValue;
2892}
2893
2894/// HowFarToNonZero - Return the number of times a backedge checking the
2895/// specified value for nonzero will execute. If not computable, return
2896/// UnknownValue
2897SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2898 // Loops that look like: while (X == 0) are very strange indeed. We don't
2899 // handle them yet except for the trivial case. This could be expanded in the
2900 // future as needed.
2901
2902 // If the value is a constant, check to see if it is known to be non-zero
2903 // already. If so, the backedge will execute zero times.
2904 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00002905 if (!C->getValue()->isNullValue())
2906 return SE.getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002907 return UnknownValue; // Otherwise it will loop infinitely.
2908 }
2909
2910 // We could implement others, but I really doubt anyone writes loops like
2911 // this, and if they did, they would already be constant folded.
2912 return UnknownValue;
2913}
2914
Dan Gohman1cddf972008-09-15 22:18:04 +00002915/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2916/// (which may not be an immediate predecessor) which has exactly one
2917/// successor from which BB is reachable, or null if no such block is
2918/// found.
2919///
2920BasicBlock *
2921ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2922 // If the block has a unique predecessor, the predecessor must have
2923 // no other successors from which BB is reachable.
2924 if (BasicBlock *Pred = BB->getSinglePredecessor())
2925 return Pred;
2926
2927 // A loop's header is defined to be a block that dominates the loop.
2928 // If the loop has a preheader, it must be a block that has exactly
2929 // one successor that can reach BB. This is slightly more strict
2930 // than necessary, but works if critical edges are split.
2931 if (Loop *L = LI.getLoopFor(BB))
2932 return L->getLoopPreheader();
2933
2934 return 0;
2935}
2936
Dan Gohmancacd2012009-02-12 22:19:27 +00002937/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002938/// a conditional between LHS and RHS.
Dan Gohmancacd2012009-02-12 22:19:27 +00002939bool ScalarEvolutionsImpl::isLoopGuardedByCond(const Loop *L,
2940 ICmpInst::Predicate Pred,
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002941 SCEV *LHS, SCEV *RHS) {
2942 BasicBlock *Preheader = L->getLoopPreheader();
2943 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002944
Dan Gohmanab678fb2008-08-12 20:17:31 +00002945 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohman1cddf972008-09-15 22:18:04 +00002946 // there are predecessors that can be found that have unique successors
2947 // leading to the original header.
2948 for (; Preheader;
2949 PreheaderDest = Preheader,
2950 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00002951
2952 BranchInst *LoopEntryPredicate =
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002953 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00002954 if (!LoopEntryPredicate ||
2955 LoopEntryPredicate->isUnconditional())
2956 continue;
2957
2958 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2959 if (!ICI) continue;
2960
2961 // Now that we found a conditional branch that dominates the loop, check to
2962 // see if it is the comparison we are looking for.
2963 Value *PreCondLHS = ICI->getOperand(0);
2964 Value *PreCondRHS = ICI->getOperand(1);
2965 ICmpInst::Predicate Cond;
2966 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2967 Cond = ICI->getPredicate();
2968 else
2969 Cond = ICI->getInversePredicate();
2970
Dan Gohmancacd2012009-02-12 22:19:27 +00002971 if (Cond == Pred)
2972 ; // An exact match.
2973 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
2974 ; // The actual condition is beyond sufficient.
2975 else
2976 // Check a few special cases.
2977 switch (Cond) {
2978 case ICmpInst::ICMP_UGT:
2979 if (Pred == ICmpInst::ICMP_ULT) {
2980 std::swap(PreCondLHS, PreCondRHS);
2981 Cond = ICmpInst::ICMP_ULT;
2982 break;
2983 }
2984 continue;
2985 case ICmpInst::ICMP_SGT:
2986 if (Pred == ICmpInst::ICMP_SLT) {
2987 std::swap(PreCondLHS, PreCondRHS);
2988 Cond = ICmpInst::ICMP_SLT;
2989 break;
2990 }
2991 continue;
2992 case ICmpInst::ICMP_NE:
2993 // Expressions like (x >u 0) are often canonicalized to (x != 0),
2994 // so check for this case by checking if the NE is comparing against
2995 // a minimum or maximum constant.
2996 if (!ICmpInst::isTrueWhenEqual(Pred))
2997 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
2998 const APInt &A = CI->getValue();
2999 switch (Pred) {
3000 case ICmpInst::ICMP_SLT:
3001 if (A.isMaxSignedValue()) break;
3002 continue;
3003 case ICmpInst::ICMP_SGT:
3004 if (A.isMinSignedValue()) break;
3005 continue;
3006 case ICmpInst::ICMP_ULT:
3007 if (A.isMaxValue()) break;
3008 continue;
3009 case ICmpInst::ICMP_UGT:
3010 if (A.isMinValue()) break;
3011 continue;
3012 default:
3013 continue;
3014 }
3015 Cond = ICmpInst::ICMP_NE;
3016 // NE is symmetric but the original comparison may not be. Swap
3017 // the operands if necessary so that they match below.
3018 if (isa<SCEVConstant>(LHS))
3019 std::swap(PreCondLHS, PreCondRHS);
3020 break;
3021 }
3022 continue;
3023 default:
3024 // We weren't able to reconcile the condition.
3025 continue;
3026 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003027
3028 if (!PreCondLHS->getType()->isInteger()) continue;
3029
3030 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3031 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3032 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
3033 (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
3034 RHS == SE.getNotSCEV(PreCondLHSSCEV)))
3035 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003036 }
3037
Dan Gohmanab678fb2008-08-12 20:17:31 +00003038 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003039}
3040
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003041/// HowManyLessThans - Return the number of times a backedge containing the
3042/// specified less-than comparison will execute. If not computable, return
3043/// UnknownValue.
3044SCEVHandle ScalarEvolutionsImpl::
Nick Lewycky35b56022009-01-13 09:18:58 +00003045HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003046 // Only handle: "ADDREC < LoopInvariant".
3047 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3048
3049 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
3050 if (!AddRec || AddRec->getLoop() != L)
3051 return UnknownValue;
3052
3053 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003054 // FORNOW: We only support unit strides.
3055 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
3056 if (AddRec->getOperand(1) != One)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003057 return UnknownValue;
3058
Nick Lewycky35b56022009-01-13 09:18:58 +00003059 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
3060 // m. So, we count the number of iterations in which {n,+,1} < m is true.
3061 // Note that we cannot simply return max(m-n,0) because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00003062 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003063
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003064 // First, we get the value of the LHS in the first iteration: n
3065 SCEVHandle Start = AddRec->getOperand(0);
3066
Dan Gohmancacd2012009-02-12 22:19:27 +00003067 if (isLoopGuardedByCond(L,
3068 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Nick Lewycky35b56022009-01-13 09:18:58 +00003069 SE.getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
3070 // Since we know that the condition is true in order to enter the loop,
3071 // we know that it will run exactly m-n times.
3072 return SE.getMinusSCEV(RHS, Start);
3073 } else {
3074 // Then, we get the value of the LHS in the first iteration in which the
3075 // above condition doesn't hold. This equals to max(m,n).
3076 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
3077 : SE.getUMaxExpr(RHS, Start);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003078
Nick Lewycky35b56022009-01-13 09:18:58 +00003079 // Finally, we subtract these two values to get the number of times the
3080 // backedge is executed: max(m,n)-n.
3081 return SE.getMinusSCEV(End, Start);
Nick Lewycky64d1fff2008-12-16 08:30:01 +00003082 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003083 }
3084
3085 return UnknownValue;
3086}
3087
3088/// getNumIterationsInRange - Return the number of iterations of this loop that
3089/// produce values in the specified constant range. Another way of looking at
3090/// this is that it returns the first iteration number where the value is not in
3091/// the condition, thus computing the exit count. If the iteration count can't
3092/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00003093SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3094 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003095 if (Range.isFullSet()) // Infinite loop.
3096 return new SCEVCouldNotCompute();
3097
3098 // If the start is a non-zero constant, shift the range to simplify things.
3099 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
3100 if (!SC->getValue()->isZero()) {
3101 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003102 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3103 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003104 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
3105 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003106 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003107 // This is strange and shouldn't happen.
3108 return new SCEVCouldNotCompute();
3109 }
3110
3111 // The only time we can solve this is when we have all constant indices.
3112 // Otherwise, we cannot determine the overflow conditions.
3113 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3114 if (!isa<SCEVConstant>(getOperand(i)))
3115 return new SCEVCouldNotCompute();
3116
3117
3118 // Okay at this point we know that all elements of the chrec are constants and
3119 // that the start element is zero.
3120
3121 // First check to see if the range contains zero. If not, the first
3122 // iteration exits.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003123 unsigned BitWidth = SE.getTargetData().getTypeSizeInBits(getType());
3124 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003125 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003126
3127 if (isAffine()) {
3128 // If this is an affine expression then we have this situation:
3129 // Solve {0,+,A} in Range === Ax in Range
3130
3131 // We know that zero is in the range. If A is positive then we know that
3132 // the upper value of the range must be the first possible exit value.
3133 // If A is negative then the lower of the range is the last possible loop
3134 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003135 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003136 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3137 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3138
3139 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003140 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003141 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3142
3143 // Evaluate at the exit value. If we really did fall out of the valid
3144 // range, then we computed our trip count, otherwise wrap around or other
3145 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003146 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003147 if (Range.contains(Val->getValue()))
3148 return new SCEVCouldNotCompute(); // Something strange happened
3149
3150 // Ensure that the previous value is in the range. This is a sanity check.
3151 assert(Range.contains(
3152 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003153 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003154 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003155 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003156 } else if (isQuadratic()) {
3157 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3158 // quadratic equation to solve it. To do this, we must frame our problem in
3159 // terms of figuring out when zero is crossed, instead of when
3160 // Range.getUpper() is crossed.
3161 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003162 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3163 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003164
3165 // Next, solve the constructed addrec
3166 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003167 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003168 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3169 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3170 if (R1) {
3171 // Pick the smallest positive root value.
3172 if (ConstantInt *CB =
3173 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3174 R1->getValue(), R2->getValue()))) {
3175 if (CB->getZExtValue() == false)
3176 std::swap(R1, R2); // R1 is the minimum root now.
3177
3178 // Make sure the root is not off by one. The returned iteration should
3179 // not be in the range, but the previous one should be. When solving
3180 // for "X*X < 5", for example, we should not return a root of 2.
3181 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003182 R1->getValue(),
3183 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003184 if (Range.contains(R1Val->getValue())) {
3185 // The next iteration must be out of the range...
3186 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3187
Dan Gohman89f85052007-10-22 18:31:58 +00003188 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003189 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003190 return SE.getConstant(NextVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003191 return new SCEVCouldNotCompute(); // Something strange happened
3192 }
3193
3194 // If R1 was not in the range, then it is a good return value. Make
3195 // sure that R1-1 WAS in the range though, just in case.
3196 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003197 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003198 if (Range.contains(R1Val->getValue()))
3199 return R1;
3200 return new SCEVCouldNotCompute(); // Something strange happened
3201 }
3202 }
3203 }
3204
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003205 return new SCEVCouldNotCompute();
3206}
3207
3208
3209
3210//===----------------------------------------------------------------------===//
3211// ScalarEvolution Class Implementation
3212//===----------------------------------------------------------------------===//
3213
3214bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00003215 Impl = new ScalarEvolutionsImpl(*this, F,
3216 getAnalysis<LoopInfo>(),
3217 getAnalysis<TargetData>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003218 return false;
3219}
3220
3221void ScalarEvolution::releaseMemory() {
3222 delete (ScalarEvolutionsImpl*)Impl;
3223 Impl = 0;
3224}
3225
3226void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3227 AU.setPreservesAll();
3228 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003229 AU.addRequiredTransitive<TargetData>();
3230}
3231
3232const TargetData &ScalarEvolution::getTargetData() const {
3233 return ((ScalarEvolutionsImpl*)Impl)->getTargetData();
3234}
3235
3236SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
3237 return ((ScalarEvolutionsImpl*)Impl)->getIntegerSCEV(Val, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003238}
3239
3240SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
3241 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
3242}
3243
3244/// hasSCEV - Return true if the SCEV for this value has already been
3245/// computed.
3246bool ScalarEvolution::hasSCEV(Value *V) const {
3247 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
3248}
3249
3250
3251/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
3252/// the specified value.
3253void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
3254 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
3255}
3256
Dan Gohman01c2ee72009-04-16 03:18:22 +00003257/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
3258///
3259SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
3260 return ((ScalarEvolutionsImpl*)Impl)->getNegativeSCEV(V);
3261}
3262
3263/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
3264///
3265SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
3266 return ((ScalarEvolutionsImpl*)Impl)->getNotSCEV(V);
3267}
3268
3269/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
3270///
3271SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
3272 const SCEVHandle &RHS) {
3273 return ((ScalarEvolutionsImpl*)Impl)->getMinusSCEV(LHS, RHS);
3274}
3275
3276/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
3277/// of the input value to the specified type. If the type must be
3278/// extended, it is zero extended.
3279SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
3280 const Type *Ty) {
3281 return ((ScalarEvolutionsImpl*)Impl)->getTruncateOrZeroExtend(V, Ty);
3282}
3283
3284/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
3285/// of the input value to the specified type. If the type must be
3286/// extended, it is sign extended.
3287SCEVHandle ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
3288 const Type *Ty) {
3289 return ((ScalarEvolutionsImpl*)Impl)->getTruncateOrSignExtend(V, Ty);
3290}
3291
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003292
Dan Gohmancacd2012009-02-12 22:19:27 +00003293bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
3294 ICmpInst::Predicate Pred,
3295 SCEV *LHS, SCEV *RHS) {
3296 return ((ScalarEvolutionsImpl*)Impl)->isLoopGuardedByCond(L, Pred,
3297 LHS, RHS);
3298}
3299
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003300SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) const {
3301 return ((ScalarEvolutionsImpl*)Impl)->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003302}
3303
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003304bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) const {
3305 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003306}
3307
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003308void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
3309 return ((ScalarEvolutionsImpl*)Impl)->forgetLoopBackedgeTakenCount(L);
Dan Gohmanf3a060a2009-02-17 20:49:49 +00003310}
3311
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003312SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3313 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3314}
3315
3316void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3317 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
3318}
3319
3320static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
3321 const Loop *L) {
3322 // Print all inner loops first
3323 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3324 PrintLoopInfo(OS, SE, *I);
3325
Nick Lewyckye5da1912008-01-02 02:49:20 +00003326 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003327
Devang Patel02451fa2007-08-21 00:31:24 +00003328 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003329 L->getExitBlocks(ExitBlocks);
3330 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003331 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003332
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003333 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3334 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003335 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003336 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003337 }
3338
Nick Lewyckye5da1912008-01-02 02:49:20 +00003339 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003340}
3341
3342void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
3343 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3344 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3345
3346 OS << "Classifying expressions for: " << F.getName() << "\n";
3347 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3348 if (I->getType()->isInteger()) {
3349 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003350 OS << " --> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003351 SCEVHandle SV = getSCEV(&*I);
3352 SV->print(OS);
3353 OS << "\t\t";
3354
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003355 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
3356 OS << "Exits: ";
3357 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
3358 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3359 OS << "<<Unknown>>";
3360 } else {
3361 OS << *ExitValue;
3362 }
3363 }
3364
3365
3366 OS << "\n";
3367 }
3368
3369 OS << "Determining loop execution counts for: " << F.getName() << "\n";
3370 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3371 PrintLoopInfo(OS, this, *I);
3372}