blob: 36fe4fb8fdeb890a35856aa116de407293960a16 [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
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.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000031//
Chris Lattner53e677a2004-04-02 20:23:17 +000032// 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 Lattner3b27d682006-12-19 22:30:33 +000062#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000063#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000064#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000066#include "llvm/GlobalVariable.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
John Criswella1156432005-10-27 15:54:34 +000068#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng5a6c1a82009-02-17 00:13:06 +000069#include "llvm/Analysis/Dominators.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000070#include "llvm/Analysis/LoopInfo.h"
71#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000072#include "llvm/Target/TargetData.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000073#include "llvm/Transforms/Scalar.h"
74#include "llvm/Support/CFG.h"
Chris Lattner95255282006-06-28 23:17:24 +000075#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000076#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000077#include "llvm/Support/ConstantRange.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000078#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000079#include "llvm/Support/InstIterator.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000080#include "llvm/Support/ManagedStatic.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000081#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000082#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000083#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000084#include "llvm/ADT/STLExtras.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000085#include <ostream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000086#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000087#include <cmath>
Chris Lattner53e677a2004-04-02 20:23:17 +000088using namespace llvm;
89
Chris Lattner3b27d682006-12-19 22:30:33 +000090STATISTIC(NumArrayLenItCounts,
91 "Number of trip counts computed with array length");
92STATISTIC(NumTripCountsComputed,
93 "Number of loops with predictable loop counts");
94STATISTIC(NumTripCountsNotComputed,
95 "Number of loops without predictable loop counts");
96STATISTIC(NumBruteForceTripCountsComputed,
97 "Number of loops with trip counts computed by force");
98
Dan Gohman844731a2008-05-13 00:00:25 +000099static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +0000100MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
101 cl::desc("Maximum number of iterations SCEV will "
102 "symbolically execute a constant derived loop"),
103 cl::init(100));
104
Dan Gohman844731a2008-05-13 00:00:25 +0000105static RegisterPass<ScalarEvolution>
106R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000107char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000108
109//===----------------------------------------------------------------------===//
110// SCEV class definitions
111//===----------------------------------------------------------------------===//
112
113//===----------------------------------------------------------------------===//
114// Implementation of the SCEV class.
115//
Chris Lattner53e677a2004-04-02 20:23:17 +0000116SCEV::~SCEV() {}
117void SCEV::dump() const {
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000118 print(errs());
119 errs() << '\n';
120}
121
122void SCEV::print(std::ostream &o) const {
123 raw_os_ostream OS(o);
124 print(OS);
Chris Lattner53e677a2004-04-02 20:23:17 +0000125}
126
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000127bool SCEV::isZero() const {
128 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
129 return SC->getValue()->isZero();
130 return false;
131}
132
Chris Lattner53e677a2004-04-02 20:23:17 +0000133
134SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
Dan Gohmanf8a8be82009-04-21 23:15:49 +0000135SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
Chris Lattner53e677a2004-04-02 20:23:17 +0000136
137bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
138 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000139 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000140}
141
142const Type *SCEVCouldNotCompute::getType() const {
143 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000144 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000145}
146
147bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
148 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
149 return false;
150}
151
Chris Lattner4dc534c2005-02-13 04:37:18 +0000152SCEVHandle SCEVCouldNotCompute::
153replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000154 const SCEVHandle &Conc,
155 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000156 return this;
157}
158
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000159void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000160 OS << "***COULDNOTCOMPUTE***";
161}
162
163bool SCEVCouldNotCompute::classof(const SCEV *S) {
164 return S->getSCEVType() == scCouldNotCompute;
165}
166
167
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000168// SCEVConstants - Only allow the creation of one SCEVConstant for any
169// particular value. Don't use a SCEVHandle here, or else the object will
170// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000171static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000172
Chris Lattner53e677a2004-04-02 20:23:17 +0000173
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000174SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000175 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000176}
Chris Lattner53e677a2004-04-02 20:23:17 +0000177
Dan Gohman246b2562007-10-22 18:31:58 +0000178SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Chris Lattnerb3364092006-10-04 21:49:37 +0000179 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000180 if (R == 0) R = new SCEVConstant(V);
181 return R;
182}
Chris Lattner53e677a2004-04-02 20:23:17 +0000183
Dan Gohman246b2562007-10-22 18:31:58 +0000184SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
185 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000186}
187
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000188const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000189
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000190void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000191 WriteAsOperand(OS, V, false);
192}
Chris Lattner53e677a2004-04-02 20:23:17 +0000193
Dan Gohman84923602009-04-21 01:25:57 +0000194SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
195 const SCEVHandle &op, const Type *ty)
196 : SCEV(SCEVTy), Op(op), Ty(ty) {}
197
198SCEVCastExpr::~SCEVCastExpr() {}
199
200bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
201 return Op->dominates(BB, DT);
202}
203
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000204// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
205// particular input. Don't use a SCEVHandle here, or else the object will
206// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000207static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
208 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000209
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000210SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman84923602009-04-21 01:25:57 +0000211 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000212 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
213 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000214 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000215}
Chris Lattner53e677a2004-04-02 20:23:17 +0000216
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000217SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000218 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219}
Chris Lattner53e677a2004-04-02 20:23:17 +0000220
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000221void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000222 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000223}
224
225// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
226// particular input. Don't use a SCEVHandle here, or else the object will never
227// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000228static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
229 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000230
231SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman84923602009-04-21 01:25:57 +0000232 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000233 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
234 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000235 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000236}
237
238SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000239 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000240}
241
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000242void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000243 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000244}
245
Dan Gohmand19534a2007-06-15 14:38:12 +0000246// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
247// particular input. Don't use a SCEVHandle here, or else the object will never
248// be deleted!
249static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
250 SCEVSignExtendExpr*> > SCEVSignExtends;
251
252SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman84923602009-04-21 01:25:57 +0000253 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000254 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
255 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000256 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000257}
258
259SCEVSignExtendExpr::~SCEVSignExtendExpr() {
260 SCEVSignExtends->erase(std::make_pair(Op, Ty));
261}
262
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000263void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000264 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000265}
266
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000267// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
268// particular input. Don't use a SCEVHandle here, or else the object will never
269// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000270static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
271 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000272
273SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000274 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
275 std::vector<SCEV*>(Operands.begin(),
276 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000277}
278
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000279void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000280 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
281 const char *OpStr = getOperationStr();
282 OS << "(" << *Operands[0];
283 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
284 OS << OpStr << *Operands[i];
285 OS << ")";
286}
287
Chris Lattner4dc534c2005-02-13 04:37:18 +0000288SCEVHandle SCEVCommutativeExpr::
289replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000290 const SCEVHandle &Conc,
291 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000292 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000293 SCEVHandle H =
294 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000295 if (H != getOperand(i)) {
296 std::vector<SCEVHandle> NewOps;
297 NewOps.reserve(getNumOperands());
298 for (unsigned j = 0; j != i; ++j)
299 NewOps.push_back(getOperand(j));
300 NewOps.push_back(H);
301 for (++i; i != e; ++i)
302 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000303 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000304
305 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000306 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000307 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000308 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000309 else if (isa<SCEVSMaxExpr>(this))
310 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000311 else if (isa<SCEVUMaxExpr>(this))
312 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000313 else
314 assert(0 && "Unknown commutative expr!");
315 }
316 }
317 return this;
318}
319
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000320bool SCEVCommutativeExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
321 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
322 if (!getOperand(i)->dominates(BB, DT))
323 return false;
324 }
325 return true;
326}
327
Chris Lattner4dc534c2005-02-13 04:37:18 +0000328
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000329// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000330// input. Don't use a SCEVHandle here, or else the object will never be
331// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000332static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000333 SCEVUDivExpr*> > SCEVUDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000334
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000335SCEVUDivExpr::~SCEVUDivExpr() {
336 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000337}
338
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000339bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
340 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
341}
342
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000343void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000344 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000345}
346
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000347const Type *SCEVUDivExpr::getType() const {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000348 return LHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000349}
350
351// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
352// particular input. Don't use a SCEVHandle here, or else the object will never
353// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000354static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
355 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000356
357SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000358 SCEVAddRecExprs->erase(std::make_pair(L,
359 std::vector<SCEV*>(Operands.begin(),
360 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000361}
362
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000363bool SCEVAddRecExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
364 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
365 if (!getOperand(i)->dominates(BB, DT))
366 return false;
367 }
368 return true;
369}
370
371
Chris Lattner4dc534c2005-02-13 04:37:18 +0000372SCEVHandle SCEVAddRecExpr::
373replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000374 const SCEVHandle &Conc,
375 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000376 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000377 SCEVHandle H =
378 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000379 if (H != getOperand(i)) {
380 std::vector<SCEVHandle> NewOps;
381 NewOps.reserve(getNumOperands());
382 for (unsigned j = 0; j != i; ++j)
383 NewOps.push_back(getOperand(j));
384 NewOps.push_back(H);
385 for (++i; i != e; ++i)
386 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000387 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000388
Dan Gohman246b2562007-10-22 18:31:58 +0000389 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000390 }
391 }
392 return this;
393}
394
395
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000396bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
397 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000398 // contain L and if the start is invariant.
399 return !QueryLoop->contains(L->getHeader()) &&
400 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000401}
402
403
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000404void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000405 OS << "{" << *Operands[0];
406 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
407 OS << ",+," << *Operands[i];
408 OS << "}<" << L->getHeader()->getName() + ">";
409}
Chris Lattner53e677a2004-04-02 20:23:17 +0000410
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000411// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
412// value. Don't use a SCEVHandle here, or else the object will never be
413// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000414static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000415
Chris Lattnerb3364092006-10-04 21:49:37 +0000416SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000417
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000418bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
419 // All non-instruction values are loop invariant. All instructions are loop
420 // invariant if they are not contained in the specified loop.
421 if (Instruction *I = dyn_cast<Instruction>(V))
422 return !L->contains(I->getParent());
423 return true;
424}
Chris Lattner53e677a2004-04-02 20:23:17 +0000425
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000426bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
427 if (Instruction *I = dyn_cast<Instruction>(getValue()))
428 return DT->dominates(I->getParent(), BB);
429 return true;
430}
431
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000432const Type *SCEVUnknown::getType() const {
433 return V->getType();
434}
Chris Lattner53e677a2004-04-02 20:23:17 +0000435
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000436void SCEVUnknown::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000437 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000438}
439
Chris Lattner8d741b82004-06-20 06:23:15 +0000440//===----------------------------------------------------------------------===//
441// SCEV Utilities
442//===----------------------------------------------------------------------===//
443
444namespace {
445 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
446 /// than the complexity of the RHS. This comparator is used to canonicalize
447 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000448 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000449 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Chris Lattner8d741b82004-06-20 06:23:15 +0000450 return LHS->getSCEVType() < RHS->getSCEVType();
451 }
452 };
453}
454
455/// GroupByComplexity - Given a list of SCEV objects, order them by their
456/// complexity, and group objects of the same complexity together by value.
457/// When this routine is finished, we know that any duplicates in the vector are
458/// consecutive and that complexity is monotonically increasing.
459///
460/// Note that we go take special precautions to ensure that we get determinstic
461/// results from this routine. In other words, we don't want the results of
462/// this to depend on where the addresses of various SCEV objects happened to
463/// land in memory.
464///
465static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
466 if (Ops.size() < 2) return; // Noop
467 if (Ops.size() == 2) {
468 // This is the common case, which also happens to be trivially simple.
469 // Special case it.
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000470 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000471 std::swap(Ops[0], Ops[1]);
472 return;
473 }
474
475 // Do the rough sort by complexity.
476 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
477
478 // Now that we are sorted by complexity, group elements of the same
479 // complexity. Note that this is, at worst, N^2, but the vector is likely to
480 // be extremely short in practice. Note that we take this approach because we
481 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000482 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000483 SCEV *S = Ops[i];
484 unsigned Complexity = S->getSCEVType();
485
486 // If there are any objects of the same complexity and same value as this
487 // one, group them.
488 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
489 if (Ops[j] == S) { // Found a duplicate.
490 // Move it to immediately after i'th element.
491 std::swap(Ops[i+1], Ops[j]);
492 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000493 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000494 }
495 }
496 }
497}
498
Chris Lattner53e677a2004-04-02 20:23:17 +0000499
Chris Lattner53e677a2004-04-02 20:23:17 +0000500
501//===----------------------------------------------------------------------===//
502// Simple SCEV method implementations
503//===----------------------------------------------------------------------===//
504
Eli Friedmanb42a6262008-08-04 23:49:06 +0000505/// BinomialCoefficient - Compute BC(It, K). The result has width W.
506// Assume, K > 0.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000507static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedmanb42a6262008-08-04 23:49:06 +0000508 ScalarEvolution &SE,
Dan Gohman2d1be872009-04-16 03:18:22 +0000509 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000510 // Handle the simplest case efficiently.
511 if (K == 1)
512 return SE.getTruncateOrZeroExtend(It, ResultTy);
513
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000514 // We are using the following formula for BC(It, K):
515 //
516 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
517 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000518 // Suppose, W is the bitwidth of the return value. We must be prepared for
519 // overflow. Hence, we must assure that the result of our computation is
520 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
521 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000522 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000523 // However, this code doesn't use exactly that formula; the formula it uses
524 // is something like the following, where T is the number of factors of 2 in
525 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
526 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000527 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000528 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000529 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000530 // This formula is trivially equivalent to the previous formula. However,
531 // this formula can be implemented much more efficiently. The trick is that
532 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
533 // arithmetic. To do exact division in modular arithmetic, all we have
534 // to do is multiply by the inverse. Therefore, this step can be done at
535 // width W.
536 //
537 // The next issue is how to safely do the division by 2^T. The way this
538 // is done is by doing the multiplication step at a width of at least W + T
539 // bits. This way, the bottom W+T bits of the product are accurate. Then,
540 // when we perform the division by 2^T (which is equivalent to a right shift
541 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
542 // truncated out after the division by 2^T.
543 //
544 // In comparison to just directly using the first formula, this technique
545 // is much more efficient; using the first formula requires W * K bits,
546 // but this formula less than W + K bits. Also, the first formula requires
547 // a division step, whereas this formula only requires multiplies and shifts.
548 //
549 // It doesn't matter whether the subtraction step is done in the calculation
550 // width or the input iteration count's width; if the subtraction overflows,
551 // the result must be zero anyway. We prefer here to do it in the width of
552 // the induction variable because it helps a lot for certain cases; CodeGen
553 // isn't smart enough to ignore the overflow, which leads to much less
554 // efficient code if the width of the subtraction is wider than the native
555 // register width.
556 //
557 // (It's possible to not widen at all by pulling out factors of 2 before
558 // the multiplication; for example, K=2 can be calculated as
559 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
560 // extra arithmetic, so it's not an obvious win, and it gets
561 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000562
Eli Friedmanb42a6262008-08-04 23:49:06 +0000563 // Protection from insane SCEVs; this bound is conservative,
564 // but it probably doesn't matter.
565 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000566 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000567
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000568 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000569
Eli Friedmanb42a6262008-08-04 23:49:06 +0000570 // Calculate K! / 2^T and T; we divide out the factors of two before
571 // multiplying for calculating K! / 2^T to avoid overflow.
572 // Other overflow doesn't matter because we only care about the bottom
573 // W bits of the result.
574 APInt OddFactorial(W, 1);
575 unsigned T = 1;
576 for (unsigned i = 3; i <= K; ++i) {
577 APInt Mult(W, i);
578 unsigned TwoFactors = Mult.countTrailingZeros();
579 T += TwoFactors;
580 Mult = Mult.lshr(TwoFactors);
581 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000582 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000583
Eli Friedmanb42a6262008-08-04 23:49:06 +0000584 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000585 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000586
587 // Calcuate 2^T, at width T+W.
588 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
589
590 // Calculate the multiplicative inverse of K! / 2^T;
591 // this multiplication factor will perform the exact division by
592 // K! / 2^T.
593 APInt Mod = APInt::getSignedMinValue(W+1);
594 APInt MultiplyFactor = OddFactorial.zext(W+1);
595 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
596 MultiplyFactor = MultiplyFactor.trunc(W);
597
598 // Calculate the product, at width T+W
599 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
600 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
601 for (unsigned i = 1; i != K; ++i) {
602 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
603 Dividend = SE.getMulExpr(Dividend,
604 SE.getTruncateOrZeroExtend(S, CalculationTy));
605 }
606
607 // Divide by 2^T
608 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
609
610 // Truncate the result, and divide by K! / 2^T.
611
612 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
613 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000614}
615
Chris Lattner53e677a2004-04-02 20:23:17 +0000616/// evaluateAtIteration - Return the value of this chain of recurrences at
617/// the specified iteration number. We can evaluate this recurrence by
618/// multiplying each element in the chain by the binomial coefficient
619/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
620///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000621/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000622///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000623/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000624///
Dan Gohman246b2562007-10-22 18:31:58 +0000625SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
626 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000627 SCEVHandle Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000628 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000629 // The computation is correct in the face of overflow provided that the
630 // multiplication is performed _after_ the evaluation of the binomial
631 // coefficient.
Dan Gohman2d1be872009-04-16 03:18:22 +0000632 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000633 if (isa<SCEVCouldNotCompute>(Coeff))
634 return Coeff;
635
636 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000637 }
638 return Result;
639}
640
Chris Lattner53e677a2004-04-02 20:23:17 +0000641//===----------------------------------------------------------------------===//
642// SCEV Expression folder implementations
643//===----------------------------------------------------------------------===//
644
Dan Gohman99243b32009-05-01 16:44:56 +0000645SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
646 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000647 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000648 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000649 assert(isSCEVable(Ty) &&
650 "This is not a conversion to a SCEVable type!");
651 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000652
Dan Gohman622ed672009-05-04 22:02:23 +0000653 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000654 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000655 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000656
Dan Gohman20900ca2009-04-22 16:20:48 +0000657 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000658 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000659 return getTruncateExpr(ST->getOperand(), Ty);
660
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000661 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000662 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000663 return getTruncateOrSignExtend(SS->getOperand(), Ty);
664
665 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000666 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000667 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
668
Chris Lattner53e677a2004-04-02 20:23:17 +0000669 // If the input value is a chrec scev made out of constants, truncate
670 // all of the constants.
Dan Gohman622ed672009-05-04 22:02:23 +0000671 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000672 std::vector<SCEVHandle> Operands;
673 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
674 // FIXME: This should allow truncation of other expression types!
675 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman246b2562007-10-22 18:31:58 +0000676 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000677 else
678 break;
679 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman246b2562007-10-22 18:31:58 +0000680 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000681 }
682
Chris Lattnerb3364092006-10-04 21:49:37 +0000683 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000684 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
685 return Result;
686}
687
Dan Gohman8170a682009-04-16 19:25:55 +0000688SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
689 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000690 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000691 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000692 assert(isSCEVable(Ty) &&
693 "This is not a conversion to a SCEVable type!");
694 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000695
Dan Gohman622ed672009-05-04 22:02:23 +0000696 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000697 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000698 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
699 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
700 return getUnknown(C);
701 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000702
Dan Gohman20900ca2009-04-22 16:20:48 +0000703 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000704 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000705 return getZeroExtendExpr(SZ->getOperand(), Ty);
706
Dan Gohman01ecca22009-04-27 20:16:15 +0000707 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000708 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000709 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000710 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000711 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000712 if (AR->isAffine()) {
713 // Check whether the backedge-taken count is SCEVCouldNotCompute.
714 // Note that this serves two purposes: It filters out loops that are
715 // simply not analyzable, and it covers the case where this code is
716 // being called from within backedge-taken count analysis, such that
717 // attempting to ask for the backedge-taken count would likely result
718 // in infinite recursion. In the later case, the analysis code will
719 // cope with a conservative value, and it will take care to purge
720 // that value once it has finished.
Dan Gohmana1af7572009-04-30 20:47:05 +0000721 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
722 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000723 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000724 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000725 SCEVHandle Start = AR->getStart();
726 SCEVHandle Step = AR->getStepRecurrence(*this);
727
728 // Check whether the backedge-taken count can be losslessly casted to
729 // the addrec's type. The count is always unsigned.
Dan Gohmana1af7572009-04-30 20:47:05 +0000730 SCEVHandle CastedMaxBECount =
731 getTruncateOrZeroExtend(MaxBECount, Start->getType());
732 if (MaxBECount ==
733 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000734 const Type *WideTy =
735 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000736 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000737 SCEVHandle ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000738 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000739 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000740 SCEVHandle Add = getAddExpr(Start, ZMul);
741 if (getZeroExtendExpr(Add, WideTy) ==
742 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmana1af7572009-04-30 20:47:05 +0000743 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohmanac70cea2009-04-29 22:28:28 +0000744 getZeroExtendExpr(Step, WideTy))))
745 // Return the expression with the addrec on the outside.
746 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
747 getZeroExtendExpr(Step, Ty),
748 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000749
750 // Similar to above, only this time treat the step value as signed.
751 // This covers loops that count down.
752 SCEVHandle SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000753 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000754 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000755 Add = getAddExpr(Start, SMul);
756 if (getZeroExtendExpr(Add, WideTy) ==
757 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmana1af7572009-04-30 20:47:05 +0000758 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohmanac70cea2009-04-29 22:28:28 +0000759 getSignExtendExpr(Step, WideTy))))
760 // Return the expression with the addrec on the outside.
761 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
762 getSignExtendExpr(Step, Ty),
763 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000764 }
765 }
766 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000767
Chris Lattnerb3364092006-10-04 21:49:37 +0000768 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000769 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
770 return Result;
771}
772
Dan Gohman01ecca22009-04-27 20:16:15 +0000773SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
774 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000775 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000776 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000777 assert(isSCEVable(Ty) &&
778 "This is not a conversion to a SCEVable type!");
779 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000780
Dan Gohman622ed672009-05-04 22:02:23 +0000781 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000782 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000783 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
784 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
785 return getUnknown(C);
786 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000787
Dan Gohman20900ca2009-04-22 16:20:48 +0000788 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000789 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000790 return getSignExtendExpr(SS->getOperand(), Ty);
791
Dan Gohman01ecca22009-04-27 20:16:15 +0000792 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000793 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000794 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000795 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000796 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000797 if (AR->isAffine()) {
798 // Check whether the backedge-taken count is SCEVCouldNotCompute.
799 // Note that this serves two purposes: It filters out loops that are
800 // simply not analyzable, and it covers the case where this code is
801 // being called from within backedge-taken count analysis, such that
802 // attempting to ask for the backedge-taken count would likely result
803 // in infinite recursion. In the later case, the analysis code will
804 // cope with a conservative value, and it will take care to purge
805 // that value once it has finished.
Dan Gohmana1af7572009-04-30 20:47:05 +0000806 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
807 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000808 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000809 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000810 SCEVHandle Start = AR->getStart();
811 SCEVHandle Step = AR->getStepRecurrence(*this);
812
813 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000814 // the addrec's type. The count is always unsigned.
Dan Gohmana1af7572009-04-30 20:47:05 +0000815 SCEVHandle CastedMaxBECount =
816 getTruncateOrZeroExtend(MaxBECount, Start->getType());
817 if (MaxBECount ==
818 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000819 const Type *WideTy =
820 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000821 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000822 SCEVHandle SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000823 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000824 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000825 SCEVHandle Add = getAddExpr(Start, SMul);
826 if (getSignExtendExpr(Add, WideTy) ==
827 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohmana1af7572009-04-30 20:47:05 +0000828 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohmanac70cea2009-04-29 22:28:28 +0000829 getSignExtendExpr(Step, WideTy))))
830 // Return the expression with the addrec on the outside.
831 return getAddRecExpr(getSignExtendExpr(Start, Ty),
832 getSignExtendExpr(Step, Ty),
833 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000834 }
835 }
836 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000837
838 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
839 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
840 return Result;
841}
842
Chris Lattner53e677a2004-04-02 20:23:17 +0000843// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman246b2562007-10-22 18:31:58 +0000844SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000845 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000846 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000847
848 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000849 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000850
851 // If there are any constants, fold them together.
852 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +0000853 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000854 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000855 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +0000856 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000857 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000858 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
859 RHSC->getValue()->getValue());
860 Ops[0] = getConstant(Fold);
861 Ops.erase(Ops.begin()+1); // Erase the folded element
862 if (Ops.size() == 1) return Ops[0];
863 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000864 }
865
866 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +0000867 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000868 Ops.erase(Ops.begin());
869 --Idx;
870 }
871 }
872
Chris Lattner627018b2004-04-07 16:16:11 +0000873 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000874
Chris Lattner53e677a2004-04-02 20:23:17 +0000875 // Okay, check to see if the same value occurs in the operand list twice. If
876 // so, merge them together into an multiply expression. Since we sorted the
877 // list, these values are required to be adjacent.
878 const Type *Ty = Ops[0]->getType();
879 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
880 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
881 // Found a match, merge the two values into a multiply, and add any
882 // remaining values to the result.
Dan Gohman246b2562007-10-22 18:31:58 +0000883 SCEVHandle Two = getIntegerSCEV(2, Ty);
884 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +0000885 if (Ops.size() == 2)
886 return Mul;
887 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
888 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +0000889 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000890 }
891
Dan Gohmanf50cd742007-06-18 19:30:09 +0000892 // Now we know the first non-constant operand. Skip past any cast SCEVs.
893 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
894 ++Idx;
895
896 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +0000897 if (Idx < Ops.size()) {
898 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +0000899 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000900 // If we have an add, expand the add operands onto the end of the operands
901 // list.
902 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
903 Ops.erase(Ops.begin()+Idx);
904 DeletedAdd = true;
905 }
906
907 // If we deleted at least one add, we added operands to the end of the list,
908 // and they are not necessarily sorted. Recurse to resort and resimplify
909 // any operands we just aquired.
910 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +0000911 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000912 }
913
914 // Skip over the add expression until we get to a multiply.
915 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
916 ++Idx;
917
918 // If we are adding something to a multiply expression, make sure the
919 // something is not already an operand of the multiply. If so, merge it into
920 // the multiply.
921 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
922 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
923 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
924 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
925 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000926 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000927 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
928 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
929 if (Mul->getNumOperands() != 2) {
930 // If the multiply has more than two operands, we must get the
931 // Y*Z term.
932 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
933 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000934 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000935 }
Dan Gohman246b2562007-10-22 18:31:58 +0000936 SCEVHandle One = getIntegerSCEV(1, Ty);
937 SCEVHandle AddOne = getAddExpr(InnerMul, One);
938 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000939 if (Ops.size() == 2) return OuterMul;
940 if (AddOp < Idx) {
941 Ops.erase(Ops.begin()+AddOp);
942 Ops.erase(Ops.begin()+Idx-1);
943 } else {
944 Ops.erase(Ops.begin()+Idx);
945 Ops.erase(Ops.begin()+AddOp-1);
946 }
947 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000948 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000949 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000950
Chris Lattner53e677a2004-04-02 20:23:17 +0000951 // Check this multiply against other multiplies being added together.
952 for (unsigned OtherMulIdx = Idx+1;
953 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
954 ++OtherMulIdx) {
955 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
956 // If MulOp occurs in OtherMul, we can fold the two multiplies
957 // together.
958 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
959 OMulOp != e; ++OMulOp)
960 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
961 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
962 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
963 if (Mul->getNumOperands() != 2) {
964 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
965 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000966 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000967 }
968 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
969 if (OtherMul->getNumOperands() != 2) {
970 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
971 OtherMul->op_end());
972 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000973 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000974 }
Dan Gohman246b2562007-10-22 18:31:58 +0000975 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
976 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +0000977 if (Ops.size() == 2) return OuterMul;
978 Ops.erase(Ops.begin()+Idx);
979 Ops.erase(Ops.begin()+OtherMulIdx-1);
980 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000981 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000982 }
983 }
984 }
985 }
986
987 // If there are any add recurrences in the operands list, see if any other
988 // added values are loop invariant. If so, we can fold them into the
989 // recurrence.
990 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
991 ++Idx;
992
993 // Scan over all recurrences, trying to fold loop invariants into them.
994 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
995 // Scan all of the other operands to this add and add them to the vector if
996 // they are loop invariant w.r.t. the recurrence.
997 std::vector<SCEVHandle> LIOps;
998 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
999 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1000 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1001 LIOps.push_back(Ops[i]);
1002 Ops.erase(Ops.begin()+i);
1003 --i; --e;
1004 }
1005
1006 // If we found some loop invariants, fold them into the recurrence.
1007 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001008 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001009 LIOps.push_back(AddRec->getStart());
1010
1011 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001012 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001013
Dan Gohman246b2562007-10-22 18:31:58 +00001014 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001015 // If all of the other operands were loop invariant, we are done.
1016 if (Ops.size() == 1) return NewRec;
1017
1018 // Otherwise, add the folded AddRec by the non-liv parts.
1019 for (unsigned i = 0;; ++i)
1020 if (Ops[i] == AddRec) {
1021 Ops[i] = NewRec;
1022 break;
1023 }
Dan Gohman246b2562007-10-22 18:31:58 +00001024 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001025 }
1026
1027 // Okay, if there weren't any loop invariants to be folded, check to see if
1028 // there are multiple AddRec's with the same loop induction variable being
1029 // added together. If so, we can fold them.
1030 for (unsigned OtherIdx = Idx+1;
1031 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1032 if (OtherIdx != Idx) {
1033 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1034 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1035 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1036 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1037 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1038 if (i >= NewOps.size()) {
1039 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1040 OtherAddRec->op_end());
1041 break;
1042 }
Dan Gohman246b2562007-10-22 18:31:58 +00001043 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001044 }
Dan Gohman246b2562007-10-22 18:31:58 +00001045 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001046
1047 if (Ops.size() == 2) return NewAddRec;
1048
1049 Ops.erase(Ops.begin()+Idx);
1050 Ops.erase(Ops.begin()+OtherIdx-1);
1051 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001052 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001053 }
1054 }
1055
1056 // Otherwise couldn't fold anything into this recurrence. Move onto the
1057 // next one.
1058 }
1059
1060 // Okay, it looks like we really DO need an add expr. Check to see if we
1061 // already have one, otherwise create a new one.
1062 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001063 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1064 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +00001065 if (Result == 0) Result = new SCEVAddExpr(Ops);
1066 return Result;
1067}
1068
1069
Dan Gohman246b2562007-10-22 18:31:58 +00001070SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001071 assert(!Ops.empty() && "Cannot get empty mul!");
1072
1073 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +00001074 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001075
1076 // If there are any constants, fold them together.
1077 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001078 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001079
1080 // C1*(C2+V) -> C1*C2 + C1*V
1081 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001082 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001083 if (Add->getNumOperands() == 2 &&
1084 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001085 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1086 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001087
1088
1089 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001090 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001091 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001092 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1093 RHSC->getValue()->getValue());
1094 Ops[0] = getConstant(Fold);
1095 Ops.erase(Ops.begin()+1); // Erase the folded element
1096 if (Ops.size() == 1) return Ops[0];
1097 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001098 }
1099
1100 // If we are left with a constant one being multiplied, strip it off.
1101 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1102 Ops.erase(Ops.begin());
1103 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001104 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001105 // If we have a multiply of zero, it will always be zero.
1106 return Ops[0];
1107 }
1108 }
1109
1110 // Skip over the add expression until we get to a multiply.
1111 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1112 ++Idx;
1113
1114 if (Ops.size() == 1)
1115 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001116
Chris Lattner53e677a2004-04-02 20:23:17 +00001117 // If there are mul operands inline them all into this expression.
1118 if (Idx < Ops.size()) {
1119 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001120 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001121 // If we have an mul, expand the mul operands onto the end of the operands
1122 // list.
1123 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1124 Ops.erase(Ops.begin()+Idx);
1125 DeletedMul = true;
1126 }
1127
1128 // If we deleted at least one mul, we added operands to the end of the list,
1129 // and they are not necessarily sorted. Recurse to resort and resimplify
1130 // any operands we just aquired.
1131 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001132 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001133 }
1134
1135 // If there are any add recurrences in the operands list, see if any other
1136 // added values are loop invariant. If so, we can fold them into the
1137 // recurrence.
1138 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1139 ++Idx;
1140
1141 // Scan over all recurrences, trying to fold loop invariants into them.
1142 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1143 // Scan all of the other operands to this mul and add them to the vector if
1144 // they are loop invariant w.r.t. the recurrence.
1145 std::vector<SCEVHandle> LIOps;
1146 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1147 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1148 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1149 LIOps.push_back(Ops[i]);
1150 Ops.erase(Ops.begin()+i);
1151 --i; --e;
1152 }
1153
1154 // If we found some loop invariants, fold them into the recurrence.
1155 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001156 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001157 std::vector<SCEVHandle> NewOps;
1158 NewOps.reserve(AddRec->getNumOperands());
1159 if (LIOps.size() == 1) {
1160 SCEV *Scale = LIOps[0];
1161 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001162 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001163 } else {
1164 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1165 std::vector<SCEVHandle> MulOps(LIOps);
1166 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001167 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001168 }
1169 }
1170
Dan Gohman246b2562007-10-22 18:31:58 +00001171 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001172
1173 // If all of the other operands were loop invariant, we are done.
1174 if (Ops.size() == 1) return NewRec;
1175
1176 // Otherwise, multiply the folded AddRec by the non-liv parts.
1177 for (unsigned i = 0;; ++i)
1178 if (Ops[i] == AddRec) {
1179 Ops[i] = NewRec;
1180 break;
1181 }
Dan Gohman246b2562007-10-22 18:31:58 +00001182 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001183 }
1184
1185 // Okay, if there weren't any loop invariants to be folded, check to see if
1186 // there are multiple AddRec's with the same loop induction variable being
1187 // multiplied together. If so, we can fold them.
1188 for (unsigned OtherIdx = Idx+1;
1189 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1190 if (OtherIdx != Idx) {
1191 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1192 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1193 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1194 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman246b2562007-10-22 18:31:58 +00001195 SCEVHandle NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001196 G->getStart());
Dan Gohman246b2562007-10-22 18:31:58 +00001197 SCEVHandle B = F->getStepRecurrence(*this);
1198 SCEVHandle D = G->getStepRecurrence(*this);
1199 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1200 getMulExpr(G, B),
1201 getMulExpr(B, D));
1202 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1203 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001204 if (Ops.size() == 2) return NewAddRec;
1205
1206 Ops.erase(Ops.begin()+Idx);
1207 Ops.erase(Ops.begin()+OtherIdx-1);
1208 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001209 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001210 }
1211 }
1212
1213 // Otherwise couldn't fold anything into this recurrence. Move onto the
1214 // next one.
1215 }
1216
1217 // Okay, it looks like we really DO need an mul expr. Check to see if we
1218 // already have one, otherwise create a new one.
1219 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001220 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1221 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001222 if (Result == 0)
1223 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001224 return Result;
1225}
1226
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001227SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Dan Gohman622ed672009-05-04 22:02:23 +00001228 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001229 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky789558d2009-01-13 09:18:58 +00001230 return LHS; // X udiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +00001231
Dan Gohman622ed672009-05-04 22:02:23 +00001232 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001233 Constant *LHSCV = LHSC->getValue();
1234 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001235 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001236 }
1237 }
1238
Nick Lewycky789558d2009-01-13 09:18:58 +00001239 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1240
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001241 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1242 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001243 return Result;
1244}
1245
1246
1247/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1248/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001249SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Chris Lattner53e677a2004-04-02 20:23:17 +00001250 const SCEVHandle &Step, const Loop *L) {
1251 std::vector<SCEVHandle> Operands;
1252 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001253 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001254 if (StepChrec->getLoop() == L) {
1255 Operands.insert(Operands.end(), StepChrec->op_begin(),
1256 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001257 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001258 }
1259
1260 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001261 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001262}
1263
1264/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1265/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001266SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001267 const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001268 if (Operands.size() == 1) return Operands[0];
1269
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001270 if (Operands.back()->isZero()) {
1271 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001272 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001273 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001274
Dan Gohmand9cc7492008-08-08 18:33:12 +00001275 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001276 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmand9cc7492008-08-08 18:33:12 +00001277 const Loop* NestedLoop = NestedAR->getLoop();
1278 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1279 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1280 NestedAR->op_end());
1281 SCEVHandle NestedARHandle(NestedAR);
1282 Operands[0] = NestedAR->getStart();
1283 NestedOperands[0] = getAddRecExpr(Operands, L);
1284 return getAddRecExpr(NestedOperands, NestedLoop);
1285 }
1286 }
1287
Chris Lattner53e677a2004-04-02 20:23:17 +00001288 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001289 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1290 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001291 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1292 return Result;
1293}
1294
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001295SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1296 const SCEVHandle &RHS) {
1297 std::vector<SCEVHandle> Ops;
1298 Ops.push_back(LHS);
1299 Ops.push_back(RHS);
1300 return getSMaxExpr(Ops);
1301}
1302
1303SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1304 assert(!Ops.empty() && "Cannot get empty smax!");
1305 if (Ops.size() == 1) return Ops[0];
1306
1307 // Sort by complexity, this groups all similar expression types together.
1308 GroupByComplexity(Ops);
1309
1310 // If there are any constants, fold them together.
1311 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001312 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001313 ++Idx;
1314 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001315 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001316 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001317 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001318 APIntOps::smax(LHSC->getValue()->getValue(),
1319 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001320 Ops[0] = getConstant(Fold);
1321 Ops.erase(Ops.begin()+1); // Erase the folded element
1322 if (Ops.size() == 1) return Ops[0];
1323 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001324 }
1325
1326 // If we are left with a constant -inf, strip it off.
1327 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1328 Ops.erase(Ops.begin());
1329 --Idx;
1330 }
1331 }
1332
1333 if (Ops.size() == 1) return Ops[0];
1334
1335 // Find the first SMax
1336 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1337 ++Idx;
1338
1339 // Check to see if one of the operands is an SMax. If so, expand its operands
1340 // onto our operand list, and recurse to simplify.
1341 if (Idx < Ops.size()) {
1342 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001343 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001344 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1345 Ops.erase(Ops.begin()+Idx);
1346 DeletedSMax = true;
1347 }
1348
1349 if (DeletedSMax)
1350 return getSMaxExpr(Ops);
1351 }
1352
1353 // Okay, check to see if the same value occurs in the operand list twice. If
1354 // so, delete one. Since we sorted the list, these values are required to
1355 // be adjacent.
1356 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1357 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1358 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1359 --i; --e;
1360 }
1361
1362 if (Ops.size() == 1) return Ops[0];
1363
1364 assert(!Ops.empty() && "Reduced smax down to nothing!");
1365
Nick Lewycky3e630762008-02-20 06:48:22 +00001366 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001367 // already have one, otherwise create a new one.
1368 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1369 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1370 SCEVOps)];
1371 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1372 return Result;
1373}
1374
Nick Lewycky3e630762008-02-20 06:48:22 +00001375SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1376 const SCEVHandle &RHS) {
1377 std::vector<SCEVHandle> Ops;
1378 Ops.push_back(LHS);
1379 Ops.push_back(RHS);
1380 return getUMaxExpr(Ops);
1381}
1382
1383SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1384 assert(!Ops.empty() && "Cannot get empty umax!");
1385 if (Ops.size() == 1) return Ops[0];
1386
1387 // Sort by complexity, this groups all similar expression types together.
1388 GroupByComplexity(Ops);
1389
1390 // If there are any constants, fold them together.
1391 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001392 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001393 ++Idx;
1394 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001395 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001396 // We found two constants, fold them together!
1397 ConstantInt *Fold = ConstantInt::get(
1398 APIntOps::umax(LHSC->getValue()->getValue(),
1399 RHSC->getValue()->getValue()));
1400 Ops[0] = getConstant(Fold);
1401 Ops.erase(Ops.begin()+1); // Erase the folded element
1402 if (Ops.size() == 1) return Ops[0];
1403 LHSC = cast<SCEVConstant>(Ops[0]);
1404 }
1405
1406 // If we are left with a constant zero, strip it off.
1407 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1408 Ops.erase(Ops.begin());
1409 --Idx;
1410 }
1411 }
1412
1413 if (Ops.size() == 1) return Ops[0];
1414
1415 // Find the first UMax
1416 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1417 ++Idx;
1418
1419 // Check to see if one of the operands is a UMax. If so, expand its operands
1420 // onto our operand list, and recurse to simplify.
1421 if (Idx < Ops.size()) {
1422 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001423 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001424 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1425 Ops.erase(Ops.begin()+Idx);
1426 DeletedUMax = true;
1427 }
1428
1429 if (DeletedUMax)
1430 return getUMaxExpr(Ops);
1431 }
1432
1433 // Okay, check to see if the same value occurs in the operand list twice. If
1434 // so, delete one. Since we sorted the list, these values are required to
1435 // be adjacent.
1436 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1437 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1438 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1439 --i; --e;
1440 }
1441
1442 if (Ops.size() == 1) return Ops[0];
1443
1444 assert(!Ops.empty() && "Reduced umax down to nothing!");
1445
1446 // Okay, it looks like we really DO need a umax expr. Check to see if we
1447 // already have one, otherwise create a new one.
1448 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1449 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1450 SCEVOps)];
1451 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1452 return Result;
1453}
1454
Dan Gohman246b2562007-10-22 18:31:58 +00001455SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001456 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001457 return getConstant(CI);
Dan Gohman2d1be872009-04-16 03:18:22 +00001458 if (isa<ConstantPointerNull>(V))
1459 return getIntegerSCEV(0, V->getType());
Chris Lattnerb3364092006-10-04 21:49:37 +00001460 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001461 if (Result == 0) Result = new SCEVUnknown(V);
1462 return Result;
1463}
1464
Chris Lattner53e677a2004-04-02 20:23:17 +00001465//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001466// Basic SCEV Analysis and PHI Idiom Recognition Code
1467//
1468
Dan Gohmanf9a77b72009-05-03 05:46:20 +00001469/// deleteValueFromRecords - This method should be called by the
1470/// client before it removes an instruction from the program, to make sure
1471/// that no dangling references are left around.
1472void ScalarEvolution::deleteValueFromRecords(Value *V) {
1473 SmallVector<Value *, 16> Worklist;
1474
1475 if (Scalars.erase(V)) {
1476 if (PHINode *PN = dyn_cast<PHINode>(V))
1477 ConstantEvolutionLoopExitValue.erase(PN);
1478 Worklist.push_back(V);
1479 }
1480
1481 while (!Worklist.empty()) {
1482 Value *VV = Worklist.back();
1483 Worklist.pop_back();
1484
1485 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1486 UI != UE; ++UI) {
1487 Instruction *Inst = cast<Instruction>(*UI);
1488 if (Scalars.erase(Inst)) {
1489 if (PHINode *PN = dyn_cast<PHINode>(VV))
1490 ConstantEvolutionLoopExitValue.erase(PN);
1491 Worklist.push_back(Inst);
1492 }
1493 }
1494 }
1495}
1496
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001497/// isSCEVable - Test if values of the given type are analyzable within
1498/// the SCEV framework. This primarily includes integer types, and it
1499/// can optionally include pointer types if the ScalarEvolution class
1500/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001501bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001502 // Integers are always SCEVable.
1503 if (Ty->isInteger())
1504 return true;
1505
1506 // Pointers are SCEVable if TargetData information is available
1507 // to provide pointer size information.
1508 if (isa<PointerType>(Ty))
1509 return TD != NULL;
1510
1511 // Otherwise it's not SCEVable.
1512 return false;
1513}
1514
1515/// getTypeSizeInBits - Return the size in bits of the specified type,
1516/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001517uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001518 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1519
1520 // If we have a TargetData, use it!
1521 if (TD)
1522 return TD->getTypeSizeInBits(Ty);
1523
1524 // Otherwise, we support only integer types.
1525 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1526 return Ty->getPrimitiveSizeInBits();
1527}
1528
1529/// getEffectiveSCEVType - Return a type with the same bitwidth as
1530/// the given type and which represents how SCEV will treat the given
1531/// type, for which isSCEVable must return true. For pointer types,
1532/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001533const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001534 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1535
1536 if (Ty->isInteger())
1537 return Ty;
1538
1539 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1540 return TD->getIntPtrType();
Dan Gohman2d1be872009-04-16 03:18:22 +00001541}
Chris Lattner53e677a2004-04-02 20:23:17 +00001542
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001543SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00001544 return UnknownValue;
1545}
1546
Dan Gohman92fa56e2009-05-04 22:20:30 +00001547/// hasSCEV - Return true if the SCEV for this value has already been
Torok Edwine3d12852009-05-01 08:33:47 +00001548/// computed.
1549bool ScalarEvolution::hasSCEV(Value *V) const {
1550 return Scalars.count(V);
1551}
1552
Chris Lattner53e677a2004-04-02 20:23:17 +00001553/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1554/// expression and create a new one.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001555SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001556 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00001557
Dan Gohmanf9a77b72009-05-03 05:46:20 +00001558 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001559 if (I != Scalars.end()) return I->second;
1560 SCEVHandle S = createSCEV(V);
Dan Gohmanf9a77b72009-05-03 05:46:20 +00001561 Scalars.insert(std::make_pair(V, S));
Chris Lattner53e677a2004-04-02 20:23:17 +00001562 return S;
1563}
1564
Dan Gohman2d1be872009-04-16 03:18:22 +00001565/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1566/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001567SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1568 Ty = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001569 Constant *C;
1570 if (Val == 0)
1571 C = Constant::getNullValue(Ty);
1572 else if (Ty->isFloatingPoint())
1573 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1574 APFloat::IEEEdouble, Val));
1575 else
1576 C = ConstantInt::get(Ty, Val);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001577 return getUnknown(C);
Dan Gohman2d1be872009-04-16 03:18:22 +00001578}
1579
1580/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1581///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001582SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohman622ed672009-05-04 22:02:23 +00001583 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001584 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman2d1be872009-04-16 03:18:22 +00001585
1586 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001587 Ty = getEffectiveSCEVType(Ty);
1588 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00001589}
1590
1591/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001592SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohman622ed672009-05-04 22:02:23 +00001593 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001594 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman2d1be872009-04-16 03:18:22 +00001595
1596 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001597 Ty = getEffectiveSCEVType(Ty);
1598 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman2d1be872009-04-16 03:18:22 +00001599 return getMinusSCEV(AllOnes, V);
1600}
1601
1602/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1603///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001604SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001605 const SCEVHandle &RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001606 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001607 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00001608}
1609
1610/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1611/// input value to the specified type. If the type must be extended, it is zero
1612/// extended.
1613SCEVHandle
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001614ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001615 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001616 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001617 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1618 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00001619 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001620 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00001621 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001622 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001623 return getTruncateExpr(V, Ty);
1624 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001625}
1626
1627/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1628/// input value to the specified type. If the type must be extended, it is sign
1629/// extended.
1630SCEVHandle
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001631ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001632 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001633 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001634 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1635 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00001636 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001637 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00001638 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001639 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001640 return getTruncateExpr(V, Ty);
1641 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001642}
1643
Chris Lattner4dc534c2005-02-13 04:37:18 +00001644/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1645/// the specified instruction and replaces any references to the symbolic value
1646/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001647void ScalarEvolution::
Chris Lattner4dc534c2005-02-13 04:37:18 +00001648ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1649 const SCEVHandle &NewVal) {
Dan Gohmanf9a77b72009-05-03 05:46:20 +00001650 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001651 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001652
Chris Lattner4dc534c2005-02-13 04:37:18 +00001653 SCEVHandle NV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001654 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001655 if (NV == SI->second) return; // No change.
1656
1657 SI->second = NV; // Update the scalars map!
1658
1659 // Any instruction values that use this instruction might also need to be
1660 // updated!
1661 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1662 UI != E; ++UI)
1663 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1664}
Chris Lattner53e677a2004-04-02 20:23:17 +00001665
1666/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1667/// a loop header, making it a potential recurrence, or it doesn't.
1668///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001669SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001670 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001671 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00001672 if (L->getHeader() == PN->getParent()) {
1673 // If it lives in the loop header, it has two incoming values, one
1674 // from outside the loop, and one from inside.
1675 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1676 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001677
Chris Lattner53e677a2004-04-02 20:23:17 +00001678 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001679 SCEVHandle SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001680 assert(Scalars.find(PN) == Scalars.end() &&
1681 "PHI node already processed?");
Dan Gohmanf9a77b72009-05-03 05:46:20 +00001682 Scalars.insert(std::make_pair(PN, SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00001683
1684 // Using this symbolic name for the PHI, analyze the value coming around
1685 // the back-edge.
1686 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1687
1688 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1689 // has a special value for the first iteration of the loop.
1690
1691 // If the value coming around the backedge is an add with the symbolic
1692 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00001693 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001694 // If there is a single occurrence of the symbolic value, replace it
1695 // with a recurrence.
1696 unsigned FoundIndex = Add->getNumOperands();
1697 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1698 if (Add->getOperand(i) == SymbolicName)
1699 if (FoundIndex == e) {
1700 FoundIndex = i;
1701 break;
1702 }
1703
1704 if (FoundIndex != Add->getNumOperands()) {
1705 // Create an add with everything but the specified operand.
1706 std::vector<SCEVHandle> Ops;
1707 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1708 if (i != FoundIndex)
1709 Ops.push_back(Add->getOperand(i));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001710 SCEVHandle Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001711
1712 // This is not a valid addrec if the step amount is varying each
1713 // loop iteration, but is not itself an addrec in this loop.
1714 if (Accum->isLoopInvariant(L) ||
1715 (isa<SCEVAddRecExpr>(Accum) &&
1716 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1717 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001718 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001719
1720 // Okay, for the entire analysis of this edge we assumed the PHI
1721 // to be symbolic. We now need to go back and update all of the
1722 // entries for the scalars that use the PHI (except for the PHI
1723 // itself) to use the new analyzed value instead of the "symbolic"
1724 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001725 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001726 return PHISCEV;
1727 }
1728 }
Dan Gohman622ed672009-05-04 22:02:23 +00001729 } else if (const SCEVAddRecExpr *AddRec =
1730 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00001731 // Otherwise, this could be a loop like this:
1732 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1733 // In this case, j = {1,+,1} and BEValue is j.
1734 // Because the other in-value of i (0) fits the evolution of BEValue
1735 // i really is an addrec evolution.
1736 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1737 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1738
1739 // If StartVal = j.start - j.stride, we can use StartVal as the
1740 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001741 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00001742 AddRec->getOperand(1))) {
Chris Lattner97156e72006-04-26 18:34:07 +00001743 SCEVHandle PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001744 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00001745
1746 // Okay, for the entire analysis of this edge we assumed the PHI
1747 // to be symbolic. We now need to go back and update all of the
1748 // entries for the scalars that use the PHI (except for the PHI
1749 // itself) to use the new analyzed value instead of the "symbolic"
1750 // value.
1751 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1752 return PHISCEV;
1753 }
1754 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001755 }
1756
1757 return SymbolicName;
1758 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001759
Chris Lattner53e677a2004-04-02 20:23:17 +00001760 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001761 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001762}
1763
Nick Lewycky83bb0052007-11-22 07:59:40 +00001764/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1765/// guaranteed to end in (at every loop iteration). It is, at the same time,
1766/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1767/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001768static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Dan Gohman622ed672009-05-04 22:02:23 +00001769 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00001770 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00001771
Dan Gohman622ed672009-05-04 22:02:23 +00001772 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001773 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1774 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00001775
Dan Gohman622ed672009-05-04 22:02:23 +00001776 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001777 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1778 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1779 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00001780 }
1781
Dan Gohman622ed672009-05-04 22:02:23 +00001782 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001783 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1784 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1785 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00001786 }
1787
Dan Gohman622ed672009-05-04 22:02:23 +00001788 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001789 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001790 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky83bb0052007-11-22 07:59:40 +00001791 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001792 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky83bb0052007-11-22 07:59:40 +00001793 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001794 }
1795
Dan Gohman622ed672009-05-04 22:02:23 +00001796 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001797 // The result is the sum of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001798 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1799 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00001800 for (unsigned i = 1, e = M->getNumOperands();
1801 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001802 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky83bb0052007-11-22 07:59:40 +00001803 BitWidth);
1804 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001805 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001806
Dan Gohman622ed672009-05-04 22:02:23 +00001807 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001808 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001809 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky83bb0052007-11-22 07:59:40 +00001810 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001811 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky83bb0052007-11-22 07:59:40 +00001812 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001813 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001814
Dan Gohman622ed672009-05-04 22:02:23 +00001815 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001816 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001817 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001818 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001819 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001820 return MinOpRes;
1821 }
1822
Dan Gohman622ed672009-05-04 22:02:23 +00001823 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001824 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001825 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky3e630762008-02-20 06:48:22 +00001826 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001827 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky3e630762008-02-20 06:48:22 +00001828 return MinOpRes;
1829 }
1830
Nick Lewycky789558d2009-01-13 09:18:58 +00001831 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky83bb0052007-11-22 07:59:40 +00001832 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00001833}
Chris Lattner53e677a2004-04-02 20:23:17 +00001834
1835/// createSCEV - We know that there is no SCEV for the specified value.
1836/// Analyze the expression.
1837///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001838SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001839 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001840 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00001841
Dan Gohman6c459a22008-06-22 19:56:46 +00001842 unsigned Opcode = Instruction::UserOp1;
1843 if (Instruction *I = dyn_cast<Instruction>(V))
1844 Opcode = I->getOpcode();
1845 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1846 Opcode = CE->getOpcode();
1847 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001848 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00001849
Dan Gohman6c459a22008-06-22 19:56:46 +00001850 User *U = cast<User>(V);
1851 switch (Opcode) {
1852 case Instruction::Add:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001853 return getAddExpr(getSCEV(U->getOperand(0)),
1854 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00001855 case Instruction::Mul:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001856 return getMulExpr(getSCEV(U->getOperand(0)),
1857 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00001858 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001859 return getUDivExpr(getSCEV(U->getOperand(0)),
1860 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00001861 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001862 return getMinusSCEV(getSCEV(U->getOperand(0)),
1863 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00001864 case Instruction::And:
1865 // For an expression like x&255 that merely masks off the high bits,
1866 // use zext(trunc(x)) as the SCEV expression.
1867 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00001868 if (CI->isNullValue())
1869 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00001870 if (CI->isAllOnesValue())
1871 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00001872 const APInt &A = CI->getValue();
1873 unsigned Ones = A.countTrailingOnes();
1874 if (APIntOps::isMask(Ones, A))
1875 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001876 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
1877 IntegerType::get(Ones)),
1878 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00001879 }
1880 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00001881 case Instruction::Or:
1882 // If the RHS of the Or is a constant, we may have something like:
1883 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1884 // optimizations will transparently handle this case.
1885 //
1886 // In order for this transformation to be safe, the LHS must be of the
1887 // form X*(2^n) and the Or constant must be less than 2^n.
1888 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1889 SCEVHandle LHS = getSCEV(U->getOperand(0));
1890 const APInt &CIVal = CI->getValue();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001891 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman6c459a22008-06-22 19:56:46 +00001892 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001893 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001894 }
Dan Gohman6c459a22008-06-22 19:56:46 +00001895 break;
1896 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00001897 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00001898 // If the RHS of the xor is a signbit, then this is just an add.
1899 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00001900 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001901 return getAddExpr(getSCEV(U->getOperand(0)),
1902 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00001903
1904 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman6c459a22008-06-22 19:56:46 +00001905 else if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001906 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman6c459a22008-06-22 19:56:46 +00001907 }
1908 break;
1909
1910 case Instruction::Shl:
1911 // Turn shift left of a constant amount into a multiply.
1912 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1913 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1914 Constant *X = ConstantInt::get(
1915 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001916 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00001917 }
1918 break;
1919
Nick Lewycky01eaf802008-07-07 06:15:49 +00001920 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00001921 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00001922 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1923 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1924 Constant *X = ConstantInt::get(
1925 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001926 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00001927 }
1928 break;
1929
Dan Gohman4ee29af2009-04-21 02:26:00 +00001930 case Instruction::AShr:
1931 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
1932 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
1933 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
1934 if (L->getOpcode() == Instruction::Shl &&
1935 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00001936 unsigned BitWidth = getTypeSizeInBits(U->getType());
1937 uint64_t Amt = BitWidth - CI->getZExtValue();
1938 if (Amt == BitWidth)
1939 return getSCEV(L->getOperand(0)); // shift by zero --> noop
1940 if (Amt > BitWidth)
1941 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00001942 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001943 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman2c73d5f2009-04-25 17:05:40 +00001944 IntegerType::get(Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00001945 U->getType());
1946 }
1947 break;
1948
Dan Gohman6c459a22008-06-22 19:56:46 +00001949 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001950 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00001951
1952 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001953 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00001954
1955 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001956 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00001957
1958 case Instruction::BitCast:
1959 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001960 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00001961 return getSCEV(U->getOperand(0));
1962 break;
1963
Dan Gohman2d1be872009-04-16 03:18:22 +00001964 case Instruction::IntToPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001965 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00001966 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001967 TD->getIntPtrType());
Dan Gohman2d1be872009-04-16 03:18:22 +00001968
1969 case Instruction::PtrToInt:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001970 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00001971 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
1972 U->getType());
1973
1974 case Instruction::GetElementPtr: {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001975 if (!TD) break; // Without TD we can't analyze pointers.
1976 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohman2d1be872009-04-16 03:18:22 +00001977 Value *Base = U->getOperand(0);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001978 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohman2d1be872009-04-16 03:18:22 +00001979 gep_type_iterator GTI = gep_type_begin(U);
1980 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
1981 E = U->op_end();
1982 I != E; ++I) {
1983 Value *Index = *I;
1984 // Compute the (potentially symbolic) offset in bytes for this index.
1985 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1986 // For a struct, add the member offset.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001987 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohman2d1be872009-04-16 03:18:22 +00001988 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1989 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001990 TotalOffset = getAddExpr(TotalOffset,
1991 getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman2d1be872009-04-16 03:18:22 +00001992 } else {
1993 // For an array, add the element offset, explicitly scaled.
1994 SCEVHandle LocalOffset = getSCEV(Index);
1995 if (!isa<PointerType>(LocalOffset->getType()))
1996 // Getelementptr indicies are signed.
1997 LocalOffset = getTruncateOrSignExtend(LocalOffset,
1998 IntPtrTy);
1999 LocalOffset =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002000 getMulExpr(LocalOffset,
2001 getIntegerSCEV(TD->getTypePaddedSize(*GTI),
2002 IntPtrTy));
2003 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman2d1be872009-04-16 03:18:22 +00002004 }
2005 }
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002006 return getAddExpr(getSCEV(Base), TotalOffset);
Dan Gohman2d1be872009-04-16 03:18:22 +00002007 }
2008
Dan Gohman6c459a22008-06-22 19:56:46 +00002009 case Instruction::PHI:
2010 return createNodeForPHI(cast<PHINode>(U));
2011
2012 case Instruction::Select:
2013 // This could be a smax or umax that was lowered earlier.
2014 // Try to recover it.
2015 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2016 Value *LHS = ICI->getOperand(0);
2017 Value *RHS = ICI->getOperand(1);
2018 switch (ICI->getPredicate()) {
2019 case ICmpInst::ICMP_SLT:
2020 case ICmpInst::ICMP_SLE:
2021 std::swap(LHS, RHS);
2022 // fall through
2023 case ICmpInst::ICMP_SGT:
2024 case ICmpInst::ICMP_SGE:
2025 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002026 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002027 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman1fbffe02008-07-30 04:36:32 +00002028 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002029 return getNotSCEV(getSMaxExpr(
2030 getNotSCEV(getSCEV(LHS)),
2031 getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00002032 break;
2033 case ICmpInst::ICMP_ULT:
2034 case ICmpInst::ICMP_ULE:
2035 std::swap(LHS, RHS);
2036 // fall through
2037 case ICmpInst::ICMP_UGT:
2038 case ICmpInst::ICMP_UGE:
2039 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002040 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002041 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2042 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002043 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2044 getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00002045 break;
2046 default:
2047 break;
2048 }
2049 }
2050
2051 default: // We cannot analyze this expression.
2052 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002053 }
2054
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002055 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002056}
2057
2058
2059
2060//===----------------------------------------------------------------------===//
2061// Iteration Count Computation Code
2062//
2063
Dan Gohman46bdfb02009-02-24 18:55:53 +00002064/// getBackedgeTakenCount - If the specified loop has a predictable
2065/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2066/// object. The backedge-taken count is the number of times the loop header
2067/// will be branched to from within the loop. This is one less than the
2068/// trip count of the loop, since it doesn't count the first iteration,
2069/// when the header is branched to from outside the loop.
2070///
2071/// Note that it is not valid to call this method on a loop without a
2072/// loop-invariant backedge-taken count (see
2073/// hasLoopInvariantBackedgeTakenCount).
2074///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002075SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002076 return getBackedgeTakenInfo(L).Exact;
2077}
2078
2079/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2080/// return the least SCEV value that is known never to be less than the
2081/// actual backedge taken count.
2082SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2083 return getBackedgeTakenInfo(L).Max;
2084}
2085
2086const ScalarEvolution::BackedgeTakenInfo &
2087ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00002088 // Initially insert a CouldNotCompute for this loop. If the insertion
2089 // succeeds, procede to actually compute a backedge-taken count and
2090 // update the value. The temporary CouldNotCompute value tells SCEV
2091 // code elsewhere that it shouldn't attempt to request a new
2092 // backedge-taken count, which could result in infinite recursion.
Dan Gohmana1af7572009-04-30 20:47:05 +00002093 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00002094 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2095 if (Pair.second) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002096 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2097 if (ItCount.Exact != UnknownValue) {
2098 assert(ItCount.Exact->isLoopInvariant(L) &&
2099 ItCount.Max->isLoopInvariant(L) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002100 "Computed trip count isn't loop invariant for loop!");
2101 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00002102
Dan Gohman01ecca22009-04-27 20:16:15 +00002103 // Update the value in the map.
2104 Pair.first->second = ItCount;
Chris Lattner53e677a2004-04-02 20:23:17 +00002105 } else if (isa<PHINode>(L->getHeader()->begin())) {
2106 // Only count loops that have phi nodes as not being computable.
2107 ++NumTripCountsNotComputed;
2108 }
Dan Gohmana1af7572009-04-30 20:47:05 +00002109
2110 // Now that we know more about the trip count for this loop, forget any
2111 // existing SCEV values for PHI nodes in this loop since they are only
2112 // conservative estimates made without the benefit
2113 // of trip count information.
2114 if (ItCount.hasAnyInfo())
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00002115 forgetLoopPHIs(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002116 }
Dan Gohman01ecca22009-04-27 20:16:15 +00002117 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00002118}
2119
Dan Gohman46bdfb02009-02-24 18:55:53 +00002120/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohman60f8a632009-02-17 20:49:49 +00002121/// client when it has changed a loop in a way that may effect
Dan Gohman46bdfb02009-02-24 18:55:53 +00002122/// ScalarEvolution's ability to compute a trip count, or if the loop
2123/// is deleted.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002124void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00002125 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00002126 forgetLoopPHIs(L);
2127}
2128
2129/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2130/// PHI nodes in the given loop. This is used when the trip count of
2131/// the loop may have changed.
2132void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
2133 for (BasicBlock::iterator I = L->getHeader()->begin();
2134 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Dan Gohmanf9a77b72009-05-03 05:46:20 +00002135 deleteValueFromRecords(PN);
Dan Gohman60f8a632009-02-17 20:49:49 +00002136}
2137
Dan Gohman46bdfb02009-02-24 18:55:53 +00002138/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2139/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00002140ScalarEvolution::BackedgeTakenInfo
2141ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002142 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patelb7211a22007-08-21 00:31:24 +00002143 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002144 L->getExitBlocks(ExitBlocks);
2145 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002146
2147 // Okay, there is one exit block. Try to find the condition that causes the
2148 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002149 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00002150
2151 BasicBlock *ExitingBlock = 0;
2152 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2153 PI != E; ++PI)
2154 if (L->contains(*PI)) {
2155 if (ExitingBlock == 0)
2156 ExitingBlock = *PI;
2157 else
2158 return UnknownValue; // More than one block exiting!
2159 }
2160 assert(ExitingBlock && "No exits from loop, something is broken!");
2161
2162 // Okay, we've computed the exiting block. See what condition causes us to
2163 // exit.
2164 //
2165 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00002166 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2167 if (ExitBr == 0) return UnknownValue;
2168 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00002169
2170 // At this point, we know we have a conditional branch that determines whether
2171 // the loop is exited. However, we don't know if the branch is executed each
2172 // time through the loop. If not, then the execution count of the branch will
2173 // not be equal to the trip count of the loop.
2174 //
2175 // Currently we check for this by checking to see if the Exit branch goes to
2176 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00002177 // times as the loop. We also handle the case where the exit block *is* the
2178 // loop header. This is common for un-rotated loops. More extensive analysis
2179 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00002180 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00002181 ExitBr->getSuccessor(1) != L->getHeader() &&
2182 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00002183 return UnknownValue;
2184
Reid Spencere4d87aa2006-12-23 06:05:41 +00002185 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2186
Nick Lewycky3b711652008-02-21 08:34:02 +00002187 // If it's not an integer comparison then compute it the hard way.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002188 // Note that ICmpInst deals with pointer comparisons too so we must check
2189 // the type of the operand.
Chris Lattner8b0e3602007-01-07 02:24:26 +00002190 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Dan Gohman46bdfb02009-02-24 18:55:53 +00002191 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Chris Lattner7980fb92004-04-17 18:36:24 +00002192 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00002193
Reid Spencere4d87aa2006-12-23 06:05:41 +00002194 // If the condition was exit on true, convert the condition to exit on false
2195 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00002196 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00002197 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002198 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00002199 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002200
2201 // Handle common loops like: for (X = "string"; *X; ++X)
2202 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2203 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2204 SCEVHandle ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00002205 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Chris Lattner673e02b2004-10-12 01:49:27 +00002206 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2207 }
2208
Chris Lattner53e677a2004-04-02 20:23:17 +00002209 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2210 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2211
2212 // Try to evaluate any dependencies out of the loop.
2213 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2214 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2215 Tmp = getSCEVAtScope(RHS, L);
2216 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2217
Reid Spencere4d87aa2006-12-23 06:05:41 +00002218 // At this point, we would like to compute how many iterations of the
2219 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00002220 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2221 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00002222 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002223 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00002224 }
2225
Chris Lattner53e677a2004-04-02 20:23:17 +00002226 // If we have a comparison of a chrec against a constant, try to use value
2227 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00002228 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2229 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00002230 if (AddRec->getLoop() == L) {
2231 // Form the comparison range using the constant of the correct type so
2232 // that the ConstantRange class knows to do a signed or unsigned
2233 // comparison.
2234 ConstantInt *CompVal = RHSC->getValue();
2235 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00002236 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00002237 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00002238 if (CompVal) {
2239 // Form the constant range.
Reid Spencerc6aedf72007-02-28 22:03:51 +00002240 ConstantRange CompRange(
2241 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002242
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002243 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00002244 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2245 }
2246 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002247
Chris Lattner53e677a2004-04-02 20:23:17 +00002248 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002249 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00002250 // Convert to: while (X-Y != 0)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002251 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002252 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002253 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002254 }
2255 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00002256 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002257 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002258 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002259 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002260 }
2261 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002262 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2263 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002264 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002265 }
2266 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002267 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2268 getNotSCEV(RHS), L, true);
2269 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002270 break;
2271 }
2272 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002273 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2274 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002275 break;
2276 }
2277 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002278 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2279 getNotSCEV(RHS), L, false);
2280 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002281 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002282 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002283 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002284#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002285 errs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002286 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002287 errs() << "[unsigned] ";
2288 errs() << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00002289 << Instruction::getOpcodeName(Instruction::ICmp)
2290 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002291#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00002292 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002293 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00002294 return
2295 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2296 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00002297}
2298
Chris Lattner673e02b2004-10-12 01:49:27 +00002299static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00002300EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2301 ScalarEvolution &SE) {
2302 SCEVHandle InVal = SE.getConstant(C);
2303 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002304 assert(isa<SCEVConstant>(Val) &&
2305 "Evaluation of SCEV at constant didn't fold correctly?");
2306 return cast<SCEVConstant>(Val)->getValue();
2307}
2308
2309/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2310/// and a GEP expression (missing the pointer index) indexing into it, return
2311/// the addressed element of the initializer or null if the index expression is
2312/// invalid.
2313static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002314GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00002315 const std::vector<ConstantInt*> &Indices) {
2316 Constant *Init = GV->getInitializer();
2317 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002318 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00002319 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2320 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2321 Init = cast<Constant>(CS->getOperand(Idx));
2322 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2323 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2324 Init = cast<Constant>(CA->getOperand(Idx));
2325 } else if (isa<ConstantAggregateZero>(Init)) {
2326 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2327 assert(Idx < STy->getNumElements() && "Bad struct index!");
2328 Init = Constant::getNullValue(STy->getElementType(Idx));
2329 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2330 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2331 Init = Constant::getNullValue(ATy->getElementType());
2332 } else {
2333 assert(0 && "Unknown constant aggregate type!");
2334 }
2335 return 0;
2336 } else {
2337 return 0; // Unknown initializer type
2338 }
2339 }
2340 return Init;
2341}
2342
Dan Gohman46bdfb02009-02-24 18:55:53 +00002343/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2344/// 'icmp op load X, cst', try to see if we can compute the backedge
2345/// execution count.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002346SCEVHandle ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00002347ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2348 const Loop *L,
2349 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002350 if (LI->isVolatile()) return UnknownValue;
2351
2352 // Check to see if the loaded pointer is a getelementptr of a global.
2353 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2354 if (!GEP) return UnknownValue;
2355
2356 // Make sure that it is really a constant global we are gepping, with an
2357 // initializer, and make sure the first IDX is really 0.
2358 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2359 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2360 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2361 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2362 return UnknownValue;
2363
2364 // Okay, we allow one non-constant index into the GEP instruction.
2365 Value *VarIdx = 0;
2366 std::vector<ConstantInt*> Indexes;
2367 unsigned VarIdxNum = 0;
2368 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2369 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2370 Indexes.push_back(CI);
2371 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2372 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2373 VarIdx = GEP->getOperand(i);
2374 VarIdxNum = i-2;
2375 Indexes.push_back(0);
2376 }
2377
2378 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2379 // Check to see if X is a loop variant variable value now.
2380 SCEVHandle Idx = getSCEV(VarIdx);
2381 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2382 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2383
2384 // We can only recognize very limited forms of loop index expressions, in
2385 // particular, only affine AddRec's like {C1,+,C2}.
2386 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2387 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2388 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2389 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2390 return UnknownValue;
2391
2392 unsigned MaxSteps = MaxBruteForceIterations;
2393 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002394 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00002395 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002396 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00002397
2398 // Form the GEP offset.
2399 Indexes[VarIdxNum] = Val;
2400
2401 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2402 if (Result == 0) break; // Cannot compute!
2403
2404 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002405 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002406 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00002407 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002408#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002409 errs() << "\n***\n*** Computed loop count " << *ItCst
2410 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2411 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00002412#endif
2413 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002414 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00002415 }
2416 }
2417 return UnknownValue;
2418}
2419
2420
Chris Lattner3221ad02004-04-17 22:58:41 +00002421/// CanConstantFold - Return true if we can constant fold an instruction of the
2422/// specified type, assuming that all operands were constants.
2423static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00002424 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00002425 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2426 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002427
Chris Lattner3221ad02004-04-17 22:58:41 +00002428 if (const CallInst *CI = dyn_cast<CallInst>(I))
2429 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00002430 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00002431 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00002432}
2433
Chris Lattner3221ad02004-04-17 22:58:41 +00002434/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2435/// in the loop that V is derived from. We allow arbitrary operations along the
2436/// way, but the operands of an operation must either be constants or a value
2437/// derived from a constant PHI. If this expression does not fit with these
2438/// constraints, return null.
2439static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2440 // If this is not an instruction, or if this is an instruction outside of the
2441 // loop, it can't be derived from a loop PHI.
2442 Instruction *I = dyn_cast<Instruction>(V);
2443 if (I == 0 || !L->contains(I->getParent())) return 0;
2444
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002445 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002446 if (L->getHeader() == I->getParent())
2447 return PN;
2448 else
2449 // We don't currently keep track of the control flow needed to evaluate
2450 // PHIs, so we cannot handle PHIs inside of loops.
2451 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002452 }
Chris Lattner3221ad02004-04-17 22:58:41 +00002453
2454 // If we won't be able to constant fold this expression even if the operands
2455 // are constants, return early.
2456 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002457
Chris Lattner3221ad02004-04-17 22:58:41 +00002458 // Otherwise, we can evaluate this instruction if all of its operands are
2459 // constant or derived from a PHI node themselves.
2460 PHINode *PHI = 0;
2461 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2462 if (!(isa<Constant>(I->getOperand(Op)) ||
2463 isa<GlobalValue>(I->getOperand(Op)))) {
2464 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2465 if (P == 0) return 0; // Not evolving from PHI
2466 if (PHI == 0)
2467 PHI = P;
2468 else if (PHI != P)
2469 return 0; // Evolving from multiple different PHIs.
2470 }
2471
2472 // This is a expression evolving from a constant PHI!
2473 return PHI;
2474}
2475
2476/// EvaluateExpression - Given an expression that passes the
2477/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2478/// in the loop has the value PHIVal. If we can't fold this expression for some
2479/// reason, return null.
2480static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2481 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00002482 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00002483 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00002484 Instruction *I = cast<Instruction>(V);
2485
2486 std::vector<Constant*> Operands;
2487 Operands.resize(I->getNumOperands());
2488
2489 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2490 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2491 if (Operands[i] == 0) return 0;
2492 }
2493
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002494 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2495 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2496 &Operands[0], Operands.size());
2497 else
2498 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2499 &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00002500}
2501
2502/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2503/// in the header of its containing loop, we know the loop executes a
2504/// constant number of times, and the PHI node is just a recurrence
2505/// involving constants, fold it.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002506Constant *ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00002507getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00002508 std::map<PHINode*, Constant*>::iterator I =
2509 ConstantEvolutionLoopExitValue.find(PN);
2510 if (I != ConstantEvolutionLoopExitValue.end())
2511 return I->second;
2512
Dan Gohman46bdfb02009-02-24 18:55:53 +00002513 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00002514 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2515
2516 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2517
2518 // Since the loop is canonicalized, the PHI node must have two entries. One
2519 // entry must be a constant (coming in from outside of the loop), and the
2520 // second must be derived from the same PHI.
2521 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2522 Constant *StartCST =
2523 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2524 if (StartCST == 0)
2525 return RetVal = 0; // Must be a constant.
2526
2527 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2528 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2529 if (PN2 != PN)
2530 return RetVal = 0; // Not derived from same PHI.
2531
2532 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00002533 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00002534 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00002535
Dan Gohman46bdfb02009-02-24 18:55:53 +00002536 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00002537 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00002538 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2539 if (IterationNum == NumIterations)
2540 return RetVal = PHIVal; // Got exit value!
2541
2542 // Compute the value of the PHI node for the next iteration.
2543 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2544 if (NextPHI == PHIVal)
2545 return RetVal = NextPHI; // Stopped evolving!
2546 if (NextPHI == 0)
2547 return 0; // Couldn't evaluate!
2548 PHIVal = NextPHI;
2549 }
2550}
2551
Dan Gohman46bdfb02009-02-24 18:55:53 +00002552/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00002553/// constant number of times (the condition evolves only from constants),
2554/// try to evaluate a few iterations of the loop until we get the exit
2555/// condition gets a value of ExitWhen (true or false). If we cannot
2556/// evaluate the trip count of the loop, return UnknownValue.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002557SCEVHandle ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00002558ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00002559 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2560 if (PN == 0) return UnknownValue;
2561
2562 // Since the loop is canonicalized, the PHI node must have two entries. One
2563 // entry must be a constant (coming in from outside of the loop), and the
2564 // second must be derived from the same PHI.
2565 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2566 Constant *StartCST =
2567 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2568 if (StartCST == 0) return UnknownValue; // Must be a constant.
2569
2570 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2571 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2572 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2573
2574 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2575 // the loop symbolically to determine when the condition gets a value of
2576 // "ExitWhen".
2577 unsigned IterationNum = 0;
2578 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2579 for (Constant *PHIVal = StartCST;
2580 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002581 ConstantInt *CondVal =
2582 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00002583
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002584 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00002585 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002586
Reid Spencere8019bb2007-03-01 07:25:48 +00002587 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002588 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00002589 ++NumBruteForceTripCountsComputed;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002590 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00002591 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002592
Chris Lattner3221ad02004-04-17 22:58:41 +00002593 // Compute the value of the PHI node for the next iteration.
2594 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2595 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00002596 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00002597 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00002598 }
2599
2600 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00002601 return UnknownValue;
2602}
2603
2604/// getSCEVAtScope - Compute the value of the specified expression within the
2605/// indicated loop (which may be null to indicate in no loop). If the
2606/// expression cannot be evaluated, return UnknownValue.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002607SCEVHandle ScalarEvolution::getSCEVAtScope(SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002608 // FIXME: this should be turned into a virtual method on SCEV!
2609
Chris Lattner3221ad02004-04-17 22:58:41 +00002610 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002611
Nick Lewycky3e630762008-02-20 06:48:22 +00002612 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00002613 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00002614 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002615 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002616 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00002617 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2618 if (PHINode *PN = dyn_cast<PHINode>(I))
2619 if (PN->getParent() == LI->getHeader()) {
2620 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00002621 // to see if the loop that contains it has a known backedge-taken
2622 // count. If so, we may be able to force computation of the exit
2623 // value.
2624 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00002625 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00002626 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002627 // Okay, we know how many times the containing loop executes. If
2628 // this is a constant evolving PHI node, get the final value at
2629 // the specified iteration number.
2630 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00002631 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00002632 LI);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002633 if (RV) return getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00002634 }
2635 }
2636
Reid Spencer09906f32006-12-04 21:33:23 +00002637 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00002638 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00002639 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00002640 // result. This is particularly useful for computing loop exit values.
2641 if (CanConstantFold(I)) {
2642 std::vector<Constant*> Operands;
2643 Operands.reserve(I->getNumOperands());
2644 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2645 Value *Op = I->getOperand(i);
2646 if (Constant *C = dyn_cast<Constant>(Op)) {
2647 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002648 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00002649 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00002650 // non-integer and non-pointer, don't even try to analyze them
2651 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00002652 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00002653 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00002654
Chris Lattner3221ad02004-04-17 22:58:41 +00002655 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohman622ed672009-05-04 22:02:23 +00002656 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00002657 Constant *C = SC->getValue();
2658 if (C->getType() != Op->getType())
2659 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2660 Op->getType(),
2661 false),
2662 C, Op->getType());
2663 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00002664 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00002665 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
2666 if (C->getType() != Op->getType())
2667 C =
2668 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2669 Op->getType(),
2670 false),
2671 C, Op->getType());
2672 Operands.push_back(C);
2673 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00002674 return V;
2675 } else {
2676 return V;
2677 }
2678 }
2679 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002680
2681 Constant *C;
2682 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2683 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2684 &Operands[0], Operands.size());
2685 else
2686 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2687 &Operands[0], Operands.size());
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002688 return getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002689 }
2690 }
2691
2692 // This is some other type of SCEVUnknown, just return it.
2693 return V;
2694 }
2695
Dan Gohman622ed672009-05-04 22:02:23 +00002696 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002697 // Avoid performing the look-up in the common case where the specified
2698 // expression has no loop-variant portions.
2699 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2700 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2701 if (OpAtScope != Comm->getOperand(i)) {
2702 if (OpAtScope == UnknownValue) return UnknownValue;
2703 // Okay, at least one of these operands is loop variant but might be
2704 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002705 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002706 NewOps.push_back(OpAtScope);
2707
2708 for (++i; i != e; ++i) {
2709 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2710 if (OpAtScope == UnknownValue) return UnknownValue;
2711 NewOps.push_back(OpAtScope);
2712 }
2713 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002714 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002715 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002716 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002717 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002718 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00002719 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002720 return getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002721 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002722 }
2723 }
2724 // If we got here, all operands are loop invariant.
2725 return Comm;
2726 }
2727
Dan Gohman622ed672009-05-04 22:02:23 +00002728 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Nick Lewycky789558d2009-01-13 09:18:58 +00002729 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002730 if (LHS == UnknownValue) return LHS;
Nick Lewycky789558d2009-01-13 09:18:58 +00002731 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002732 if (RHS == UnknownValue) return RHS;
Nick Lewycky789558d2009-01-13 09:18:58 +00002733 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2734 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002735 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002736 }
2737
2738 // If this is a loop recurrence for a loop that does not contain L, then we
2739 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00002740 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002741 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2742 // To evaluate this recurrence, we need to know how many times the AddRec
2743 // loop iterates. Compute this now.
Dan Gohman46bdfb02009-02-24 18:55:53 +00002744 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2745 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002746
Eli Friedmanb42a6262008-08-04 23:49:06 +00002747 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002748 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00002749 }
2750 return UnknownValue;
2751 }
2752
Dan Gohman622ed672009-05-04 22:02:23 +00002753 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmaneb3948b2009-04-29 22:29:01 +00002754 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2755 if (Op == UnknownValue) return Op;
2756 if (Op == Cast->getOperand())
2757 return Cast; // must be loop invariant
2758 return getZeroExtendExpr(Op, Cast->getType());
2759 }
2760
Dan Gohman622ed672009-05-04 22:02:23 +00002761 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmaneb3948b2009-04-29 22:29:01 +00002762 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2763 if (Op == UnknownValue) return Op;
2764 if (Op == Cast->getOperand())
2765 return Cast; // must be loop invariant
2766 return getSignExtendExpr(Op, Cast->getType());
2767 }
2768
Dan Gohman622ed672009-05-04 22:02:23 +00002769 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmaneb3948b2009-04-29 22:29:01 +00002770 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2771 if (Op == UnknownValue) return Op;
2772 if (Op == Cast->getOperand())
2773 return Cast; // must be loop invariant
2774 return getTruncateExpr(Op, Cast->getType());
2775 }
2776
2777 assert(0 && "Unknown SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002778}
2779
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002780/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2781/// at the specified scope in the program. The L value specifies a loop
2782/// nest to evaluate the expression at, where null is the top-level or a
2783/// specified loop is immediately inside of the loop.
2784///
2785/// This method can be used to compute the exit value for a variable defined
2786/// in a loop by querying what the value will hold in the parent loop.
2787///
2788/// If this value is not computable at this scope, a SCEVCouldNotCompute
2789/// object is returned.
2790SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2791 return getSCEVAtScope(getSCEV(V), L);
2792}
2793
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002794/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2795/// following equation:
2796///
2797/// A * X = B (mod N)
2798///
2799/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2800/// A and B isn't important.
2801///
2802/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2803static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2804 ScalarEvolution &SE) {
2805 uint32_t BW = A.getBitWidth();
2806 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2807 assert(A != 0 && "A must be non-zero.");
2808
2809 // 1. D = gcd(A, N)
2810 //
2811 // The gcd of A and N may have only one prime factor: 2. The number of
2812 // trailing zeros in A is its multiplicity
2813 uint32_t Mult2 = A.countTrailingZeros();
2814 // D = 2^Mult2
2815
2816 // 2. Check if B is divisible by D.
2817 //
2818 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2819 // is not less than multiplicity of this prime factor for D.
2820 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002821 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002822
2823 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2824 // modulo (N / D).
2825 //
2826 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2827 // bit width during computations.
2828 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2829 APInt Mod(BW + 1, 0);
2830 Mod.set(BW - Mult2); // Mod = N / D
2831 APInt I = AD.multiplicativeInverse(Mod);
2832
2833 // 4. Compute the minimum unsigned root of the equation:
2834 // I * (B / D) mod (N / D)
2835 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2836
2837 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2838 // bits.
2839 return SE.getConstant(Result.trunc(BW));
2840}
Chris Lattner53e677a2004-04-02 20:23:17 +00002841
2842/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2843/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2844/// might be the same) or two SCEVCouldNotCompute objects.
2845///
2846static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman246b2562007-10-22 18:31:58 +00002847SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002848 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Reid Spencere8019bb2007-03-01 07:25:48 +00002849 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2850 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2851 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002852
Chris Lattner53e677a2004-04-02 20:23:17 +00002853 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00002854 if (!LC || !MC || !NC) {
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002855 SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00002856 return std::make_pair(CNC, CNC);
2857 }
2858
Reid Spencere8019bb2007-03-01 07:25:48 +00002859 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00002860 const APInt &L = LC->getValue()->getValue();
2861 const APInt &M = MC->getValue()->getValue();
2862 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00002863 APInt Two(BitWidth, 2);
2864 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002865
Reid Spencere8019bb2007-03-01 07:25:48 +00002866 {
2867 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00002868 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00002869 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2870 // The B coefficient is M-N/2
2871 APInt B(M);
2872 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002873
Reid Spencere8019bb2007-03-01 07:25:48 +00002874 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00002875 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00002876
Reid Spencere8019bb2007-03-01 07:25:48 +00002877 // Compute the B^2-4ac term.
2878 APInt SqrtTerm(B);
2879 SqrtTerm *= B;
2880 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00002881
Reid Spencere8019bb2007-03-01 07:25:48 +00002882 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2883 // integer value or else APInt::sqrt() will assert.
2884 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002885
Reid Spencere8019bb2007-03-01 07:25:48 +00002886 // Compute the two solutions for the quadratic formula.
2887 // The divisions must be performed as signed divisions.
2888 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00002889 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00002890 if (TwoA.isMinValue()) {
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002891 SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00002892 return std::make_pair(CNC, CNC);
2893 }
2894
Reid Spencere8019bb2007-03-01 07:25:48 +00002895 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2896 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002897
Dan Gohman246b2562007-10-22 18:31:58 +00002898 return std::make_pair(SE.getConstant(Solution1),
2899 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00002900 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00002901}
2902
2903/// HowFarToZero - Return the number of times a backedge comparing the specified
2904/// value to zero will execute. If not computable, return UnknownValue
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002905SCEVHandle ScalarEvolution::HowFarToZero(SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002906 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00002907 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002908 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00002909 if (C->getValue()->isZero()) return C;
Chris Lattner53e677a2004-04-02 20:23:17 +00002910 return UnknownValue; // Otherwise it will loop infinitely.
2911 }
2912
2913 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2914 if (!AddRec || AddRec->getLoop() != L)
2915 return UnknownValue;
2916
2917 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002918 // If this is an affine expression, the execution count of this branch is
2919 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00002920 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002921 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00002922 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002923 // equivalent to:
2924 //
2925 // Step*N = -Start (mod 2^BW)
2926 //
2927 // where BW is the common bit width of Start and Step.
2928
Chris Lattner53e677a2004-04-02 20:23:17 +00002929 // Get the initial value for the loop.
2930 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002931 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002932
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002933 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002934
Dan Gohman622ed672009-05-04 22:02:23 +00002935 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002936 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00002937
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002938 // First, handle unitary steps.
2939 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002940 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002941 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2942 return Start; // N = Start (as unsigned)
2943
2944 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00002945 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002946 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002947 -StartC->getValue()->getValue(),
2948 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00002949 }
Chris Lattner42a75512007-01-15 02:27:26 +00002950 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002951 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2952 // the quadratic equation to solve it.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002953 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
2954 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00002955 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2956 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2957 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002958#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002959 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
2960 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002961#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002962 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002963 if (ConstantInt *CB =
2964 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002965 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002966 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002967 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002968
Chris Lattner53e677a2004-04-02 20:23:17 +00002969 // We can only use this value if the chrec ends up with an exact zero
2970 // value at this index. When solving for "X*X != 5", for example, we
2971 // should not accept a root of 2.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002972 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002973 if (Val->isZero())
2974 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00002975 }
2976 }
2977 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002978
Chris Lattner53e677a2004-04-02 20:23:17 +00002979 return UnknownValue;
2980}
2981
2982/// HowFarToNonZero - Return the number of times a backedge checking the
2983/// specified value for nonzero will execute. If not computable, return
2984/// UnknownValue
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002985SCEVHandle ScalarEvolution::HowFarToNonZero(SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002986 // Loops that look like: while (X == 0) are very strange indeed. We don't
2987 // handle them yet except for the trivial case. This could be expanded in the
2988 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002989
Chris Lattner53e677a2004-04-02 20:23:17 +00002990 // If the value is a constant, check to see if it is known to be non-zero
2991 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00002992 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00002993 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002994 return getIntegerSCEV(0, C->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002995 return UnknownValue; // Otherwise it will loop infinitely.
2996 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002997
Chris Lattner53e677a2004-04-02 20:23:17 +00002998 // We could implement others, but I really doubt anyone writes loops like
2999 // this, and if they did, they would already be constant folded.
3000 return UnknownValue;
3001}
3002
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003003/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3004/// (which may not be an immediate predecessor) which has exactly one
3005/// successor from which BB is reachable, or null if no such block is
3006/// found.
3007///
3008BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003009ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00003010 // If the block has a unique predecessor, then there is no path from the
3011 // predecessor to the block that does not go through the direct edge
3012 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003013 if (BasicBlock *Pred = BB->getSinglePredecessor())
3014 return Pred;
3015
3016 // A loop's header is defined to be a block that dominates the loop.
3017 // If the loop has a preheader, it must be a block that has exactly
3018 // one successor that can reach BB. This is slightly more strict
3019 // than necessary, but works if critical edges are split.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003020 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003021 return L->getLoopPreheader();
3022
3023 return 0;
3024}
3025
Dan Gohmanc2390b12009-02-12 22:19:27 +00003026/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman3d739fe2009-04-30 20:48:53 +00003027/// a conditional between LHS and RHS. This is used to help avoid max
3028/// expressions in loop trip counts.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003029bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman3d739fe2009-04-30 20:48:53 +00003030 ICmpInst::Predicate Pred,
3031 SCEV *LHS, SCEV *RHS) {
Nick Lewycky59cff122008-07-12 07:41:32 +00003032 BasicBlock *Preheader = L->getLoopPreheader();
3033 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00003034
Dan Gohman38372182008-08-12 20:17:31 +00003035 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003036 // there are predecessors that can be found that have unique successors
3037 // leading to the original header.
3038 for (; Preheader;
3039 PreheaderDest = Preheader,
3040 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohman38372182008-08-12 20:17:31 +00003041
3042 BranchInst *LoopEntryPredicate =
Nick Lewycky59cff122008-07-12 07:41:32 +00003043 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00003044 if (!LoopEntryPredicate ||
3045 LoopEntryPredicate->isUnconditional())
3046 continue;
3047
3048 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3049 if (!ICI) continue;
3050
3051 // Now that we found a conditional branch that dominates the loop, check to
3052 // see if it is the comparison we are looking for.
3053 Value *PreCondLHS = ICI->getOperand(0);
3054 Value *PreCondRHS = ICI->getOperand(1);
3055 ICmpInst::Predicate Cond;
3056 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3057 Cond = ICI->getPredicate();
3058 else
3059 Cond = ICI->getInversePredicate();
3060
Dan Gohmanc2390b12009-02-12 22:19:27 +00003061 if (Cond == Pred)
3062 ; // An exact match.
3063 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3064 ; // The actual condition is beyond sufficient.
3065 else
3066 // Check a few special cases.
3067 switch (Cond) {
3068 case ICmpInst::ICMP_UGT:
3069 if (Pred == ICmpInst::ICMP_ULT) {
3070 std::swap(PreCondLHS, PreCondRHS);
3071 Cond = ICmpInst::ICMP_ULT;
3072 break;
3073 }
3074 continue;
3075 case ICmpInst::ICMP_SGT:
3076 if (Pred == ICmpInst::ICMP_SLT) {
3077 std::swap(PreCondLHS, PreCondRHS);
3078 Cond = ICmpInst::ICMP_SLT;
3079 break;
3080 }
3081 continue;
3082 case ICmpInst::ICMP_NE:
3083 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3084 // so check for this case by checking if the NE is comparing against
3085 // a minimum or maximum constant.
3086 if (!ICmpInst::isTrueWhenEqual(Pred))
3087 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3088 const APInt &A = CI->getValue();
3089 switch (Pred) {
3090 case ICmpInst::ICMP_SLT:
3091 if (A.isMaxSignedValue()) break;
3092 continue;
3093 case ICmpInst::ICMP_SGT:
3094 if (A.isMinSignedValue()) break;
3095 continue;
3096 case ICmpInst::ICMP_ULT:
3097 if (A.isMaxValue()) break;
3098 continue;
3099 case ICmpInst::ICMP_UGT:
3100 if (A.isMinValue()) break;
3101 continue;
3102 default:
3103 continue;
3104 }
3105 Cond = ICmpInst::ICMP_NE;
3106 // NE is symmetric but the original comparison may not be. Swap
3107 // the operands if necessary so that they match below.
3108 if (isa<SCEVConstant>(LHS))
3109 std::swap(PreCondLHS, PreCondRHS);
3110 break;
3111 }
3112 continue;
3113 default:
3114 // We weren't able to reconcile the condition.
3115 continue;
3116 }
Dan Gohman38372182008-08-12 20:17:31 +00003117
3118 if (!PreCondLHS->getType()->isInteger()) continue;
3119
3120 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3121 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3122 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003123 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3124 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohman38372182008-08-12 20:17:31 +00003125 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00003126 }
3127
Dan Gohman38372182008-08-12 20:17:31 +00003128 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00003129}
3130
Chris Lattnerdb25de42005-08-15 23:33:51 +00003131/// HowManyLessThans - Return the number of times a backedge containing the
3132/// specified less-than comparison will execute. If not computable, return
3133/// UnknownValue.
Dan Gohmana1af7572009-04-30 20:47:05 +00003134ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Nick Lewycky789558d2009-01-13 09:18:58 +00003135HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00003136 // Only handle: "ADDREC < LoopInvariant".
3137 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3138
3139 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
3140 if (!AddRec || AddRec->getLoop() != L)
3141 return UnknownValue;
3142
3143 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00003144 // FORNOW: We only support unit strides.
Dan Gohmana1af7572009-04-30 20:47:05 +00003145 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3146 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3147 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3148
3149 // TODO: handle non-constant strides.
3150 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3151 if (!CStep || CStep->isZero())
3152 return UnknownValue;
3153 if (CStep->getValue()->getValue() == 1) {
3154 // With unit stride, the iteration never steps past the limit value.
3155 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3156 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3157 // Test whether a positive iteration iteration can step past the limit
3158 // value and past the maximum value for its type in a single step.
3159 if (isSigned) {
3160 APInt Max = APInt::getSignedMaxValue(BitWidth);
3161 if ((Max - CStep->getValue()->getValue())
3162 .slt(CLimit->getValue()->getValue()))
3163 return UnknownValue;
3164 } else {
3165 APInt Max = APInt::getMaxValue(BitWidth);
3166 if ((Max - CStep->getValue()->getValue())
3167 .ult(CLimit->getValue()->getValue()))
3168 return UnknownValue;
3169 }
3170 } else
3171 // TODO: handle non-constant limit values below.
3172 return UnknownValue;
3173 } else
3174 // TODO: handle negative strides below.
Chris Lattnerdb25de42005-08-15 23:33:51 +00003175 return UnknownValue;
3176
Dan Gohmana1af7572009-04-30 20:47:05 +00003177 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3178 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3179 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00003180 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00003181
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00003182 // First, we get the value of the LHS in the first iteration: n
3183 SCEVHandle Start = AddRec->getOperand(0);
3184
Dan Gohmana1af7572009-04-30 20:47:05 +00003185 // Determine the minimum constant start value.
3186 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3187 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3188 APInt::getMinValue(BitWidth));
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00003189
Dan Gohmana1af7572009-04-30 20:47:05 +00003190 // If we know that the condition is true in order to enter the loop,
3191 // then we know that it will run exactly (m-n)/s times. Otherwise, we
3192 // only know if will execute (max(m,n)-n)/s times. In both cases, the
3193 // division must round up.
3194 SCEVHandle End = RHS;
3195 if (!isLoopGuardedByCond(L,
3196 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3197 getMinusSCEV(Start, Step), RHS))
3198 End = isSigned ? getSMaxExpr(RHS, Start)
3199 : getUMaxExpr(RHS, Start);
3200
3201 // Determine the maximum constant end value.
3202 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3203 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3204 APInt::getMaxValue(BitWidth));
3205
3206 // Finally, we subtract these two values and divide, rounding up, to get
3207 // the number of times the backedge is executed.
3208 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3209 getAddExpr(Step, NegOne)),
3210 Step);
3211
3212 // The maximum backedge count is similar, except using the minimum start
3213 // value and the maximum end value.
3214 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3215 MinStart),
3216 getAddExpr(Step, NegOne)),
3217 Step);
3218
3219 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00003220 }
3221
3222 return UnknownValue;
3223}
3224
Chris Lattner53e677a2004-04-02 20:23:17 +00003225/// getNumIterationsInRange - Return the number of iterations of this loop that
3226/// produce values in the specified constant range. Another way of looking at
3227/// this is that it returns the first iteration number where the value is not in
3228/// the condition, thus computing the exit count. If the iteration count can't
3229/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman246b2562007-10-22 18:31:58 +00003230SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3231 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00003232 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003233 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003234
3235 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00003236 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00003237 if (!SC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003238 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00003239 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3240 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00003241 if (const SCEVAddRecExpr *ShiftedAddRec =
3242 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00003243 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00003244 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00003245 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003246 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003247 }
3248
3249 // The only time we can solve this is when we have all constant indices.
3250 // Otherwise, we cannot determine the overflow conditions.
3251 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3252 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003253 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003254
3255
3256 // Okay at this point we know that all elements of the chrec are constants and
3257 // that the start element is zero.
3258
3259 // First check to see if the range contains zero. If not, the first
3260 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003261 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00003262 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman246b2562007-10-22 18:31:58 +00003263 return SE.getConstant(ConstantInt::get(getType(),0));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003264
Chris Lattner53e677a2004-04-02 20:23:17 +00003265 if (isAffine()) {
3266 // If this is an affine expression then we have this situation:
3267 // Solve {0,+,A} in Range === Ax in Range
3268
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003269 // We know that zero is in the range. If A is positive then we know that
3270 // the upper value of the range must be the first possible exit value.
3271 // If A is negative then the lower of the range is the last possible loop
3272 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00003273 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003274 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3275 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00003276
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003277 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00003278 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00003279 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00003280
3281 // Evaluate at the exit value. If we really did fall out of the valid
3282 // range, then we computed our trip count, otherwise wrap around or other
3283 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00003284 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003285 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003286 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003287
3288 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00003289 assert(Range.contains(
3290 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003291 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00003292 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00003293 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00003294 } else if (isQuadratic()) {
3295 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3296 // quadratic equation to solve it. To do this, we must frame our problem in
3297 // terms of figuring out when zero is crossed, instead of when
3298 // Range.getUpper() is crossed.
3299 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00003300 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3301 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003302
3303 // Next, solve the constructed addrec
3304 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00003305 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00003306 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3307 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3308 if (R1) {
3309 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003310 if (ConstantInt *CB =
3311 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003312 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00003313 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00003314 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003315
Chris Lattner53e677a2004-04-02 20:23:17 +00003316 // Make sure the root is not off by one. The returned iteration should
3317 // not be in the range, but the previous one should be. When solving
3318 // for "X*X < 5", for example, we should not return a root of 2.
3319 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003320 R1->getValue(),
3321 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003322 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003323 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00003324 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003325
Dan Gohman246b2562007-10-22 18:31:58 +00003326 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003327 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00003328 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003329 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003330 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003331
Chris Lattner53e677a2004-04-02 20:23:17 +00003332 // If R1 was not in the range, then it is a good return value. Make
3333 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00003334 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00003335 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003336 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00003337 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003338 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003339 }
3340 }
3341 }
3342
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003343 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003344}
3345
3346
3347
3348//===----------------------------------------------------------------------===//
3349// ScalarEvolution Class Implementation
3350//===----------------------------------------------------------------------===//
3351
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003352ScalarEvolution::ScalarEvolution()
3353 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3354}
3355
Chris Lattner53e677a2004-04-02 20:23:17 +00003356bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003357 this->F = &F;
3358 LI = &getAnalysis<LoopInfo>();
3359 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00003360 return false;
3361}
3362
3363void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003364 Scalars.clear();
3365 BackedgeTakenCounts.clear();
3366 ConstantEvolutionLoopExitValue.clear();
Chris Lattner53e677a2004-04-02 20:23:17 +00003367}
3368
3369void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3370 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00003371 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +00003372}
3373
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003374bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00003375 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00003376}
3377
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003378static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00003379 const Loop *L) {
3380 // Print all inner loops first
3381 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3382 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003383
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003384 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003385
Devang Patelb7211a22007-08-21 00:31:24 +00003386 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003387 L->getExitBlocks(ExitBlocks);
3388 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003389 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003390
Dan Gohman46bdfb02009-02-24 18:55:53 +00003391 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3392 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003393 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00003394 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003395 }
3396
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003397 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00003398}
3399
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003400void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003401 // ScalarEvolution's implementaiton of the print method is to print
3402 // out SCEV values of all instructions that are interesting. Doing
3403 // this potentially causes it to create new SCEV objects though,
3404 // which technically conflicts with the const qualifier. This isn't
3405 // observable from outside the class though (the hasSCEV function
3406 // notwithstanding), so casting away the const isn't dangerous.
3407 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003408
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003409 OS << "Classifying expressions for: " << F->getName() << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00003410 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00003411 if (isSCEVable(I->getType())) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00003412 OS << *I;
Dan Gohman8dae1382008-09-14 17:21:12 +00003413 OS << " --> ";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003414 SCEVHandle SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00003415 SV->print(OS);
3416 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003417
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003418 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003419 OS << "Exits: ";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003420 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003421 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3422 OS << "<<Unknown>>";
3423 } else {
3424 OS << *ExitValue;
3425 }
3426 }
3427
3428
3429 OS << "\n";
3430 }
3431
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003432 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3433 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3434 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00003435}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003436
3437void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3438 raw_os_ostream OS(o);
3439 print(OS, M);
3440}