blob: cac3b507ba103b9ad7f3386b9fef794732371363 [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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//
Chris Lattner53e677a2004-04-02 20:23:17 +000036// 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
Chris Lattner0a7f98c2004-04-15 15:07:24 +000062#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000063#include "llvm/Constants.h"
64#include "llvm/DerivedTypes.h"
65#include "llvm/Instructions.h"
66#include "llvm/Type.h"
67#include "llvm/Value.h"
68#include "llvm/Analysis/LoopInfo.h"
69#include "llvm/Assembly/Writer.h"
70#include "llvm/Transforms/Scalar.h"
Chris Lattner7980fb92004-04-17 18:36:24 +000071#include "llvm/Transforms/Utils/Local.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000072#include "llvm/Support/CFG.h"
73#include "llvm/Support/ConstantRange.h"
74#include "llvm/Support/InstIterator.h"
Chris Lattner7980fb92004-04-17 18:36:24 +000075#include "Support/CommandLine.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000076#include "Support/Statistic.h"
Brian Gaekec5985172004-04-16 15:57:32 +000077#include <cmath>
Chris Lattner53e677a2004-04-02 20:23:17 +000078using namespace llvm;
79
80namespace {
81 RegisterAnalysis<ScalarEvolution>
Chris Lattner45a1cf82004-04-19 03:42:32 +000082 R("scalar-evolution", "Scalar Evolution Analysis");
Chris Lattner53e677a2004-04-02 20:23:17 +000083
84 Statistic<>
85 NumBruteForceEvaluations("scalar-evolution",
86 "Number of brute force evaluations needed to calculate high-order polynomial exit values");
87 Statistic<>
88 NumTripCountsComputed("scalar-evolution",
89 "Number of loops with predictable loop counts");
90 Statistic<>
91 NumTripCountsNotComputed("scalar-evolution",
92 "Number of loops without predictable loop counts");
Chris Lattner7980fb92004-04-17 18:36:24 +000093 Statistic<>
94 NumBruteForceTripCountsComputed("scalar-evolution",
95 "Number of loops with trip counts computed by force");
96
97 cl::opt<unsigned>
98 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
99 cl::desc("Maximum number of iterations SCEV will symbolically execute a constant derived loop"),
100 cl::init(100));
Chris Lattner53e677a2004-04-02 20:23:17 +0000101}
102
103//===----------------------------------------------------------------------===//
104// SCEV class definitions
105//===----------------------------------------------------------------------===//
106
107//===----------------------------------------------------------------------===//
108// Implementation of the SCEV class.
109//
Chris Lattner53e677a2004-04-02 20:23:17 +0000110SCEV::~SCEV() {}
111void SCEV::dump() const {
112 print(std::cerr);
113}
114
115/// getValueRange - Return the tightest constant bounds that this value is
116/// known to have. This method is only valid on integer SCEV objects.
117ConstantRange SCEV::getValueRange() const {
118 const Type *Ty = getType();
119 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
120 Ty = Ty->getUnsignedVersion();
121 // Default to a full range if no better information is available.
122 return ConstantRange(getType());
123}
124
125
126SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
127
128bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
129 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000130 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000131}
132
133const Type *SCEVCouldNotCompute::getType() const {
134 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000135 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000136}
137
138bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
139 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
140 return false;
141}
142
Chris Lattner53e677a2004-04-02 20:23:17 +0000143void SCEVCouldNotCompute::print(std::ostream &OS) const {
144 OS << "***COULDNOTCOMPUTE***";
145}
146
147bool SCEVCouldNotCompute::classof(const SCEV *S) {
148 return S->getSCEVType() == scCouldNotCompute;
149}
150
151
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000152// SCEVConstants - Only allow the creation of one SCEVConstant for any
153// particular value. Don't use a SCEVHandle here, or else the object will
154// never be deleted!
155static std::map<ConstantInt*, SCEVConstant*> SCEVConstants;
156
Chris Lattner53e677a2004-04-02 20:23:17 +0000157
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000158SCEVConstant::~SCEVConstant() {
159 SCEVConstants.erase(V);
160}
Chris Lattner53e677a2004-04-02 20:23:17 +0000161
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000162SCEVHandle SCEVConstant::get(ConstantInt *V) {
163 // Make sure that SCEVConstant instances are all unsigned.
164 if (V->getType()->isSigned()) {
165 const Type *NewTy = V->getType()->getUnsignedVersion();
166 V = cast<ConstantUInt>(ConstantExpr::getCast(V, NewTy));
167 }
168
169 SCEVConstant *&R = SCEVConstants[V];
170 if (R == 0) R = new SCEVConstant(V);
171 return R;
172}
Chris Lattner53e677a2004-04-02 20:23:17 +0000173
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000174ConstantRange SCEVConstant::getValueRange() const {
175 return ConstantRange(V);
176}
Chris Lattner53e677a2004-04-02 20:23:17 +0000177
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000178const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000179
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000180void SCEVConstant::print(std::ostream &OS) const {
181 WriteAsOperand(OS, V, false);
182}
Chris Lattner53e677a2004-04-02 20:23:17 +0000183
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000184// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
185// particular input. Don't use a SCEVHandle here, or else the object will
186// never be deleted!
187static std::map<std::pair<SCEV*, const Type*>, SCEVTruncateExpr*> SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000188
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000189SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
190 : SCEV(scTruncate), Op(op), Ty(ty) {
191 assert(Op->getType()->isInteger() && Ty->isInteger() &&
192 Ty->isUnsigned() &&
193 "Cannot truncate non-integer value!");
194 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
195 "This is not a truncating conversion!");
196}
Chris Lattner53e677a2004-04-02 20:23:17 +0000197
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000198SCEVTruncateExpr::~SCEVTruncateExpr() {
199 SCEVTruncates.erase(std::make_pair(Op, Ty));
200}
Chris Lattner53e677a2004-04-02 20:23:17 +0000201
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000202ConstantRange SCEVTruncateExpr::getValueRange() const {
203 return getOperand()->getValueRange().truncate(getType());
204}
Chris Lattner53e677a2004-04-02 20:23:17 +0000205
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000206void SCEVTruncateExpr::print(std::ostream &OS) const {
207 OS << "(truncate " << *Op << " to " << *Ty << ")";
208}
209
210// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
211// particular input. Don't use a SCEVHandle here, or else the object will never
212// be deleted!
213static std::map<std::pair<SCEV*, const Type*>,
214 SCEVZeroExtendExpr*> SCEVZeroExtends;
215
216SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
217 : SCEV(scTruncate), Op(Op), Ty(ty) {
218 assert(Op->getType()->isInteger() && Ty->isInteger() &&
219 Ty->isUnsigned() &&
220 "Cannot zero extend non-integer value!");
221 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
222 "This is not an extending conversion!");
223}
224
225SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
226 SCEVZeroExtends.erase(std::make_pair(Op, Ty));
227}
228
229ConstantRange SCEVZeroExtendExpr::getValueRange() const {
230 return getOperand()->getValueRange().zeroExtend(getType());
231}
232
233void SCEVZeroExtendExpr::print(std::ostream &OS) const {
234 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
235}
236
237// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
238// particular input. Don't use a SCEVHandle here, or else the object will never
239// be deleted!
240static std::map<std::pair<unsigned, std::vector<SCEV*> >,
241 SCEVCommutativeExpr*> SCEVCommExprs;
242
243SCEVCommutativeExpr::~SCEVCommutativeExpr() {
244 SCEVCommExprs.erase(std::make_pair(getSCEVType(),
245 std::vector<SCEV*>(Operands.begin(),
246 Operands.end())));
247}
248
249void SCEVCommutativeExpr::print(std::ostream &OS) const {
250 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
251 const char *OpStr = getOperationStr();
252 OS << "(" << *Operands[0];
253 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
254 OS << OpStr << *Operands[i];
255 OS << ")";
256}
257
258// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
259// input. Don't use a SCEVHandle here, or else the object will never be
260// deleted!
261static std::map<std::pair<SCEV*, SCEV*>, SCEVUDivExpr*> SCEVUDivs;
262
263SCEVUDivExpr::~SCEVUDivExpr() {
264 SCEVUDivs.erase(std::make_pair(LHS, RHS));
265}
266
267void SCEVUDivExpr::print(std::ostream &OS) const {
268 OS << "(" << *LHS << " /u " << *RHS << ")";
269}
270
271const Type *SCEVUDivExpr::getType() const {
272 const Type *Ty = LHS->getType();
273 if (Ty->isSigned()) Ty = Ty->getUnsignedVersion();
274 return Ty;
275}
276
277// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
278// particular input. Don't use a SCEVHandle here, or else the object will never
279// be deleted!
280static std::map<std::pair<const Loop *, std::vector<SCEV*> >,
281 SCEVAddRecExpr*> SCEVAddRecExprs;
282
283SCEVAddRecExpr::~SCEVAddRecExpr() {
284 SCEVAddRecExprs.erase(std::make_pair(L,
285 std::vector<SCEV*>(Operands.begin(),
286 Operands.end())));
287}
288
289bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
290 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
291 // contain L.
292 return !QueryLoop->contains(L->getHeader());
Chris Lattner53e677a2004-04-02 20:23:17 +0000293}
294
295
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000296void SCEVAddRecExpr::print(std::ostream &OS) const {
297 OS << "{" << *Operands[0];
298 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
299 OS << ",+," << *Operands[i];
300 OS << "}<" << L->getHeader()->getName() + ">";
301}
Chris Lattner53e677a2004-04-02 20:23:17 +0000302
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000303// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
304// value. Don't use a SCEVHandle here, or else the object will never be
305// deleted!
306static std::map<Value*, SCEVUnknown*> SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000307
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000308SCEVUnknown::~SCEVUnknown() { SCEVUnknowns.erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000309
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000310bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
311 // All non-instruction values are loop invariant. All instructions are loop
312 // invariant if they are not contained in the specified loop.
313 if (Instruction *I = dyn_cast<Instruction>(V))
314 return !L->contains(I->getParent());
315 return true;
316}
Chris Lattner53e677a2004-04-02 20:23:17 +0000317
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000318const Type *SCEVUnknown::getType() const {
319 return V->getType();
320}
Chris Lattner53e677a2004-04-02 20:23:17 +0000321
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000322void SCEVUnknown::print(std::ostream &OS) const {
323 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000324}
325
Chris Lattner8d741b82004-06-20 06:23:15 +0000326//===----------------------------------------------------------------------===//
327// SCEV Utilities
328//===----------------------------------------------------------------------===//
329
330namespace {
331 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
332 /// than the complexity of the RHS. This comparator is used to canonicalize
333 /// expressions.
334 struct SCEVComplexityCompare {
335 bool operator()(SCEV *LHS, SCEV *RHS) {
336 return LHS->getSCEVType() < RHS->getSCEVType();
337 }
338 };
339}
340
341/// GroupByComplexity - Given a list of SCEV objects, order them by their
342/// complexity, and group objects of the same complexity together by value.
343/// When this routine is finished, we know that any duplicates in the vector are
344/// consecutive and that complexity is monotonically increasing.
345///
346/// Note that we go take special precautions to ensure that we get determinstic
347/// results from this routine. In other words, we don't want the results of
348/// this to depend on where the addresses of various SCEV objects happened to
349/// land in memory.
350///
351static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
352 if (Ops.size() < 2) return; // Noop
353 if (Ops.size() == 2) {
354 // This is the common case, which also happens to be trivially simple.
355 // Special case it.
356 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
357 std::swap(Ops[0], Ops[1]);
358 return;
359 }
360
361 // Do the rough sort by complexity.
362 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
363
364 // Now that we are sorted by complexity, group elements of the same
365 // complexity. Note that this is, at worst, N^2, but the vector is likely to
366 // be extremely short in practice. Note that we take this approach because we
367 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000368 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000369 SCEV *S = Ops[i];
370 unsigned Complexity = S->getSCEVType();
371
372 // If there are any objects of the same complexity and same value as this
373 // one, group them.
374 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
375 if (Ops[j] == S) { // Found a duplicate.
376 // Move it to immediately after i'th element.
377 std::swap(Ops[i+1], Ops[j]);
378 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000379 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000380 }
381 }
382 }
383}
384
Chris Lattner53e677a2004-04-02 20:23:17 +0000385
Chris Lattner53e677a2004-04-02 20:23:17 +0000386
387//===----------------------------------------------------------------------===//
388// Simple SCEV method implementations
389//===----------------------------------------------------------------------===//
390
391/// getIntegerSCEV - Given an integer or FP type, create a constant for the
392/// specified signed integer value and return a SCEV for the constant.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000393SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000394 Constant *C;
395 if (Val == 0)
396 C = Constant::getNullValue(Ty);
397 else if (Ty->isFloatingPoint())
398 C = ConstantFP::get(Ty, Val);
399 else if (Ty->isSigned())
400 C = ConstantSInt::get(Ty, Val);
401 else {
402 C = ConstantSInt::get(Ty->getSignedVersion(), Val);
403 C = ConstantExpr::getCast(C, Ty);
404 }
405 return SCEVUnknown::get(C);
406}
407
408/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
409/// input value to the specified type. If the type must be extended, it is zero
410/// extended.
411static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
412 const Type *SrcTy = V->getType();
413 assert(SrcTy->isInteger() && Ty->isInteger() &&
414 "Cannot truncate or zero extend with non-integer arguments!");
415 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
416 return V; // No conversion
417 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
418 return SCEVTruncateExpr::get(V, Ty);
419 return SCEVZeroExtendExpr::get(V, Ty);
420}
421
422/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
423///
424static SCEVHandle getNegativeSCEV(const SCEVHandle &V) {
425 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
426 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
427
Chris Lattnerb06432c2004-04-23 21:29:03 +0000428 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000429}
430
431/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
432///
433static SCEVHandle getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
434 // X - Y --> X + -Y
435 return SCEVAddExpr::get(LHS, getNegativeSCEV(RHS));
436}
437
438
439/// Binomial - Evaluate N!/((N-M)!*M!) . Note that N is often large and M is
440/// often very small, so we try to reduce the number of N! terms we need to
441/// evaluate by evaluating this as (N!/(N-M)!)/M!
442static ConstantInt *Binomial(ConstantInt *N, unsigned M) {
443 uint64_t NVal = N->getRawValue();
444 uint64_t FirstTerm = 1;
445 for (unsigned i = 0; i != M; ++i)
446 FirstTerm *= NVal-i;
447
448 unsigned MFactorial = 1;
449 for (; M; --M)
450 MFactorial *= M;
451
452 Constant *Result = ConstantUInt::get(Type::ULongTy, FirstTerm/MFactorial);
453 Result = ConstantExpr::getCast(Result, N->getType());
454 assert(isa<ConstantInt>(Result) && "Cast of integer not folded??");
455 return cast<ConstantInt>(Result);
456}
457
458/// PartialFact - Compute V!/(V-NumSteps)!
459static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
460 // Handle this case efficiently, it is common to have constant iteration
461 // counts while computing loop exit values.
462 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
463 uint64_t Val = SC->getValue()->getRawValue();
464 uint64_t Result = 1;
465 for (; NumSteps; --NumSteps)
466 Result *= Val-(NumSteps-1);
467 Constant *Res = ConstantUInt::get(Type::ULongTy, Result);
468 return SCEVUnknown::get(ConstantExpr::getCast(Res, V->getType()));
469 }
470
471 const Type *Ty = V->getType();
472 if (NumSteps == 0)
Chris Lattnerb06432c2004-04-23 21:29:03 +0000473 return SCEVUnknown::getIntegerSCEV(1, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000474
475 SCEVHandle Result = V;
476 for (unsigned i = 1; i != NumSteps; ++i)
Chris Lattnerb06432c2004-04-23 21:29:03 +0000477 Result = SCEVMulExpr::get(Result, getMinusSCEV(V,
478 SCEVUnknown::getIntegerSCEV(i, Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000479 return Result;
480}
481
482
483/// evaluateAtIteration - Return the value of this chain of recurrences at
484/// the specified iteration number. We can evaluate this recurrence by
485/// multiplying each element in the chain by the binomial coefficient
486/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
487///
488/// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
489///
490/// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
491/// Is the binomial equation safe using modular arithmetic??
492///
493SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
494 SCEVHandle Result = getStart();
495 int Divisor = 1;
496 const Type *Ty = It->getType();
497 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
498 SCEVHandle BC = PartialFact(It, i);
499 Divisor *= i;
500 SCEVHandle Val = SCEVUDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
Chris Lattnerb06432c2004-04-23 21:29:03 +0000501 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000502 Result = SCEVAddExpr::get(Result, Val);
503 }
504 return Result;
505}
506
507
508//===----------------------------------------------------------------------===//
509// SCEV Expression folder implementations
510//===----------------------------------------------------------------------===//
511
512SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
513 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
514 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
515
516 // If the input value is a chrec scev made out of constants, truncate
517 // all of the constants.
518 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
519 std::vector<SCEVHandle> Operands;
520 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
521 // FIXME: This should allow truncation of other expression types!
522 if (isa<SCEVConstant>(AddRec->getOperand(i)))
523 Operands.push_back(get(AddRec->getOperand(i), Ty));
524 else
525 break;
526 if (Operands.size() == AddRec->getNumOperands())
527 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
528 }
529
530 SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)];
531 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
532 return Result;
533}
534
535SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
536 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
537 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
538
539 // FIXME: If the input value is a chrec scev, and we can prove that the value
540 // did not overflow the old, smaller, value, we can zero extend all of the
541 // operands (often constants). This would allow analysis of something like
542 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
543
544 SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)];
545 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
546 return Result;
547}
548
549// get - Get a canonical add expression, or something simpler if possible.
550SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
551 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000552 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000553
554 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000555 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000556
557 // If there are any constants, fold them together.
558 unsigned Idx = 0;
559 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
560 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000561 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000562 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
563 // We found two constants, fold them together!
564 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
565 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
566 Ops[0] = SCEVConstant::get(CI);
567 Ops.erase(Ops.begin()+1); // Erase the folded element
568 if (Ops.size() == 1) return Ops[0];
569 } else {
570 // If we couldn't fold the expression, move to the next constant. Note
571 // that this is impossible to happen in practice because we always
572 // constant fold constant ints to constant ints.
573 ++Idx;
574 }
575 }
576
577 // If we are left with a constant zero being added, strip it off.
578 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
579 Ops.erase(Ops.begin());
580 --Idx;
581 }
582 }
583
Chris Lattner627018b2004-04-07 16:16:11 +0000584 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000585
586 // Okay, check to see if the same value occurs in the operand list twice. If
587 // so, merge them together into an multiply expression. Since we sorted the
588 // list, these values are required to be adjacent.
589 const Type *Ty = Ops[0]->getType();
590 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
591 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
592 // Found a match, merge the two values into a multiply, and add any
593 // remaining values to the result.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000594 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000595 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
596 if (Ops.size() == 2)
597 return Mul;
598 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
599 Ops.push_back(Mul);
600 return SCEVAddExpr::get(Ops);
601 }
602
603 // Okay, now we know the first non-constant operand. If there are add
604 // operands they would be next.
605 if (Idx < Ops.size()) {
606 bool DeletedAdd = false;
607 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
608 // If we have an add, expand the add operands onto the end of the operands
609 // list.
610 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
611 Ops.erase(Ops.begin()+Idx);
612 DeletedAdd = true;
613 }
614
615 // If we deleted at least one add, we added operands to the end of the list,
616 // and they are not necessarily sorted. Recurse to resort and resimplify
617 // any operands we just aquired.
618 if (DeletedAdd)
619 return get(Ops);
620 }
621
622 // Skip over the add expression until we get to a multiply.
623 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
624 ++Idx;
625
626 // If we are adding something to a multiply expression, make sure the
627 // something is not already an operand of the multiply. If so, merge it into
628 // the multiply.
629 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
630 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
631 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
632 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
633 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
634 if (MulOpSCEV == Ops[AddOp] &&
635 (Mul->getNumOperands() != 2 || !isa<SCEVConstant>(MulOpSCEV))) {
636 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
637 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
638 if (Mul->getNumOperands() != 2) {
639 // If the multiply has more than two operands, we must get the
640 // Y*Z term.
641 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
642 MulOps.erase(MulOps.begin()+MulOp);
643 InnerMul = SCEVMulExpr::get(MulOps);
644 }
Chris Lattnerb06432c2004-04-23 21:29:03 +0000645 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000646 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
647 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
648 if (Ops.size() == 2) return OuterMul;
649 if (AddOp < Idx) {
650 Ops.erase(Ops.begin()+AddOp);
651 Ops.erase(Ops.begin()+Idx-1);
652 } else {
653 Ops.erase(Ops.begin()+Idx);
654 Ops.erase(Ops.begin()+AddOp-1);
655 }
656 Ops.push_back(OuterMul);
657 return SCEVAddExpr::get(Ops);
658 }
659
660 // Check this multiply against other multiplies being added together.
661 for (unsigned OtherMulIdx = Idx+1;
662 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
663 ++OtherMulIdx) {
664 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
665 // If MulOp occurs in OtherMul, we can fold the two multiplies
666 // together.
667 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
668 OMulOp != e; ++OMulOp)
669 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
670 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
671 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
672 if (Mul->getNumOperands() != 2) {
673 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
674 MulOps.erase(MulOps.begin()+MulOp);
675 InnerMul1 = SCEVMulExpr::get(MulOps);
676 }
677 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
678 if (OtherMul->getNumOperands() != 2) {
679 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
680 OtherMul->op_end());
681 MulOps.erase(MulOps.begin()+OMulOp);
682 InnerMul2 = SCEVMulExpr::get(MulOps);
683 }
684 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
685 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
686 if (Ops.size() == 2) return OuterMul;
687 Ops.erase(Ops.begin()+Idx);
688 Ops.erase(Ops.begin()+OtherMulIdx-1);
689 Ops.push_back(OuterMul);
690 return SCEVAddExpr::get(Ops);
691 }
692 }
693 }
694 }
695
696 // If there are any add recurrences in the operands list, see if any other
697 // added values are loop invariant. If so, we can fold them into the
698 // recurrence.
699 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
700 ++Idx;
701
702 // Scan over all recurrences, trying to fold loop invariants into them.
703 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
704 // Scan all of the other operands to this add and add them to the vector if
705 // they are loop invariant w.r.t. the recurrence.
706 std::vector<SCEVHandle> LIOps;
707 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
708 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
709 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
710 LIOps.push_back(Ops[i]);
711 Ops.erase(Ops.begin()+i);
712 --i; --e;
713 }
714
715 // If we found some loop invariants, fold them into the recurrence.
716 if (!LIOps.empty()) {
717 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
718 LIOps.push_back(AddRec->getStart());
719
720 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
721 AddRecOps[0] = SCEVAddExpr::get(LIOps);
722
723 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
724 // If all of the other operands were loop invariant, we are done.
725 if (Ops.size() == 1) return NewRec;
726
727 // Otherwise, add the folded AddRec by the non-liv parts.
728 for (unsigned i = 0;; ++i)
729 if (Ops[i] == AddRec) {
730 Ops[i] = NewRec;
731 break;
732 }
733 return SCEVAddExpr::get(Ops);
734 }
735
736 // Okay, if there weren't any loop invariants to be folded, check to see if
737 // there are multiple AddRec's with the same loop induction variable being
738 // added together. If so, we can fold them.
739 for (unsigned OtherIdx = Idx+1;
740 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
741 if (OtherIdx != Idx) {
742 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
743 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
744 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
745 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
746 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
747 if (i >= NewOps.size()) {
748 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
749 OtherAddRec->op_end());
750 break;
751 }
752 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
753 }
754 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
755
756 if (Ops.size() == 2) return NewAddRec;
757
758 Ops.erase(Ops.begin()+Idx);
759 Ops.erase(Ops.begin()+OtherIdx-1);
760 Ops.push_back(NewAddRec);
761 return SCEVAddExpr::get(Ops);
762 }
763 }
764
765 // Otherwise couldn't fold anything into this recurrence. Move onto the
766 // next one.
767 }
768
769 // Okay, it looks like we really DO need an add expr. Check to see if we
770 // already have one, otherwise create a new one.
771 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
772 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr,
773 SCEVOps)];
774 if (Result == 0) Result = new SCEVAddExpr(Ops);
775 return Result;
776}
777
778
779SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
780 assert(!Ops.empty() && "Cannot get empty mul!");
781
782 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000783 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000784
785 // If there are any constants, fold them together.
786 unsigned Idx = 0;
787 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
788
789 // C1*(C2+V) -> C1*C2 + C1*V
790 if (Ops.size() == 2)
791 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
792 if (Add->getNumOperands() == 2 &&
793 isa<SCEVConstant>(Add->getOperand(0)))
794 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
795 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
796
797
798 ++Idx;
799 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
800 // We found two constants, fold them together!
801 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
802 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
803 Ops[0] = SCEVConstant::get(CI);
804 Ops.erase(Ops.begin()+1); // Erase the folded element
805 if (Ops.size() == 1) return Ops[0];
806 } else {
807 // If we couldn't fold the expression, move to the next constant. Note
808 // that this is impossible to happen in practice because we always
809 // constant fold constant ints to constant ints.
810 ++Idx;
811 }
812 }
813
814 // If we are left with a constant one being multiplied, strip it off.
815 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
816 Ops.erase(Ops.begin());
817 --Idx;
818 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
819 // If we have a multiply of zero, it will always be zero.
820 return Ops[0];
821 }
822 }
823
824 // Skip over the add expression until we get to a multiply.
825 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
826 ++Idx;
827
828 if (Ops.size() == 1)
829 return Ops[0];
830
831 // If there are mul operands inline them all into this expression.
832 if (Idx < Ops.size()) {
833 bool DeletedMul = false;
834 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
835 // If we have an mul, expand the mul operands onto the end of the operands
836 // list.
837 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
838 Ops.erase(Ops.begin()+Idx);
839 DeletedMul = true;
840 }
841
842 // If we deleted at least one mul, we added operands to the end of the list,
843 // and they are not necessarily sorted. Recurse to resort and resimplify
844 // any operands we just aquired.
845 if (DeletedMul)
846 return get(Ops);
847 }
848
849 // If there are any add recurrences in the operands list, see if any other
850 // added values are loop invariant. If so, we can fold them into the
851 // recurrence.
852 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
853 ++Idx;
854
855 // Scan over all recurrences, trying to fold loop invariants into them.
856 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
857 // Scan all of the other operands to this mul and add them to the vector if
858 // they are loop invariant w.r.t. the recurrence.
859 std::vector<SCEVHandle> LIOps;
860 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
861 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
862 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
863 LIOps.push_back(Ops[i]);
864 Ops.erase(Ops.begin()+i);
865 --i; --e;
866 }
867
868 // If we found some loop invariants, fold them into the recurrence.
869 if (!LIOps.empty()) {
870 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
871 std::vector<SCEVHandle> NewOps;
872 NewOps.reserve(AddRec->getNumOperands());
873 if (LIOps.size() == 1) {
874 SCEV *Scale = LIOps[0];
875 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
876 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
877 } else {
878 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
879 std::vector<SCEVHandle> MulOps(LIOps);
880 MulOps.push_back(AddRec->getOperand(i));
881 NewOps.push_back(SCEVMulExpr::get(MulOps));
882 }
883 }
884
885 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
886
887 // If all of the other operands were loop invariant, we are done.
888 if (Ops.size() == 1) return NewRec;
889
890 // Otherwise, multiply the folded AddRec by the non-liv parts.
891 for (unsigned i = 0;; ++i)
892 if (Ops[i] == AddRec) {
893 Ops[i] = NewRec;
894 break;
895 }
896 return SCEVMulExpr::get(Ops);
897 }
898
899 // Okay, if there weren't any loop invariants to be folded, check to see if
900 // there are multiple AddRec's with the same loop induction variable being
901 // multiplied together. If so, we can fold them.
902 for (unsigned OtherIdx = Idx+1;
903 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
904 if (OtherIdx != Idx) {
905 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
906 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
907 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
908 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
909 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
910 G->getStart());
911 SCEVHandle B = F->getStepRecurrence();
912 SCEVHandle D = G->getStepRecurrence();
913 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
914 SCEVMulExpr::get(G, B),
915 SCEVMulExpr::get(B, D));
916 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
917 F->getLoop());
918 if (Ops.size() == 2) return NewAddRec;
919
920 Ops.erase(Ops.begin()+Idx);
921 Ops.erase(Ops.begin()+OtherIdx-1);
922 Ops.push_back(NewAddRec);
923 return SCEVMulExpr::get(Ops);
924 }
925 }
926
927 // Otherwise couldn't fold anything into this recurrence. Move onto the
928 // next one.
929 }
930
931 // Okay, it looks like we really DO need an mul expr. Check to see if we
932 // already have one, otherwise create a new one.
933 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
934 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr,
935 SCEVOps)];
936 if (Result == 0) Result = new SCEVMulExpr(Ops);
937 return Result;
938}
939
940SCEVHandle SCEVUDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
941 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
942 if (RHSC->getValue()->equalsInt(1))
943 return LHS; // X /u 1 --> x
944 if (RHSC->getValue()->isAllOnesValue())
945 return getNegativeSCEV(LHS); // X /u -1 --> -x
946
947 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
948 Constant *LHSCV = LHSC->getValue();
949 Constant *RHSCV = RHSC->getValue();
950 if (LHSCV->getType()->isSigned())
951 LHSCV = ConstantExpr::getCast(LHSCV,
952 LHSCV->getType()->getUnsignedVersion());
953 if (RHSCV->getType()->isSigned())
954 RHSCV = ConstantExpr::getCast(RHSCV, LHSCV->getType());
955 return SCEVUnknown::get(ConstantExpr::getDiv(LHSCV, RHSCV));
956 }
957 }
958
959 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
960
961 SCEVUDivExpr *&Result = SCEVUDivs[std::make_pair(LHS, RHS)];
962 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
963 return Result;
964}
965
966
967/// SCEVAddRecExpr::get - Get a add recurrence expression for the
968/// specified loop. Simplify the expression as much as possible.
969SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
970 const SCEVHandle &Step, const Loop *L) {
971 std::vector<SCEVHandle> Operands;
972 Operands.push_back(Start);
973 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
974 if (StepChrec->getLoop() == L) {
975 Operands.insert(Operands.end(), StepChrec->op_begin(),
976 StepChrec->op_end());
977 return get(Operands, L);
978 }
979
980 Operands.push_back(Step);
981 return get(Operands, L);
982}
983
984/// SCEVAddRecExpr::get - Get a add recurrence expression for the
985/// specified loop. Simplify the expression as much as possible.
986SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
987 const Loop *L) {
988 if (Operands.size() == 1) return Operands[0];
989
990 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
991 if (StepC->getValue()->isNullValue()) {
992 Operands.pop_back();
993 return get(Operands, L); // { X,+,0 } --> X
994 }
995
996 SCEVAddRecExpr *&Result =
997 SCEVAddRecExprs[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
998 Operands.end()))];
999 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1000 return Result;
1001}
1002
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001003SCEVHandle SCEVUnknown::get(Value *V) {
1004 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1005 return SCEVConstant::get(CI);
1006 SCEVUnknown *&Result = SCEVUnknowns[V];
1007 if (Result == 0) Result = new SCEVUnknown(V);
1008 return Result;
1009}
1010
Chris Lattner53e677a2004-04-02 20:23:17 +00001011
1012//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001013// ScalarEvolutionsImpl Definition and Implementation
1014//===----------------------------------------------------------------------===//
1015//
1016/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1017/// evolution code.
1018///
1019namespace {
1020 struct ScalarEvolutionsImpl {
1021 /// F - The function we are analyzing.
1022 ///
1023 Function &F;
1024
1025 /// LI - The loop information for the function we are currently analyzing.
1026 ///
1027 LoopInfo &LI;
1028
1029 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1030 /// things.
1031 SCEVHandle UnknownValue;
1032
1033 /// Scalars - This is a cache of the scalars we have analyzed so far.
1034 ///
1035 std::map<Value*, SCEVHandle> Scalars;
1036
1037 /// IterationCounts - Cache the iteration count of the loops for this
1038 /// function as they are computed.
1039 std::map<const Loop*, SCEVHandle> IterationCounts;
1040
Chris Lattner3221ad02004-04-17 22:58:41 +00001041 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1042 /// the PHI instructions that we attempt to compute constant evolutions for.
1043 /// This allows us to avoid potentially expensive recomputation of these
1044 /// properties. An instruction maps to null if we are unable to compute its
1045 /// exit value.
1046 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1047
Chris Lattner53e677a2004-04-02 20:23:17 +00001048 public:
1049 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1050 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1051
1052 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1053 /// expression and create a new one.
1054 SCEVHandle getSCEV(Value *V);
1055
1056 /// getSCEVAtScope - Compute the value of the specified expression within
1057 /// the indicated loop (which may be null to indicate in no loop). If the
1058 /// expression cannot be evaluated, return UnknownValue itself.
1059 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1060
1061
1062 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1063 /// an analyzable loop-invariant iteration count.
1064 bool hasLoopInvariantIterationCount(const Loop *L);
1065
1066 /// getIterationCount - If the specified loop has a predictable iteration
1067 /// count, return it. Note that it is not valid to call this method on a
1068 /// loop without a loop-invariant iteration count.
1069 SCEVHandle getIterationCount(const Loop *L);
1070
1071 /// deleteInstructionFromRecords - This method should be called by the
1072 /// client before it removes an instruction from the program, to make sure
1073 /// that no dangling references are left around.
1074 void deleteInstructionFromRecords(Instruction *I);
1075
1076 private:
1077 /// createSCEV - We know that there is no SCEV for the specified value.
1078 /// Analyze the expression.
1079 SCEVHandle createSCEV(Value *V);
1080 SCEVHandle createNodeForCast(CastInst *CI);
1081
1082 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1083 /// SCEVs.
1084 SCEVHandle createNodeForPHI(PHINode *PN);
1085 void UpdatePHIUserScalarEntries(Instruction *I, PHINode *PN,
1086 std::set<Instruction*> &UpdatedInsts);
1087
1088 /// ComputeIterationCount - Compute the number of times the specified loop
1089 /// will iterate.
1090 SCEVHandle ComputeIterationCount(const Loop *L);
1091
Chris Lattner7980fb92004-04-17 18:36:24 +00001092 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1093 /// constant number of times (the condition evolves only from constants),
1094 /// try to evaluate a few iterations of the loop until we get the exit
1095 /// condition gets a value of ExitWhen (true or false). If we cannot
1096 /// evaluate the trip count of the loop, return UnknownValue.
1097 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1098 bool ExitWhen);
1099
Chris Lattner53e677a2004-04-02 20:23:17 +00001100 /// HowFarToZero - Return the number of times a backedge comparing the
1101 /// specified value to zero will execute. If not computable, return
1102 /// UnknownValue
1103 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1104
1105 /// HowFarToNonZero - Return the number of times a backedge checking the
1106 /// specified value for nonzero will execute. If not computable, return
1107 /// UnknownValue
1108 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001109
1110 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1111 /// in the header of its containing loop, we know the loop executes a
1112 /// constant number of times, and the PHI node is just a recurrence
1113 /// involving constants, fold it.
1114 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1115 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001116 };
1117}
1118
1119//===----------------------------------------------------------------------===//
1120// Basic SCEV Analysis and PHI Idiom Recognition Code
1121//
1122
1123/// deleteInstructionFromRecords - This method should be called by the
1124/// client before it removes an instruction from the program, to make sure
1125/// that no dangling references are left around.
1126void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1127 Scalars.erase(I);
Chris Lattner3221ad02004-04-17 22:58:41 +00001128 if (PHINode *PN = dyn_cast<PHINode>(I))
1129 ConstantEvolutionLoopExitValue.erase(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001130}
1131
1132
1133/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1134/// expression and create a new one.
1135SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1136 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1137
1138 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1139 if (I != Scalars.end()) return I->second;
1140 SCEVHandle S = createSCEV(V);
1141 Scalars.insert(std::make_pair(V, S));
1142 return S;
1143}
1144
1145
1146/// UpdatePHIUserScalarEntries - After PHI node analysis, we have a bunch of
1147/// entries in the scalar map that refer to the "symbolic" PHI value instead of
1148/// the recurrence value. After we resolve the PHI we must loop over all of the
1149/// using instructions that have scalar map entries and update them.
1150void ScalarEvolutionsImpl::UpdatePHIUserScalarEntries(Instruction *I,
1151 PHINode *PN,
1152 std::set<Instruction*> &UpdatedInsts) {
1153 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1154 if (SI == Scalars.end()) return; // This scalar wasn't previous processed.
1155 if (UpdatedInsts.insert(I).second) {
1156 Scalars.erase(SI); // Remove the old entry
1157 getSCEV(I); // Calculate the new entry
1158
1159 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1160 UI != E; ++UI)
1161 UpdatePHIUserScalarEntries(cast<Instruction>(*UI), PN, UpdatedInsts);
1162 }
1163}
1164
1165
1166/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1167/// a loop header, making it a potential recurrence, or it doesn't.
1168///
1169SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1170 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1171 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1172 if (L->getHeader() == PN->getParent()) {
1173 // If it lives in the loop header, it has two incoming values, one
1174 // from outside the loop, and one from inside.
1175 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1176 unsigned BackEdge = IncomingEdge^1;
1177
1178 // While we are analyzing this PHI node, handle its value symbolically.
1179 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1180 assert(Scalars.find(PN) == Scalars.end() &&
1181 "PHI node already processed?");
1182 Scalars.insert(std::make_pair(PN, SymbolicName));
1183
1184 // Using this symbolic name for the PHI, analyze the value coming around
1185 // the back-edge.
1186 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1187
1188 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1189 // has a special value for the first iteration of the loop.
1190
1191 // If the value coming around the backedge is an add with the symbolic
1192 // value we just inserted, then we found a simple induction variable!
1193 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1194 // If there is a single occurrence of the symbolic value, replace it
1195 // with a recurrence.
1196 unsigned FoundIndex = Add->getNumOperands();
1197 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1198 if (Add->getOperand(i) == SymbolicName)
1199 if (FoundIndex == e) {
1200 FoundIndex = i;
1201 break;
1202 }
1203
1204 if (FoundIndex != Add->getNumOperands()) {
1205 // Create an add with everything but the specified operand.
1206 std::vector<SCEVHandle> Ops;
1207 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1208 if (i != FoundIndex)
1209 Ops.push_back(Add->getOperand(i));
1210 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1211
1212 // This is not a valid addrec if the step amount is varying each
1213 // loop iteration, but is not itself an addrec in this loop.
1214 if (Accum->isLoopInvariant(L) ||
1215 (isa<SCEVAddRecExpr>(Accum) &&
1216 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1217 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1218 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1219
1220 // Okay, for the entire analysis of this edge we assumed the PHI
1221 // to be symbolic. We now need to go back and update all of the
1222 // entries for the scalars that use the PHI (except for the PHI
1223 // itself) to use the new analyzed value instead of the "symbolic"
1224 // value.
1225 Scalars.find(PN)->second = PHISCEV; // Update the PHI value
1226 std::set<Instruction*> UpdatedInsts;
1227 UpdatedInsts.insert(PN);
1228 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
1229 UI != E; ++UI)
1230 UpdatePHIUserScalarEntries(cast<Instruction>(*UI), PN,
1231 UpdatedInsts);
1232 return PHISCEV;
1233 }
1234 }
1235 }
1236
1237 return SymbolicName;
1238 }
1239
1240 // If it's not a loop phi, we can't handle it yet.
1241 return SCEVUnknown::get(PN);
1242}
1243
1244/// createNodeForCast - Handle the various forms of casts that we support.
1245///
1246SCEVHandle ScalarEvolutionsImpl::createNodeForCast(CastInst *CI) {
1247 const Type *SrcTy = CI->getOperand(0)->getType();
1248 const Type *DestTy = CI->getType();
1249
1250 // If this is a noop cast (ie, conversion from int to uint), ignore it.
1251 if (SrcTy->isLosslesslyConvertibleTo(DestTy))
1252 return getSCEV(CI->getOperand(0));
1253
1254 if (SrcTy->isInteger() && DestTy->isInteger()) {
1255 // Otherwise, if this is a truncating integer cast, we can represent this
1256 // cast.
1257 if (SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1258 return SCEVTruncateExpr::get(getSCEV(CI->getOperand(0)),
1259 CI->getType()->getUnsignedVersion());
1260 if (SrcTy->isUnsigned() &&
1261 SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1262 return SCEVZeroExtendExpr::get(getSCEV(CI->getOperand(0)),
1263 CI->getType()->getUnsignedVersion());
1264 }
1265
1266 // If this is an sign or zero extending cast and we can prove that the value
1267 // will never overflow, we could do similar transformations.
1268
1269 // Otherwise, we can't handle this cast!
1270 return SCEVUnknown::get(CI);
1271}
1272
1273
1274/// createSCEV - We know that there is no SCEV for the specified value.
1275/// Analyze the expression.
1276///
1277SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1278 if (Instruction *I = dyn_cast<Instruction>(V)) {
1279 switch (I->getOpcode()) {
1280 case Instruction::Add:
1281 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1282 getSCEV(I->getOperand(1)));
1283 case Instruction::Mul:
1284 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1285 getSCEV(I->getOperand(1)));
1286 case Instruction::Div:
1287 if (V->getType()->isInteger() && V->getType()->isUnsigned())
1288 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)),
1289 getSCEV(I->getOperand(1)));
1290 break;
1291
1292 case Instruction::Sub:
1293 return getMinusSCEV(getSCEV(I->getOperand(0)), getSCEV(I->getOperand(1)));
1294
1295 case Instruction::Shl:
1296 // Turn shift left of a constant amount into a multiply.
1297 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1298 Constant *X = ConstantInt::get(V->getType(), 1);
1299 X = ConstantExpr::getShl(X, SA);
1300 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1301 }
1302 break;
1303
1304 case Instruction::Shr:
1305 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1306 if (V->getType()->isUnsigned()) {
1307 Constant *X = ConstantInt::get(V->getType(), 1);
1308 X = ConstantExpr::getShl(X, SA);
1309 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1310 }
1311 break;
1312
1313 case Instruction::Cast:
1314 return createNodeForCast(cast<CastInst>(I));
1315
1316 case Instruction::PHI:
1317 return createNodeForPHI(cast<PHINode>(I));
1318
1319 default: // We cannot analyze this expression.
1320 break;
1321 }
1322 }
1323
1324 return SCEVUnknown::get(V);
1325}
1326
1327
1328
1329//===----------------------------------------------------------------------===//
1330// Iteration Count Computation Code
1331//
1332
1333/// getIterationCount - If the specified loop has a predictable iteration
1334/// count, return it. Note that it is not valid to call this method on a
1335/// loop without a loop-invariant iteration count.
1336SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1337 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1338 if (I == IterationCounts.end()) {
1339 SCEVHandle ItCount = ComputeIterationCount(L);
1340 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1341 if (ItCount != UnknownValue) {
1342 assert(ItCount->isLoopInvariant(L) &&
1343 "Computed trip count isn't loop invariant for loop!");
1344 ++NumTripCountsComputed;
1345 } else if (isa<PHINode>(L->getHeader()->begin())) {
1346 // Only count loops that have phi nodes as not being computable.
1347 ++NumTripCountsNotComputed;
1348 }
1349 }
1350 return I->second;
1351}
1352
1353/// ComputeIterationCount - Compute the number of times the specified loop
1354/// will iterate.
1355SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1356 // If the loop has a non-one exit block count, we can't analyze it.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001357 std::vector<BasicBlock*> ExitBlocks;
1358 L->getExitBlocks(ExitBlocks);
1359 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001360
1361 // Okay, there is one exit block. Try to find the condition that causes the
1362 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001363 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001364
1365 BasicBlock *ExitingBlock = 0;
1366 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1367 PI != E; ++PI)
1368 if (L->contains(*PI)) {
1369 if (ExitingBlock == 0)
1370 ExitingBlock = *PI;
1371 else
1372 return UnknownValue; // More than one block exiting!
1373 }
1374 assert(ExitingBlock && "No exits from loop, something is broken!");
1375
1376 // Okay, we've computed the exiting block. See what condition causes us to
1377 // exit.
1378 //
1379 // FIXME: we should be able to handle switch instructions (with a single exit)
1380 // FIXME: We should handle cast of int to bool as well
1381 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1382 if (ExitBr == 0) return UnknownValue;
1383 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1384 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
Chris Lattner7980fb92004-04-17 18:36:24 +00001385 if (ExitCond == 0) // Not a setcc
1386 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1387 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001388
1389 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1390 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1391
1392 // Try to evaluate any dependencies out of the loop.
1393 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1394 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1395 Tmp = getSCEVAtScope(RHS, L);
1396 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1397
1398 // If the condition was exit on true, convert the condition to exit on false.
1399 Instruction::BinaryOps Cond;
1400 if (ExitBr->getSuccessor(1) == ExitBlock)
1401 Cond = ExitCond->getOpcode();
1402 else
1403 Cond = ExitCond->getInverseCondition();
1404
1405 // At this point, we would like to compute how many iterations of the loop the
1406 // predicate will return true for these inputs.
1407 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1408 // If there is a constant, force it into the RHS.
1409 std::swap(LHS, RHS);
1410 Cond = SetCondInst::getSwappedCondition(Cond);
1411 }
1412
1413 // FIXME: think about handling pointer comparisons! i.e.:
1414 // while (P != P+100) ++P;
1415
1416 // If we have a comparison of a chrec against a constant, try to use value
1417 // ranges to answer this query.
1418 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1419 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1420 if (AddRec->getLoop() == L) {
1421 // Form the comparison range using the constant of the correct type so
1422 // that the ConstantRange class knows to do a signed or unsigned
1423 // comparison.
1424 ConstantInt *CompVal = RHSC->getValue();
1425 const Type *RealTy = ExitCond->getOperand(0)->getType();
1426 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1427 if (CompVal) {
1428 // Form the constant range.
1429 ConstantRange CompRange(Cond, CompVal);
1430
1431 // Now that we have it, if it's signed, convert it to an unsigned
1432 // range.
1433 if (CompRange.getLower()->getType()->isSigned()) {
1434 const Type *NewTy = RHSC->getValue()->getType();
1435 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1436 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1437 CompRange = ConstantRange(NewL, NewU);
1438 }
1439
1440 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1441 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1442 }
1443 }
1444
1445 switch (Cond) {
1446 case Instruction::SetNE: // while (X != Y)
1447 // Convert to: while (X-Y != 0)
Chris Lattner7980fb92004-04-17 18:36:24 +00001448 if (LHS->getType()->isInteger()) {
1449 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
1450 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1451 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001452 break;
1453 case Instruction::SetEQ:
1454 // Convert to: while (X-Y == 0) // while (X == Y)
Chris Lattner7980fb92004-04-17 18:36:24 +00001455 if (LHS->getType()->isInteger()) {
1456 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
1457 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1458 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001459 break;
1460 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001461#if 0
Chris Lattner53e677a2004-04-02 20:23:17 +00001462 std::cerr << "ComputeIterationCount ";
1463 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1464 std::cerr << "[unsigned] ";
1465 std::cerr << *LHS << " "
1466 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001467#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00001468 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001469 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001470
1471 return ComputeIterationCountExhaustively(L, ExitCond,
1472 ExitBr->getSuccessor(0) == ExitBlock);
1473}
1474
Chris Lattner3221ad02004-04-17 22:58:41 +00001475/// CanConstantFold - Return true if we can constant fold an instruction of the
1476/// specified type, assuming that all operands were constants.
1477static bool CanConstantFold(const Instruction *I) {
1478 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1479 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1480 return true;
Chris Lattner7980fb92004-04-17 18:36:24 +00001481
Chris Lattner3221ad02004-04-17 22:58:41 +00001482 if (const CallInst *CI = dyn_cast<CallInst>(I))
1483 if (const Function *F = CI->getCalledFunction())
1484 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1485 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00001486}
1487
Chris Lattner3221ad02004-04-17 22:58:41 +00001488/// ConstantFold - Constant fold an instruction of the specified type with the
1489/// specified constant operands. This function may modify the operands vector.
1490static Constant *ConstantFold(const Instruction *I,
1491 std::vector<Constant*> &Operands) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001492 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1493 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1494
1495 switch (I->getOpcode()) {
1496 case Instruction::Cast:
1497 return ConstantExpr::getCast(Operands[0], I->getType());
1498 case Instruction::Select:
1499 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1500 case Instruction::Call:
Reid Spencere8404342004-07-18 00:18:30 +00001501 if (Function *GV = dyn_cast<Function>(Operands[0])) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001502 Operands.erase(Operands.begin());
Reid Spencere8404342004-07-18 00:18:30 +00001503 return ConstantFoldCall(cast<Function>(GV), Operands);
Chris Lattner7980fb92004-04-17 18:36:24 +00001504 }
1505
1506 return 0;
1507 case Instruction::GetElementPtr:
1508 Constant *Base = Operands[0];
1509 Operands.erase(Operands.begin());
1510 return ConstantExpr::getGetElementPtr(Base, Operands);
1511 }
1512 return 0;
1513}
1514
1515
Chris Lattner3221ad02004-04-17 22:58:41 +00001516/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1517/// in the loop that V is derived from. We allow arbitrary operations along the
1518/// way, but the operands of an operation must either be constants or a value
1519/// derived from a constant PHI. If this expression does not fit with these
1520/// constraints, return null.
1521static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1522 // If this is not an instruction, or if this is an instruction outside of the
1523 // loop, it can't be derived from a loop PHI.
1524 Instruction *I = dyn_cast<Instruction>(V);
1525 if (I == 0 || !L->contains(I->getParent())) return 0;
1526
1527 if (PHINode *PN = dyn_cast<PHINode>(I))
1528 if (L->getHeader() == I->getParent())
1529 return PN;
1530 else
1531 // We don't currently keep track of the control flow needed to evaluate
1532 // PHIs, so we cannot handle PHIs inside of loops.
1533 return 0;
1534
1535 // If we won't be able to constant fold this expression even if the operands
1536 // are constants, return early.
1537 if (!CanConstantFold(I)) return 0;
1538
1539 // Otherwise, we can evaluate this instruction if all of its operands are
1540 // constant or derived from a PHI node themselves.
1541 PHINode *PHI = 0;
1542 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1543 if (!(isa<Constant>(I->getOperand(Op)) ||
1544 isa<GlobalValue>(I->getOperand(Op)))) {
1545 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1546 if (P == 0) return 0; // Not evolving from PHI
1547 if (PHI == 0)
1548 PHI = P;
1549 else if (PHI != P)
1550 return 0; // Evolving from multiple different PHIs.
1551 }
1552
1553 // This is a expression evolving from a constant PHI!
1554 return PHI;
1555}
1556
1557/// EvaluateExpression - Given an expression that passes the
1558/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1559/// in the loop has the value PHIVal. If we can't fold this expression for some
1560/// reason, return null.
1561static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1562 if (isa<PHINode>(V)) return PHIVal;
Chris Lattner3221ad02004-04-17 22:58:41 +00001563 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
Reid Spencere8404342004-07-18 00:18:30 +00001564 return GV;
1565 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00001566 Instruction *I = cast<Instruction>(V);
1567
1568 std::vector<Constant*> Operands;
1569 Operands.resize(I->getNumOperands());
1570
1571 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1572 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1573 if (Operands[i] == 0) return 0;
1574 }
1575
1576 return ConstantFold(I, Operands);
1577}
1578
1579/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1580/// in the header of its containing loop, we know the loop executes a
1581/// constant number of times, and the PHI node is just a recurrence
1582/// involving constants, fold it.
1583Constant *ScalarEvolutionsImpl::
1584getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1585 std::map<PHINode*, Constant*>::iterator I =
1586 ConstantEvolutionLoopExitValue.find(PN);
1587 if (I != ConstantEvolutionLoopExitValue.end())
1588 return I->second;
1589
1590 if (Its > MaxBruteForceIterations)
1591 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1592
1593 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1594
1595 // Since the loop is canonicalized, the PHI node must have two entries. One
1596 // entry must be a constant (coming in from outside of the loop), and the
1597 // second must be derived from the same PHI.
1598 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1599 Constant *StartCST =
1600 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1601 if (StartCST == 0)
1602 return RetVal = 0; // Must be a constant.
1603
1604 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1605 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1606 if (PN2 != PN)
1607 return RetVal = 0; // Not derived from same PHI.
1608
1609 // Execute the loop symbolically to determine the exit value.
1610 unsigned IterationNum = 0;
1611 unsigned NumIterations = Its;
1612 if (NumIterations != Its)
1613 return RetVal = 0; // More than 2^32 iterations??
1614
1615 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1616 if (IterationNum == NumIterations)
1617 return RetVal = PHIVal; // Got exit value!
1618
1619 // Compute the value of the PHI node for the next iteration.
1620 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1621 if (NextPHI == PHIVal)
1622 return RetVal = NextPHI; // Stopped evolving!
1623 if (NextPHI == 0)
1624 return 0; // Couldn't evaluate!
1625 PHIVal = NextPHI;
1626 }
1627}
1628
Chris Lattner7980fb92004-04-17 18:36:24 +00001629/// ComputeIterationCountExhaustively - If the trip is known to execute a
1630/// constant number of times (the condition evolves only from constants),
1631/// try to evaluate a few iterations of the loop until we get the exit
1632/// condition gets a value of ExitWhen (true or false). If we cannot
1633/// evaluate the trip count of the loop, return UnknownValue.
1634SCEVHandle ScalarEvolutionsImpl::
1635ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1636 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1637 if (PN == 0) return UnknownValue;
1638
1639 // Since the loop is canonicalized, the PHI node must have two entries. One
1640 // entry must be a constant (coming in from outside of the loop), and the
1641 // second must be derived from the same PHI.
1642 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1643 Constant *StartCST =
1644 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1645 if (StartCST == 0) return UnknownValue; // Must be a constant.
1646
1647 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1648 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1649 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1650
1651 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1652 // the loop symbolically to determine when the condition gets a value of
1653 // "ExitWhen".
1654 unsigned IterationNum = 0;
1655 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1656 for (Constant *PHIVal = StartCST;
1657 IterationNum != MaxIterations; ++IterationNum) {
1658 ConstantBool *CondVal =
1659 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1660 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
Chris Lattner3221ad02004-04-17 22:58:41 +00001661
Chris Lattner7980fb92004-04-17 18:36:24 +00001662 if (CondVal->getValue() == ExitWhen) {
Chris Lattner3221ad02004-04-17 22:58:41 +00001663 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00001664 ++NumBruteForceTripCountsComputed;
1665 return SCEVConstant::get(ConstantUInt::get(Type::UIntTy, IterationNum));
1666 }
1667
Chris Lattner3221ad02004-04-17 22:58:41 +00001668 // Compute the value of the PHI node for the next iteration.
1669 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1670 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00001671 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00001672 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00001673 }
1674
1675 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00001676 return UnknownValue;
1677}
1678
1679/// getSCEVAtScope - Compute the value of the specified expression within the
1680/// indicated loop (which may be null to indicate in no loop). If the
1681/// expression cannot be evaluated, return UnknownValue.
1682SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1683 // FIXME: this should be turned into a virtual method on SCEV!
1684
Chris Lattner3221ad02004-04-17 22:58:41 +00001685 if (isa<SCEVConstant>(V)) return V;
1686
1687 // If this instruction is evolves from a constant-evolving PHI, compute the
1688 // exit value from the loop without using SCEVs.
1689 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1690 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1691 const Loop *LI = this->LI[I->getParent()];
1692 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1693 if (PHINode *PN = dyn_cast<PHINode>(I))
1694 if (PN->getParent() == LI->getHeader()) {
1695 // Okay, there is no closed form solution for the PHI node. Check
1696 // to see if the loop that contains it has a known iteration count.
1697 // If so, we may be able to force computation of the exit value.
1698 SCEVHandle IterationCount = getIterationCount(LI);
1699 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1700 // Okay, we know how many times the containing loop executes. If
1701 // this is a constant evolving PHI node, get the final value at
1702 // the specified iteration number.
1703 Constant *RV = getConstantEvolutionLoopExitValue(PN,
1704 ICC->getValue()->getRawValue(),
1705 LI);
1706 if (RV) return SCEVUnknown::get(RV);
1707 }
1708 }
1709
1710 // Okay, this is a some expression that we cannot symbolically evaluate
1711 // into a SCEV. Check to see if it's possible to symbolically evaluate
1712 // the arguments into constants, and if see, try to constant propagate the
1713 // result. This is particularly useful for computing loop exit values.
1714 if (CanConstantFold(I)) {
1715 std::vector<Constant*> Operands;
1716 Operands.reserve(I->getNumOperands());
1717 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1718 Value *Op = I->getOperand(i);
1719 if (Constant *C = dyn_cast<Constant>(Op)) {
1720 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00001721 } else {
1722 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
1723 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
1724 Operands.push_back(ConstantExpr::getCast(SC->getValue(),
1725 Op->getType()));
1726 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
1727 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
1728 Operands.push_back(ConstantExpr::getCast(C, Op->getType()));
1729 else
1730 return V;
1731 } else {
1732 return V;
1733 }
1734 }
1735 }
1736 return SCEVUnknown::get(ConstantFold(I, Operands));
1737 }
1738 }
1739
1740 // This is some other type of SCEVUnknown, just return it.
1741 return V;
1742 }
1743
Chris Lattner53e677a2004-04-02 20:23:17 +00001744 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1745 // Avoid performing the look-up in the common case where the specified
1746 // expression has no loop-variant portions.
1747 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1748 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1749 if (OpAtScope != Comm->getOperand(i)) {
1750 if (OpAtScope == UnknownValue) return UnknownValue;
1751 // Okay, at least one of these operands is loop variant but might be
1752 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00001753 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00001754 NewOps.push_back(OpAtScope);
1755
1756 for (++i; i != e; ++i) {
1757 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1758 if (OpAtScope == UnknownValue) return UnknownValue;
1759 NewOps.push_back(OpAtScope);
1760 }
1761 if (isa<SCEVAddExpr>(Comm))
1762 return SCEVAddExpr::get(NewOps);
1763 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1764 return SCEVMulExpr::get(NewOps);
1765 }
1766 }
1767 // If we got here, all operands are loop invariant.
1768 return Comm;
1769 }
1770
1771 if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(V)) {
1772 SCEVHandle LHS = getSCEVAtScope(UDiv->getLHS(), L);
1773 if (LHS == UnknownValue) return LHS;
1774 SCEVHandle RHS = getSCEVAtScope(UDiv->getRHS(), L);
1775 if (RHS == UnknownValue) return RHS;
1776 if (LHS == UDiv->getLHS() && RHS == UDiv->getRHS())
1777 return UDiv; // must be loop invariant
1778 return SCEVUDivExpr::get(LHS, RHS);
1779 }
1780
1781 // If this is a loop recurrence for a loop that does not contain L, then we
1782 // are dealing with the final value computed by the loop.
1783 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
1784 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
1785 // To evaluate this recurrence, we need to know how many times the AddRec
1786 // loop iterates. Compute this now.
1787 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
1788 if (IterationCount == UnknownValue) return UnknownValue;
1789 IterationCount = getTruncateOrZeroExtend(IterationCount,
1790 AddRec->getType());
1791
1792 // If the value is affine, simplify the expression evaluation to just
1793 // Start + Step*IterationCount.
1794 if (AddRec->isAffine())
1795 return SCEVAddExpr::get(AddRec->getStart(),
1796 SCEVMulExpr::get(IterationCount,
1797 AddRec->getOperand(1)));
1798
1799 // Otherwise, evaluate it the hard way.
1800 return AddRec->evaluateAtIteration(IterationCount);
1801 }
1802 return UnknownValue;
1803 }
1804
1805 //assert(0 && "Unknown SCEV type!");
1806 return UnknownValue;
1807}
1808
1809
1810/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
1811/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
1812/// might be the same) or two SCEVCouldNotCompute objects.
1813///
1814static std::pair<SCEVHandle,SCEVHandle>
1815SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
1816 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
1817 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
1818 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
1819 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
1820
1821 // We currently can only solve this if the coefficients are constants.
1822 if (!L || !M || !N) {
1823 SCEV *CNC = new SCEVCouldNotCompute();
1824 return std::make_pair(CNC, CNC);
1825 }
1826
1827 Constant *Two = ConstantInt::get(L->getValue()->getType(), 2);
1828
1829 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
1830 Constant *C = L->getValue();
1831 // The B coefficient is M-N/2
1832 Constant *B = ConstantExpr::getSub(M->getValue(),
1833 ConstantExpr::getDiv(N->getValue(),
1834 Two));
1835 // The A coefficient is N/2
1836 Constant *A = ConstantExpr::getDiv(N->getValue(), Two);
1837
1838 // Compute the B^2-4ac term.
1839 Constant *SqrtTerm =
1840 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
1841 ConstantExpr::getMul(A, C));
1842 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
1843
1844 // Compute floor(sqrt(B^2-4ac))
1845 ConstantUInt *SqrtVal =
1846 cast<ConstantUInt>(ConstantExpr::getCast(SqrtTerm,
1847 SqrtTerm->getType()->getUnsignedVersion()));
1848 uint64_t SqrtValV = SqrtVal->getValue();
Chris Lattnerea9e0052004-04-05 19:05:15 +00001849 uint64_t SqrtValV2 = (uint64_t)sqrt(SqrtValV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001850 // The square root might not be precise for arbitrary 64-bit integer
1851 // values. Do some sanity checks to ensure it's correct.
1852 if (SqrtValV2*SqrtValV2 > SqrtValV ||
1853 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
1854 SCEV *CNC = new SCEVCouldNotCompute();
1855 return std::make_pair(CNC, CNC);
1856 }
1857
1858 SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2);
1859 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
1860
1861 Constant *NegB = ConstantExpr::getNeg(B);
1862 Constant *TwoA = ConstantExpr::getMul(A, Two);
1863
1864 // The divisions must be performed as signed divisions.
1865 const Type *SignedTy = NegB->getType()->getSignedVersion();
1866 NegB = ConstantExpr::getCast(NegB, SignedTy);
1867 TwoA = ConstantExpr::getCast(TwoA, SignedTy);
1868 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
1869
1870 Constant *Solution1 =
1871 ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
1872 Constant *Solution2 =
1873 ConstantExpr::getDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
1874 return std::make_pair(SCEVUnknown::get(Solution1),
1875 SCEVUnknown::get(Solution2));
1876}
1877
1878/// HowFarToZero - Return the number of times a backedge comparing the specified
1879/// value to zero will execute. If not computable, return UnknownValue
1880SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
1881 // If the value is a constant
1882 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
1883 // If the value is already zero, the branch will execute zero times.
1884 if (C->getValue()->isNullValue()) return C;
1885 return UnknownValue; // Otherwise it will loop infinitely.
1886 }
1887
1888 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
1889 if (!AddRec || AddRec->getLoop() != L)
1890 return UnknownValue;
1891
1892 if (AddRec->isAffine()) {
1893 // If this is an affine expression the execution count of this branch is
1894 // equal to:
1895 //
1896 // (0 - Start/Step) iff Start % Step == 0
1897 //
1898 // Get the initial value for the loop.
1899 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
1900 SCEVHandle Step = AddRec->getOperand(1);
1901
1902 Step = getSCEVAtScope(Step, L->getParentLoop());
1903
1904 // Figure out if Start % Step == 0.
1905 // FIXME: We should add DivExpr and RemExpr operations to our AST.
1906 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
1907 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
1908 return getNegativeSCEV(Start); // 0 - Start/1 == -Start
1909 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
1910 return Start; // 0 - Start/-1 == Start
1911
1912 // Check to see if Start is divisible by SC with no remainder.
1913 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
1914 ConstantInt *StartCC = StartC->getValue();
1915 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
1916 Constant *Rem = ConstantExpr::getRem(StartNegC, StepC->getValue());
1917 if (Rem->isNullValue()) {
1918 Constant *Result =ConstantExpr::getDiv(StartNegC,StepC->getValue());
1919 return SCEVUnknown::get(Result);
1920 }
1921 }
1922 }
1923 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
1924 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
1925 // the quadratic equation to solve it.
1926 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
1927 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
1928 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
1929 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001930#if 0
Chris Lattner53e677a2004-04-02 20:23:17 +00001931 std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1
1932 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001933#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001934 // Pick the smallest positive root value.
1935 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
1936 if (ConstantBool *CB =
1937 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
1938 R2->getValue()))) {
1939 if (CB != ConstantBool::True)
1940 std::swap(R1, R2); // R1 is the minimum root now.
1941
1942 // We can only use this value if the chrec ends up with an exact zero
1943 // value at this index. When solving for "X*X != 5", for example, we
1944 // should not accept a root of 2.
1945 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
1946 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
1947 if (EvalVal->getValue()->isNullValue())
1948 return R1; // We found a quadratic root!
1949 }
1950 }
1951 }
1952
1953 return UnknownValue;
1954}
1955
1956/// HowFarToNonZero - Return the number of times a backedge checking the
1957/// specified value for nonzero will execute. If not computable, return
1958/// UnknownValue
1959SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
1960 // Loops that look like: while (X == 0) are very strange indeed. We don't
1961 // handle them yet except for the trivial case. This could be expanded in the
1962 // future as needed.
1963
1964 // If the value is a constant, check to see if it is known to be non-zero
1965 // already. If so, the backedge will execute zero times.
1966 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
1967 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
1968 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
1969 if (NonZero == ConstantBool::True)
1970 return getSCEV(Zero);
1971 return UnknownValue; // Otherwise it will loop infinitely.
1972 }
1973
1974 // We could implement others, but I really doubt anyone writes loops like
1975 // this, and if they did, they would already be constant folded.
1976 return UnknownValue;
1977}
1978
1979static ConstantInt *
1980EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1981 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1982 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1983 assert(isa<SCEVConstant>(Val) &&
1984 "Evaluation of SCEV at constant didn't fold correctly?");
1985 return cast<SCEVConstant>(Val)->getValue();
1986}
1987
1988
1989/// getNumIterationsInRange - Return the number of iterations of this loop that
1990/// produce values in the specified constant range. Another way of looking at
1991/// this is that it returns the first iteration number where the value is not in
1992/// the condition, thus computing the exit count. If the iteration count can't
1993/// be computed, an instance of SCEVCouldNotCompute is returned.
1994SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
1995 if (Range.isFullSet()) // Infinite loop.
1996 return new SCEVCouldNotCompute();
1997
1998 // If the start is a non-zero constant, shift the range to simplify things.
1999 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2000 if (!SC->getValue()->isNullValue()) {
2001 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Chris Lattnerb06432c2004-04-23 21:29:03 +00002002 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002003 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2004 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2005 return ShiftedAddRec->getNumIterationsInRange(
2006 Range.subtract(SC->getValue()));
2007 // This is strange and shouldn't happen.
2008 return new SCEVCouldNotCompute();
2009 }
2010
2011 // The only time we can solve this is when we have all constant indices.
2012 // Otherwise, we cannot determine the overflow conditions.
2013 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2014 if (!isa<SCEVConstant>(getOperand(i)))
2015 return new SCEVCouldNotCompute();
2016
2017
2018 // Okay at this point we know that all elements of the chrec are constants and
2019 // that the start element is zero.
2020
2021 // First check to see if the range contains zero. If not, the first
2022 // iteration exits.
2023 ConstantInt *Zero = ConstantInt::get(getType(), 0);
2024 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
2025
2026 if (isAffine()) {
2027 // If this is an affine expression then we have this situation:
2028 // Solve {0,+,A} in Range === Ax in Range
2029
2030 // Since we know that zero is in the range, we know that the upper value of
2031 // the range must be the first possible exit value. Also note that we
2032 // already checked for a full range.
2033 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2034 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2035 ConstantInt *One = ConstantInt::get(getType(), 1);
2036
2037 // The exit value should be (Upper+A-1)/A.
2038 Constant *ExitValue = Upper;
2039 if (A != One) {
2040 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
2041 ExitValue = ConstantExpr::getDiv(ExitValue, A);
2042 }
2043 assert(isa<ConstantInt>(ExitValue) &&
2044 "Constant folding of integers not implemented?");
2045
2046 // Evaluate at the exit value. If we really did fall out of the valid
2047 // range, then we computed our trip count, otherwise wrap around or other
2048 // things must have happened.
2049 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2050 if (Range.contains(Val))
2051 return new SCEVCouldNotCompute(); // Something strange happened
2052
2053 // Ensure that the previous value is in the range. This is a sanity check.
2054 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2055 ConstantExpr::getSub(ExitValue, One))) &&
2056 "Linear scev computation is off in a bad way!");
2057 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2058 } else if (isQuadratic()) {
2059 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2060 // quadratic equation to solve it. To do this, we must frame our problem in
2061 // terms of figuring out when zero is crossed, instead of when
2062 // Range.getUpper() is crossed.
2063 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2064 NewOps[0] = getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
2065 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2066
2067 // Next, solve the constructed addrec
2068 std::pair<SCEVHandle,SCEVHandle> Roots =
2069 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2070 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2071 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2072 if (R1) {
2073 // Pick the smallest positive root value.
2074 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2075 if (ConstantBool *CB =
2076 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2077 R2->getValue()))) {
2078 if (CB != ConstantBool::True)
2079 std::swap(R1, R2); // R1 is the minimum root now.
2080
2081 // Make sure the root is not off by one. The returned iteration should
2082 // not be in the range, but the previous one should be. When solving
2083 // for "X*X < 5", for example, we should not return a root of 2.
2084 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2085 R1->getValue());
2086 if (Range.contains(R1Val)) {
2087 // The next iteration must be out of the range...
2088 Constant *NextVal =
2089 ConstantExpr::getAdd(R1->getValue(),
2090 ConstantInt::get(R1->getType(), 1));
2091
2092 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2093 if (!Range.contains(R1Val))
2094 return SCEVUnknown::get(NextVal);
2095 return new SCEVCouldNotCompute(); // Something strange happened
2096 }
2097
2098 // If R1 was not in the range, then it is a good return value. Make
2099 // sure that R1-1 WAS in the range though, just in case.
2100 Constant *NextVal =
2101 ConstantExpr::getSub(R1->getValue(),
2102 ConstantInt::get(R1->getType(), 1));
2103 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2104 if (Range.contains(R1Val))
2105 return R1;
2106 return new SCEVCouldNotCompute(); // Something strange happened
2107 }
2108 }
2109 }
2110
2111 // Fallback, if this is a general polynomial, figure out the progression
2112 // through brute force: evaluate until we find an iteration that fails the
2113 // test. This is likely to be slow, but getting an accurate trip count is
2114 // incredibly important, we will be able to simplify the exit test a lot, and
2115 // we are almost guaranteed to get a trip count in this case.
2116 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2117 ConstantInt *One = ConstantInt::get(getType(), 1);
2118 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2119 do {
2120 ++NumBruteForceEvaluations;
2121 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2122 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2123 return new SCEVCouldNotCompute();
2124
2125 // Check to see if we found the value!
2126 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2127 return SCEVConstant::get(TestVal);
2128
2129 // Increment to test the next index.
2130 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2131 } while (TestVal != EndVal);
2132
2133 return new SCEVCouldNotCompute();
2134}
2135
2136
2137
2138//===----------------------------------------------------------------------===//
2139// ScalarEvolution Class Implementation
2140//===----------------------------------------------------------------------===//
2141
2142bool ScalarEvolution::runOnFunction(Function &F) {
2143 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2144 return false;
2145}
2146
2147void ScalarEvolution::releaseMemory() {
2148 delete (ScalarEvolutionsImpl*)Impl;
2149 Impl = 0;
2150}
2151
2152void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2153 AU.setPreservesAll();
2154 AU.addRequiredID(LoopSimplifyID);
2155 AU.addRequiredTransitive<LoopInfo>();
2156}
2157
2158SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2159 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2160}
2161
2162SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2163 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2164}
2165
2166bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2167 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2168}
2169
2170SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2171 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2172}
2173
2174void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2175 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2176}
2177
Chris Lattner53e677a2004-04-02 20:23:17 +00002178static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2179 const Loop *L) {
2180 // Print all inner loops first
2181 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2182 PrintLoopInfo(OS, SE, *I);
2183
2184 std::cerr << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002185
2186 std::vector<BasicBlock*> ExitBlocks;
2187 L->getExitBlocks(ExitBlocks);
2188 if (ExitBlocks.size() != 1)
Chris Lattner53e677a2004-04-02 20:23:17 +00002189 std::cerr << "<multiple exits> ";
2190
2191 if (SE->hasLoopInvariantIterationCount(L)) {
2192 std::cerr << *SE->getIterationCount(L) << " iterations! ";
2193 } else {
2194 std::cerr << "Unpredictable iteration count. ";
2195 }
2196
2197 std::cerr << "\n";
2198}
2199
2200void ScalarEvolution::print(std::ostream &OS) const {
2201 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2202 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2203
2204 OS << "Classifying expressions for: " << F.getName() << "\n";
2205 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner6ffe5512004-04-27 15:13:33 +00002206 if (I->getType()->isInteger()) {
2207 OS << *I;
Chris Lattner53e677a2004-04-02 20:23:17 +00002208 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002209 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00002210 SV->print(OS);
2211 OS << "\t\t";
2212
Chris Lattner6ffe5512004-04-27 15:13:33 +00002213 if ((*I).getType()->isIntegral()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002214 ConstantRange Bounds = SV->getValueRange();
2215 if (!Bounds.isFullSet())
2216 OS << "Bounds: " << Bounds << " ";
2217 }
2218
Chris Lattner6ffe5512004-04-27 15:13:33 +00002219 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002220 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002221 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002222 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2223 OS << "<<Unknown>>";
2224 } else {
2225 OS << *ExitValue;
2226 }
2227 }
2228
2229
2230 OS << "\n";
2231 }
2232
2233 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2234 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2235 PrintLoopInfo(OS, this, *I);
2236}
2237