blob: a71db865cbf68b644416d9e961e51cf3ab5d1c08 [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 Lattner95255282006-06-28 23:17:24 +000073#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000074#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000075#include "llvm/Support/ConstantRange.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000076#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000077#include "llvm/Support/InstIterator.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000078#include "llvm/Support/ManagedStatic.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000079#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000080#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000081#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000082#include "llvm/ADT/STLExtras.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000083#include <ostream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000084#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000085using namespace llvm;
86
Chris Lattner3b27d682006-12-19 22:30:33 +000087STATISTIC(NumArrayLenItCounts,
88 "Number of trip counts computed with array length");
89STATISTIC(NumTripCountsComputed,
90 "Number of loops with predictable loop counts");
91STATISTIC(NumTripCountsNotComputed,
92 "Number of loops without predictable loop counts");
93STATISTIC(NumBruteForceTripCountsComputed,
94 "Number of loops with trip counts computed by force");
95
Dan Gohman844731a2008-05-13 00:00:25 +000096static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +000097MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
98 cl::desc("Maximum number of iterations SCEV will "
99 "symbolically execute a constant derived loop"),
100 cl::init(100));
101
Dan Gohman844731a2008-05-13 00:00:25 +0000102static RegisterPass<ScalarEvolution>
103R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000104char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000105
106//===----------------------------------------------------------------------===//
107// SCEV class definitions
108//===----------------------------------------------------------------------===//
109
110//===----------------------------------------------------------------------===//
111// Implementation of the SCEV class.
112//
Chris Lattner53e677a2004-04-02 20:23:17 +0000113SCEV::~SCEV() {}
114void SCEV::dump() const {
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000115 print(errs());
116 errs() << '\n';
117}
118
119void SCEV::print(std::ostream &o) const {
120 raw_os_ostream OS(o);
121 print(OS);
Chris Lattner53e677a2004-04-02 20:23:17 +0000122}
123
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000124bool SCEV::isZero() const {
125 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
126 return SC->getValue()->isZero();
127 return false;
128}
129
Chris Lattner53e677a2004-04-02 20:23:17 +0000130
131SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
Dan Gohmanf8a8be82009-04-21 23:15:49 +0000132SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
Chris Lattner53e677a2004-04-02 20:23:17 +0000133
134bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
135 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000136 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000137}
138
139const Type *SCEVCouldNotCompute::getType() const {
140 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000141 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000142}
143
144bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
145 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
146 return false;
147}
148
Chris Lattner4dc534c2005-02-13 04:37:18 +0000149SCEVHandle SCEVCouldNotCompute::
150replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000151 const SCEVHandle &Conc,
152 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000153 return this;
154}
155
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000156void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000157 OS << "***COULDNOTCOMPUTE***";
158}
159
160bool SCEVCouldNotCompute::classof(const SCEV *S) {
161 return S->getSCEVType() == scCouldNotCompute;
162}
163
164
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000165// SCEVConstants - Only allow the creation of one SCEVConstant for any
166// particular value. Don't use a SCEVHandle here, or else the object will
167// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000168static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000169
Chris Lattner53e677a2004-04-02 20:23:17 +0000170
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000171SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000172 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000173}
Chris Lattner53e677a2004-04-02 20:23:17 +0000174
Dan Gohman246b2562007-10-22 18:31:58 +0000175SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Chris Lattnerb3364092006-10-04 21:49:37 +0000176 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000177 if (R == 0) R = new SCEVConstant(V);
178 return R;
179}
Chris Lattner53e677a2004-04-02 20:23:17 +0000180
Dan Gohman246b2562007-10-22 18:31:58 +0000181SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
182 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000183}
184
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000185const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000186
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000187void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000188 WriteAsOperand(OS, V, false);
189}
Chris Lattner53e677a2004-04-02 20:23:17 +0000190
Dan Gohman84923602009-04-21 01:25:57 +0000191SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
192 const SCEVHandle &op, const Type *ty)
193 : SCEV(SCEVTy), Op(op), Ty(ty) {}
194
195SCEVCastExpr::~SCEVCastExpr() {}
196
197bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
198 return Op->dominates(BB, DT);
199}
200
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000201// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
202// particular input. Don't use a SCEVHandle here, or else the object will
203// never be deleted!
Dan Gohman35738ac2009-05-04 22:30:44 +0000204static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Chris Lattnerb3364092006-10-04 21:49:37 +0000205 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000206
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000207SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman84923602009-04-21 01:25:57 +0000208 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000209 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
210 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000211 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000212}
Chris Lattner53e677a2004-04-02 20:23:17 +0000213
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000214SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000215 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000216}
Chris Lattner53e677a2004-04-02 20:23:17 +0000217
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000218void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000219 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000220}
221
222// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
223// particular input. Don't use a SCEVHandle here, or else the object will never
224// be deleted!
Dan Gohman35738ac2009-05-04 22:30:44 +0000225static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Chris Lattnerb3364092006-10-04 21:49:37 +0000226 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000227
228SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman84923602009-04-21 01:25:57 +0000229 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000230 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
231 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000232 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000233}
234
235SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000236 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000237}
238
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000239void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000240 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000241}
242
Dan Gohmand19534a2007-06-15 14:38:12 +0000243// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
244// particular input. Don't use a SCEVHandle here, or else the object will never
245// be deleted!
Dan Gohman35738ac2009-05-04 22:30:44 +0000246static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmand19534a2007-06-15 14:38:12 +0000247 SCEVSignExtendExpr*> > SCEVSignExtends;
248
249SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman84923602009-04-21 01:25:57 +0000250 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000251 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
252 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000253 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000254}
255
256SCEVSignExtendExpr::~SCEVSignExtendExpr() {
257 SCEVSignExtends->erase(std::make_pair(Op, Ty));
258}
259
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000260void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000261 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000262}
263
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000264// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
265// particular input. Don't use a SCEVHandle here, or else the object will never
266// be deleted!
Dan Gohman35738ac2009-05-04 22:30:44 +0000267static ManagedStatic<std::map<std::pair<unsigned, std::vector<const SCEV*> >,
Chris Lattnerb3364092006-10-04 21:49:37 +0000268 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000269
270SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Dan Gohman35738ac2009-05-04 22:30:44 +0000271 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
272 SCEVCommExprs->erase(std::make_pair(getSCEVType(), SCEVOps));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000273}
274
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000275void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000276 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
277 const char *OpStr = getOperationStr();
278 OS << "(" << *Operands[0];
279 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
280 OS << OpStr << *Operands[i];
281 OS << ")";
282}
283
Chris Lattner4dc534c2005-02-13 04:37:18 +0000284SCEVHandle SCEVCommutativeExpr::
285replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000286 const SCEVHandle &Conc,
287 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000288 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000289 SCEVHandle H =
290 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000291 if (H != getOperand(i)) {
292 std::vector<SCEVHandle> NewOps;
293 NewOps.reserve(getNumOperands());
294 for (unsigned j = 0; j != i; ++j)
295 NewOps.push_back(getOperand(j));
296 NewOps.push_back(H);
297 for (++i; i != e; ++i)
298 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000299 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000300
301 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000302 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000303 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000304 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000305 else if (isa<SCEVSMaxExpr>(this))
306 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000307 else if (isa<SCEVUMaxExpr>(this))
308 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000309 else
310 assert(0 && "Unknown commutative expr!");
311 }
312 }
313 return this;
314}
315
Dan Gohmanecb403a2009-05-07 14:00:19 +0000316bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000317 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
318 if (!getOperand(i)->dominates(BB, DT))
319 return false;
320 }
321 return true;
322}
323
Chris Lattner4dc534c2005-02-13 04:37:18 +0000324
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000325// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000326// input. Don't use a SCEVHandle here, or else the object will never be
327// deleted!
Dan Gohman35738ac2009-05-04 22:30:44 +0000328static ManagedStatic<std::map<std::pair<const SCEV*, const SCEV*>,
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000329 SCEVUDivExpr*> > SCEVUDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000330
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000331SCEVUDivExpr::~SCEVUDivExpr() {
332 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000333}
334
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000335bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
336 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
337}
338
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000339void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000340 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000341}
342
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000343const Type *SCEVUDivExpr::getType() const {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000344 return LHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000345}
346
347// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
348// particular input. Don't use a SCEVHandle here, or else the object will never
349// be deleted!
Dan Gohman35738ac2009-05-04 22:30:44 +0000350static ManagedStatic<std::map<std::pair<const Loop *,
351 std::vector<const SCEV*> >,
Chris Lattnerb3364092006-10-04 21:49:37 +0000352 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000353
354SCEVAddRecExpr::~SCEVAddRecExpr() {
Dan Gohman35738ac2009-05-04 22:30:44 +0000355 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
356 SCEVAddRecExprs->erase(std::make_pair(L, SCEVOps));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000357}
358
Chris Lattner4dc534c2005-02-13 04:37:18 +0000359SCEVHandle SCEVAddRecExpr::
360replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000361 const SCEVHandle &Conc,
362 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000363 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000364 SCEVHandle H =
365 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000366 if (H != getOperand(i)) {
367 std::vector<SCEVHandle> NewOps;
368 NewOps.reserve(getNumOperands());
369 for (unsigned j = 0; j != i; ++j)
370 NewOps.push_back(getOperand(j));
371 NewOps.push_back(H);
372 for (++i; i != e; ++i)
373 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000374 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000375
Dan Gohman246b2562007-10-22 18:31:58 +0000376 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000377 }
378 }
379 return this;
380}
381
382
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000383bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
384 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000385 // contain L and if the start is invariant.
386 return !QueryLoop->contains(L->getHeader()) &&
387 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000388}
389
390
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000391void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000392 OS << "{" << *Operands[0];
393 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
394 OS << ",+," << *Operands[i];
395 OS << "}<" << L->getHeader()->getName() + ">";
396}
Chris Lattner53e677a2004-04-02 20:23:17 +0000397
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000398// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
399// value. Don't use a SCEVHandle here, or else the object will never be
400// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000401static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000402
Chris Lattnerb3364092006-10-04 21:49:37 +0000403SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000404
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000405bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
406 // All non-instruction values are loop invariant. All instructions are loop
407 // invariant if they are not contained in the specified loop.
408 if (Instruction *I = dyn_cast<Instruction>(V))
409 return !L->contains(I->getParent());
410 return true;
411}
Chris Lattner53e677a2004-04-02 20:23:17 +0000412
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000413bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
414 if (Instruction *I = dyn_cast<Instruction>(getValue()))
415 return DT->dominates(I->getParent(), BB);
416 return true;
417}
418
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000419const Type *SCEVUnknown::getType() const {
420 return V->getType();
421}
Chris Lattner53e677a2004-04-02 20:23:17 +0000422
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000423void SCEVUnknown::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000424 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000425}
426
Chris Lattner8d741b82004-06-20 06:23:15 +0000427//===----------------------------------------------------------------------===//
428// SCEV Utilities
429//===----------------------------------------------------------------------===//
430
431namespace {
432 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
433 /// than the complexity of the RHS. This comparator is used to canonicalize
434 /// expressions.
Dan Gohman72861302009-05-07 14:39:04 +0000435 class VISIBILITY_HIDDEN SCEVComplexityCompare {
436 LoopInfo *LI;
437 public:
438 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
439
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000440 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman72861302009-05-07 14:39:04 +0000441 // Primarily, sort the SCEVs by their getSCEVType().
442 if (LHS->getSCEVType() != RHS->getSCEVType())
443 return LHS->getSCEVType() < RHS->getSCEVType();
444
445 // Aside from the getSCEVType() ordering, the particular ordering
446 // isn't very important except that it's beneficial to be consistent,
447 // so that (a + b) and (b + a) don't end up as different expressions.
448
449 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
450 // not as complete as it could be.
451 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
452 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
453
454 // Compare getValueID values.
455 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
456 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
457
458 // Sort arguments by their position.
459 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
460 const Argument *RA = cast<Argument>(RU->getValue());
461 return LA->getArgNo() < RA->getArgNo();
462 }
463
464 // For instructions, compare their loop depth, and their opcode.
465 // This is pretty loose.
466 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
467 Instruction *RV = cast<Instruction>(RU->getValue());
468
469 // Compare loop depths.
470 if (LI->getLoopDepth(LV->getParent()) !=
471 LI->getLoopDepth(RV->getParent()))
472 return LI->getLoopDepth(LV->getParent()) <
473 LI->getLoopDepth(RV->getParent());
474
475 // Compare opcodes.
476 if (LV->getOpcode() != RV->getOpcode())
477 return LV->getOpcode() < RV->getOpcode();
478
479 // Compare the number of operands.
480 if (LV->getNumOperands() != RV->getNumOperands())
481 return LV->getNumOperands() < RV->getNumOperands();
482 }
483
484 return false;
485 }
486
487 // Constant sorting doesn't matter since they'll be folded.
488 if (isa<SCEVConstant>(LHS))
489 return false;
490
491 // Lexicographically compare n-ary expressions.
492 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
493 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
494 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
495 if (i >= RC->getNumOperands())
496 return false;
497 if (operator()(LC->getOperand(i), RC->getOperand(i)))
498 return true;
499 if (operator()(RC->getOperand(i), LC->getOperand(i)))
500 return false;
501 }
502 return LC->getNumOperands() < RC->getNumOperands();
503 }
504
Dan Gohmana6b35e22009-05-07 19:23:21 +0000505 // Lexicographically compare udiv expressions.
506 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
507 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
508 if (operator()(LC->getLHS(), RC->getLHS()))
509 return true;
510 if (operator()(RC->getLHS(), LC->getLHS()))
511 return false;
512 if (operator()(LC->getRHS(), RC->getRHS()))
513 return true;
514 if (operator()(RC->getRHS(), LC->getRHS()))
515 return false;
516 return false;
517 }
518
Dan Gohman72861302009-05-07 14:39:04 +0000519 // Compare cast expressions by operand.
520 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
521 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
522 return operator()(LC->getOperand(), RC->getOperand());
523 }
524
525 assert(0 && "Unknown SCEV kind!");
526 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000527 }
528 };
529}
530
531/// GroupByComplexity - Given a list of SCEV objects, order them by their
532/// complexity, and group objects of the same complexity together by value.
533/// When this routine is finished, we know that any duplicates in the vector are
534/// consecutive and that complexity is monotonically increasing.
535///
536/// Note that we go take special precautions to ensure that we get determinstic
537/// results from this routine. In other words, we don't want the results of
538/// this to depend on where the addresses of various SCEV objects happened to
539/// land in memory.
540///
Dan Gohman72861302009-05-07 14:39:04 +0000541static void GroupByComplexity(std::vector<SCEVHandle> &Ops,
542 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000543 if (Ops.size() < 2) return; // Noop
544 if (Ops.size() == 2) {
545 // This is the common case, which also happens to be trivially simple.
546 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000547 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000548 std::swap(Ops[0], Ops[1]);
549 return;
550 }
551
552 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000553 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000554
555 // Now that we are sorted by complexity, group elements of the same
556 // complexity. Note that this is, at worst, N^2, but the vector is likely to
557 // be extremely short in practice. Note that we take this approach because we
558 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000559 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000560 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000561 unsigned Complexity = S->getSCEVType();
562
563 // If there are any objects of the same complexity and same value as this
564 // one, group them.
565 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
566 if (Ops[j] == S) { // Found a duplicate.
567 // Move it to immediately after i'th element.
568 std::swap(Ops[i+1], Ops[j]);
569 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000570 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000571 }
572 }
573 }
574}
575
Chris Lattner53e677a2004-04-02 20:23:17 +0000576
Chris Lattner53e677a2004-04-02 20:23:17 +0000577
578//===----------------------------------------------------------------------===//
579// Simple SCEV method implementations
580//===----------------------------------------------------------------------===//
581
Eli Friedmanb42a6262008-08-04 23:49:06 +0000582/// BinomialCoefficient - Compute BC(It, K). The result has width W.
583// Assume, K > 0.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000584static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedmanb42a6262008-08-04 23:49:06 +0000585 ScalarEvolution &SE,
Dan Gohman2d1be872009-04-16 03:18:22 +0000586 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000587 // Handle the simplest case efficiently.
588 if (K == 1)
589 return SE.getTruncateOrZeroExtend(It, ResultTy);
590
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000591 // We are using the following formula for BC(It, K):
592 //
593 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
594 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000595 // Suppose, W is the bitwidth of the return value. We must be prepared for
596 // overflow. Hence, we must assure that the result of our computation is
597 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
598 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000599 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000600 // However, this code doesn't use exactly that formula; the formula it uses
601 // is something like the following, where T is the number of factors of 2 in
602 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
603 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000604 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000605 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000606 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000607 // This formula is trivially equivalent to the previous formula. However,
608 // this formula can be implemented much more efficiently. The trick is that
609 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
610 // arithmetic. To do exact division in modular arithmetic, all we have
611 // to do is multiply by the inverse. Therefore, this step can be done at
612 // width W.
613 //
614 // The next issue is how to safely do the division by 2^T. The way this
615 // is done is by doing the multiplication step at a width of at least W + T
616 // bits. This way, the bottom W+T bits of the product are accurate. Then,
617 // when we perform the division by 2^T (which is equivalent to a right shift
618 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
619 // truncated out after the division by 2^T.
620 //
621 // In comparison to just directly using the first formula, this technique
622 // is much more efficient; using the first formula requires W * K bits,
623 // but this formula less than W + K bits. Also, the first formula requires
624 // a division step, whereas this formula only requires multiplies and shifts.
625 //
626 // It doesn't matter whether the subtraction step is done in the calculation
627 // width or the input iteration count's width; if the subtraction overflows,
628 // the result must be zero anyway. We prefer here to do it in the width of
629 // the induction variable because it helps a lot for certain cases; CodeGen
630 // isn't smart enough to ignore the overflow, which leads to much less
631 // efficient code if the width of the subtraction is wider than the native
632 // register width.
633 //
634 // (It's possible to not widen at all by pulling out factors of 2 before
635 // the multiplication; for example, K=2 can be calculated as
636 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
637 // extra arithmetic, so it's not an obvious win, and it gets
638 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000639
Eli Friedmanb42a6262008-08-04 23:49:06 +0000640 // Protection from insane SCEVs; this bound is conservative,
641 // but it probably doesn't matter.
642 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000643 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000644
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000645 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000646
Eli Friedmanb42a6262008-08-04 23:49:06 +0000647 // Calculate K! / 2^T and T; we divide out the factors of two before
648 // multiplying for calculating K! / 2^T to avoid overflow.
649 // Other overflow doesn't matter because we only care about the bottom
650 // W bits of the result.
651 APInt OddFactorial(W, 1);
652 unsigned T = 1;
653 for (unsigned i = 3; i <= K; ++i) {
654 APInt Mult(W, i);
655 unsigned TwoFactors = Mult.countTrailingZeros();
656 T += TwoFactors;
657 Mult = Mult.lshr(TwoFactors);
658 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000659 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000660
Eli Friedmanb42a6262008-08-04 23:49:06 +0000661 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000662 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000663
664 // Calcuate 2^T, at width T+W.
665 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
666
667 // Calculate the multiplicative inverse of K! / 2^T;
668 // this multiplication factor will perform the exact division by
669 // K! / 2^T.
670 APInt Mod = APInt::getSignedMinValue(W+1);
671 APInt MultiplyFactor = OddFactorial.zext(W+1);
672 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
673 MultiplyFactor = MultiplyFactor.trunc(W);
674
675 // Calculate the product, at width T+W
676 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
677 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
678 for (unsigned i = 1; i != K; ++i) {
679 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
680 Dividend = SE.getMulExpr(Dividend,
681 SE.getTruncateOrZeroExtend(S, CalculationTy));
682 }
683
684 // Divide by 2^T
685 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
686
687 // Truncate the result, and divide by K! / 2^T.
688
689 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
690 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000691}
692
Chris Lattner53e677a2004-04-02 20:23:17 +0000693/// evaluateAtIteration - Return the value of this chain of recurrences at
694/// the specified iteration number. We can evaluate this recurrence by
695/// multiplying each element in the chain by the binomial coefficient
696/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
697///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000698/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000699///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000700/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000701///
Dan Gohman246b2562007-10-22 18:31:58 +0000702SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
703 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000704 SCEVHandle Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000705 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000706 // The computation is correct in the face of overflow provided that the
707 // multiplication is performed _after_ the evaluation of the binomial
708 // coefficient.
Dan Gohman2d1be872009-04-16 03:18:22 +0000709 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000710 if (isa<SCEVCouldNotCompute>(Coeff))
711 return Coeff;
712
713 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000714 }
715 return Result;
716}
717
Chris Lattner53e677a2004-04-02 20:23:17 +0000718//===----------------------------------------------------------------------===//
719// SCEV Expression folder implementations
720//===----------------------------------------------------------------------===//
721
Dan Gohman99243b32009-05-01 16:44:56 +0000722SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
723 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000724 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000725 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000726 assert(isSCEVable(Ty) &&
727 "This is not a conversion to a SCEVable type!");
728 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000729
Dan Gohman622ed672009-05-04 22:02:23 +0000730 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000731 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000732 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000733
Dan Gohman20900ca2009-04-22 16:20:48 +0000734 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000735 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000736 return getTruncateExpr(ST->getOperand(), Ty);
737
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000738 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000739 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000740 return getTruncateOrSignExtend(SS->getOperand(), Ty);
741
742 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000743 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000744 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
745
Chris Lattner53e677a2004-04-02 20:23:17 +0000746 // If the input value is a chrec scev made out of constants, truncate
747 // all of the constants.
Dan Gohman622ed672009-05-04 22:02:23 +0000748 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000749 std::vector<SCEVHandle> Operands;
750 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000751 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
752 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000753 }
754
Chris Lattnerb3364092006-10-04 21:49:37 +0000755 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000756 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
757 return Result;
758}
759
Dan Gohman8170a682009-04-16 19:25:55 +0000760SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
761 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000762 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000763 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000764 assert(isSCEVable(Ty) &&
765 "This is not a conversion to a SCEVable type!");
766 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000767
Dan Gohman622ed672009-05-04 22:02:23 +0000768 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000769 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000770 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
771 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
772 return getUnknown(C);
773 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000774
Dan Gohman20900ca2009-04-22 16:20:48 +0000775 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000776 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000777 return getZeroExtendExpr(SZ->getOperand(), Ty);
778
Dan Gohman01ecca22009-04-27 20:16:15 +0000779 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000780 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000781 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000782 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000783 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000784 if (AR->isAffine()) {
785 // Check whether the backedge-taken count is SCEVCouldNotCompute.
786 // Note that this serves two purposes: It filters out loops that are
787 // simply not analyzable, and it covers the case where this code is
788 // being called from within backedge-taken count analysis, such that
789 // attempting to ask for the backedge-taken count would likely result
790 // in infinite recursion. In the later case, the analysis code will
791 // cope with a conservative value, and it will take care to purge
792 // that value once it has finished.
Dan Gohmana1af7572009-04-30 20:47:05 +0000793 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
794 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000795 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000796 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000797 SCEVHandle Start = AR->getStart();
798 SCEVHandle Step = AR->getStepRecurrence(*this);
799
800 // Check whether the backedge-taken count can be losslessly casted to
801 // the addrec's type. The count is always unsigned.
Dan Gohmana1af7572009-04-30 20:47:05 +0000802 SCEVHandle CastedMaxBECount =
803 getTruncateOrZeroExtend(MaxBECount, Start->getType());
804 if (MaxBECount ==
805 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000806 const Type *WideTy =
807 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000808 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000809 SCEVHandle ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000810 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000811 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000812 SCEVHandle Add = getAddExpr(Start, ZMul);
813 if (getZeroExtendExpr(Add, WideTy) ==
814 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmana1af7572009-04-30 20:47:05 +0000815 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohmanac70cea2009-04-29 22:28:28 +0000816 getZeroExtendExpr(Step, WideTy))))
817 // Return the expression with the addrec on the outside.
818 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
819 getZeroExtendExpr(Step, Ty),
820 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000821
822 // Similar to above, only this time treat the step value as signed.
823 // This covers loops that count down.
824 SCEVHandle SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000825 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000826 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000827 Add = getAddExpr(Start, SMul);
828 if (getZeroExtendExpr(Add, WideTy) ==
829 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmana1af7572009-04-30 20:47:05 +0000830 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohmanac70cea2009-04-29 22:28:28 +0000831 getSignExtendExpr(Step, WideTy))))
832 // Return the expression with the addrec on the outside.
833 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
834 getSignExtendExpr(Step, Ty),
835 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000836 }
837 }
838 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000839
Chris Lattnerb3364092006-10-04 21:49:37 +0000840 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000841 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
842 return Result;
843}
844
Dan Gohman01ecca22009-04-27 20:16:15 +0000845SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
846 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000847 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000848 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000849 assert(isSCEVable(Ty) &&
850 "This is not a conversion to a SCEVable type!");
851 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000852
Dan Gohman622ed672009-05-04 22:02:23 +0000853 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000854 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000855 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
856 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
857 return getUnknown(C);
858 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000859
Dan Gohman20900ca2009-04-22 16:20:48 +0000860 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000861 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000862 return getSignExtendExpr(SS->getOperand(), Ty);
863
Dan Gohman01ecca22009-04-27 20:16:15 +0000864 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000865 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000866 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000867 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000868 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000869 if (AR->isAffine()) {
870 // Check whether the backedge-taken count is SCEVCouldNotCompute.
871 // Note that this serves two purposes: It filters out loops that are
872 // simply not analyzable, and it covers the case where this code is
873 // being called from within backedge-taken count analysis, such that
874 // attempting to ask for the backedge-taken count would likely result
875 // in infinite recursion. In the later case, the analysis code will
876 // cope with a conservative value, and it will take care to purge
877 // that value once it has finished.
Dan Gohmana1af7572009-04-30 20:47:05 +0000878 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
879 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000880 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000881 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000882 SCEVHandle Start = AR->getStart();
883 SCEVHandle Step = AR->getStepRecurrence(*this);
884
885 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000886 // the addrec's type. The count is always unsigned.
Dan Gohmana1af7572009-04-30 20:47:05 +0000887 SCEVHandle CastedMaxBECount =
888 getTruncateOrZeroExtend(MaxBECount, Start->getType());
889 if (MaxBECount ==
890 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000891 const Type *WideTy =
892 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000893 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000894 SCEVHandle SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000895 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000896 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000897 SCEVHandle Add = getAddExpr(Start, SMul);
898 if (getSignExtendExpr(Add, WideTy) ==
899 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohmana1af7572009-04-30 20:47:05 +0000900 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohmanac70cea2009-04-29 22:28:28 +0000901 getSignExtendExpr(Step, WideTy))))
902 // Return the expression with the addrec on the outside.
903 return getAddRecExpr(getSignExtendExpr(Start, Ty),
904 getSignExtendExpr(Step, Ty),
905 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000906 }
907 }
908 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000909
910 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
911 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
912 return Result;
913}
914
Chris Lattner53e677a2004-04-02 20:23:17 +0000915// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman246b2562007-10-22 18:31:58 +0000916SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000917 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000918 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000919
920 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +0000921 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +0000922
923 // If there are any constants, fold them together.
924 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +0000925 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000926 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000927 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +0000928 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000929 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000930 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
931 RHSC->getValue()->getValue());
932 Ops[0] = getConstant(Fold);
933 Ops.erase(Ops.begin()+1); // Erase the folded element
934 if (Ops.size() == 1) return Ops[0];
935 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000936 }
937
938 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +0000939 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000940 Ops.erase(Ops.begin());
941 --Idx;
942 }
943 }
944
Chris Lattner627018b2004-04-07 16:16:11 +0000945 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000946
Chris Lattner53e677a2004-04-02 20:23:17 +0000947 // Okay, check to see if the same value occurs in the operand list twice. If
948 // so, merge them together into an multiply expression. Since we sorted the
949 // list, these values are required to be adjacent.
950 const Type *Ty = Ops[0]->getType();
951 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
952 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
953 // Found a match, merge the two values into a multiply, and add any
954 // remaining values to the result.
Dan Gohman246b2562007-10-22 18:31:58 +0000955 SCEVHandle Two = getIntegerSCEV(2, Ty);
956 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +0000957 if (Ops.size() == 2)
958 return Mul;
959 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
960 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +0000961 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000962 }
963
Dan Gohman728c7f32009-05-08 21:03:19 +0000964 // Check for truncates. If all the operands are truncated from the same
965 // type, see if factoring out the truncate would permit the result to be
966 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
967 // if the contents of the resulting outer trunc fold to something simple.
968 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
969 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
970 const Type *DstType = Trunc->getType();
971 const Type *SrcType = Trunc->getOperand()->getType();
972 std::vector<SCEVHandle> LargeOps;
973 bool Ok = true;
974 // Check all the operands to see if they can be represented in the
975 // source type of the truncate.
976 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
977 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
978 if (T->getOperand()->getType() != SrcType) {
979 Ok = false;
980 break;
981 }
982 LargeOps.push_back(T->getOperand());
983 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
984 // This could be either sign or zero extension, but sign extension
985 // is much more likely to be foldable here.
986 LargeOps.push_back(getSignExtendExpr(C, SrcType));
987 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
988 std::vector<SCEVHandle> LargeMulOps;
989 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
990 if (const SCEVTruncateExpr *T =
991 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
992 if (T->getOperand()->getType() != SrcType) {
993 Ok = false;
994 break;
995 }
996 LargeMulOps.push_back(T->getOperand());
997 } else if (const SCEVConstant *C =
998 dyn_cast<SCEVConstant>(M->getOperand(j))) {
999 // This could be either sign or zero extension, but sign extension
1000 // is much more likely to be foldable here.
1001 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1002 } else {
1003 Ok = false;
1004 break;
1005 }
1006 }
1007 if (Ok)
1008 LargeOps.push_back(getMulExpr(LargeMulOps));
1009 } else {
1010 Ok = false;
1011 break;
1012 }
1013 }
1014 if (Ok) {
1015 // Evaluate the expression in the larger type.
1016 SCEVHandle Fold = getAddExpr(LargeOps);
1017 // If it folds to something simple, use it. Otherwise, don't.
1018 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1019 return getTruncateExpr(Fold, DstType);
1020 }
1021 }
1022
1023 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001024 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1025 ++Idx;
1026
1027 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001028 if (Idx < Ops.size()) {
1029 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001030 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001031 // If we have an add, expand the add operands onto the end of the operands
1032 // list.
1033 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1034 Ops.erase(Ops.begin()+Idx);
1035 DeletedAdd = true;
1036 }
1037
1038 // If we deleted at least one add, we added operands to the end of the list,
1039 // and they are not necessarily sorted. Recurse to resort and resimplify
1040 // any operands we just aquired.
1041 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001042 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001043 }
1044
1045 // Skip over the add expression until we get to a multiply.
1046 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1047 ++Idx;
1048
1049 // If we are adding something to a multiply expression, make sure the
1050 // something is not already an operand of the multiply. If so, merge it into
1051 // the multiply.
1052 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001053 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001054 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001055 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001056 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001057 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001058 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
1059 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
1060 if (Mul->getNumOperands() != 2) {
1061 // If the multiply has more than two operands, we must get the
1062 // Y*Z term.
1063 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1064 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001065 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001066 }
Dan Gohman246b2562007-10-22 18:31:58 +00001067 SCEVHandle One = getIntegerSCEV(1, Ty);
1068 SCEVHandle AddOne = getAddExpr(InnerMul, One);
1069 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001070 if (Ops.size() == 2) return OuterMul;
1071 if (AddOp < Idx) {
1072 Ops.erase(Ops.begin()+AddOp);
1073 Ops.erase(Ops.begin()+Idx-1);
1074 } else {
1075 Ops.erase(Ops.begin()+Idx);
1076 Ops.erase(Ops.begin()+AddOp-1);
1077 }
1078 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001079 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001080 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001081
Chris Lattner53e677a2004-04-02 20:23:17 +00001082 // Check this multiply against other multiplies being added together.
1083 for (unsigned OtherMulIdx = Idx+1;
1084 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1085 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001086 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001087 // If MulOp occurs in OtherMul, we can fold the two multiplies
1088 // together.
1089 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1090 OMulOp != e; ++OMulOp)
1091 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1092 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1093 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1094 if (Mul->getNumOperands() != 2) {
1095 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1096 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001097 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001098 }
1099 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1100 if (OtherMul->getNumOperands() != 2) {
1101 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
1102 OtherMul->op_end());
1103 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001104 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001105 }
Dan Gohman246b2562007-10-22 18:31:58 +00001106 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1107 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001108 if (Ops.size() == 2) return OuterMul;
1109 Ops.erase(Ops.begin()+Idx);
1110 Ops.erase(Ops.begin()+OtherMulIdx-1);
1111 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001112 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001113 }
1114 }
1115 }
1116 }
1117
1118 // If there are any add recurrences in the operands list, see if any other
1119 // added values are loop invariant. If so, we can fold them into the
1120 // recurrence.
1121 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1122 ++Idx;
1123
1124 // Scan over all recurrences, trying to fold loop invariants into them.
1125 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1126 // Scan all of the other operands to this add and add them to the vector if
1127 // they are loop invariant w.r.t. the recurrence.
1128 std::vector<SCEVHandle> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001129 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001130 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1131 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1132 LIOps.push_back(Ops[i]);
1133 Ops.erase(Ops.begin()+i);
1134 --i; --e;
1135 }
1136
1137 // If we found some loop invariants, fold them into the recurrence.
1138 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001139 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001140 LIOps.push_back(AddRec->getStart());
1141
1142 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001143 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001144
Dan Gohman246b2562007-10-22 18:31:58 +00001145 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001146 // If all of the other operands were loop invariant, we are done.
1147 if (Ops.size() == 1) return NewRec;
1148
1149 // Otherwise, add the folded AddRec by the non-liv parts.
1150 for (unsigned i = 0;; ++i)
1151 if (Ops[i] == AddRec) {
1152 Ops[i] = NewRec;
1153 break;
1154 }
Dan Gohman246b2562007-10-22 18:31:58 +00001155 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001156 }
1157
1158 // Okay, if there weren't any loop invariants to be folded, check to see if
1159 // there are multiple AddRec's with the same loop induction variable being
1160 // added together. If so, we can fold them.
1161 for (unsigned OtherIdx = Idx+1;
1162 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1163 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001164 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001165 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1166 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1167 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1168 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1169 if (i >= NewOps.size()) {
1170 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1171 OtherAddRec->op_end());
1172 break;
1173 }
Dan Gohman246b2562007-10-22 18:31:58 +00001174 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001175 }
Dan Gohman246b2562007-10-22 18:31:58 +00001176 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001177
1178 if (Ops.size() == 2) return NewAddRec;
1179
1180 Ops.erase(Ops.begin()+Idx);
1181 Ops.erase(Ops.begin()+OtherIdx-1);
1182 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001183 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001184 }
1185 }
1186
1187 // Otherwise couldn't fold anything into this recurrence. Move onto the
1188 // next one.
1189 }
1190
1191 // Okay, it looks like we really DO need an add expr. Check to see if we
1192 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001193 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001194 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1195 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +00001196 if (Result == 0) Result = new SCEVAddExpr(Ops);
1197 return Result;
1198}
1199
1200
Dan Gohman246b2562007-10-22 18:31:58 +00001201SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001202 assert(!Ops.empty() && "Cannot get empty mul!");
1203
1204 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001205 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001206
1207 // If there are any constants, fold them together.
1208 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001209 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001210
1211 // C1*(C2+V) -> C1*C2 + C1*V
1212 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001213 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001214 if (Add->getNumOperands() == 2 &&
1215 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001216 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1217 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001218
1219
1220 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001221 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001222 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001223 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1224 RHSC->getValue()->getValue());
1225 Ops[0] = getConstant(Fold);
1226 Ops.erase(Ops.begin()+1); // Erase the folded element
1227 if (Ops.size() == 1) return Ops[0];
1228 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001229 }
1230
1231 // If we are left with a constant one being multiplied, strip it off.
1232 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1233 Ops.erase(Ops.begin());
1234 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001235 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001236 // If we have a multiply of zero, it will always be zero.
1237 return Ops[0];
1238 }
1239 }
1240
1241 // Skip over the add expression until we get to a multiply.
1242 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1243 ++Idx;
1244
1245 if (Ops.size() == 1)
1246 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001247
Chris Lattner53e677a2004-04-02 20:23:17 +00001248 // If there are mul operands inline them all into this expression.
1249 if (Idx < Ops.size()) {
1250 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001251 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001252 // If we have an mul, expand the mul operands onto the end of the operands
1253 // list.
1254 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1255 Ops.erase(Ops.begin()+Idx);
1256 DeletedMul = true;
1257 }
1258
1259 // If we deleted at least one mul, we added operands to the end of the list,
1260 // and they are not necessarily sorted. Recurse to resort and resimplify
1261 // any operands we just aquired.
1262 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001263 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001264 }
1265
1266 // If there are any add recurrences in the operands list, see if any other
1267 // added values are loop invariant. If so, we can fold them into the
1268 // recurrence.
1269 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1270 ++Idx;
1271
1272 // Scan over all recurrences, trying to fold loop invariants into them.
1273 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1274 // Scan all of the other operands to this mul and add them to the vector if
1275 // they are loop invariant w.r.t. the recurrence.
1276 std::vector<SCEVHandle> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001277 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001278 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1279 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1280 LIOps.push_back(Ops[i]);
1281 Ops.erase(Ops.begin()+i);
1282 --i; --e;
1283 }
1284
1285 // If we found some loop invariants, fold them into the recurrence.
1286 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001287 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001288 std::vector<SCEVHandle> NewOps;
1289 NewOps.reserve(AddRec->getNumOperands());
1290 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001291 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001292 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001293 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001294 } else {
1295 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1296 std::vector<SCEVHandle> MulOps(LIOps);
1297 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001298 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001299 }
1300 }
1301
Dan Gohman246b2562007-10-22 18:31:58 +00001302 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001303
1304 // If all of the other operands were loop invariant, we are done.
1305 if (Ops.size() == 1) return NewRec;
1306
1307 // Otherwise, multiply the folded AddRec by the non-liv parts.
1308 for (unsigned i = 0;; ++i)
1309 if (Ops[i] == AddRec) {
1310 Ops[i] = NewRec;
1311 break;
1312 }
Dan Gohman246b2562007-10-22 18:31:58 +00001313 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001314 }
1315
1316 // Okay, if there weren't any loop invariants to be folded, check to see if
1317 // there are multiple AddRec's with the same loop induction variable being
1318 // multiplied together. If so, we can fold them.
1319 for (unsigned OtherIdx = Idx+1;
1320 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1321 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001322 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001323 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1324 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001325 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman246b2562007-10-22 18:31:58 +00001326 SCEVHandle NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001327 G->getStart());
Dan Gohman246b2562007-10-22 18:31:58 +00001328 SCEVHandle B = F->getStepRecurrence(*this);
1329 SCEVHandle D = G->getStepRecurrence(*this);
1330 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1331 getMulExpr(G, B),
1332 getMulExpr(B, D));
1333 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1334 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001335 if (Ops.size() == 2) return NewAddRec;
1336
1337 Ops.erase(Ops.begin()+Idx);
1338 Ops.erase(Ops.begin()+OtherIdx-1);
1339 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001340 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001341 }
1342 }
1343
1344 // Otherwise couldn't fold anything into this recurrence. Move onto the
1345 // next one.
1346 }
1347
1348 // Okay, it looks like we really DO need an mul expr. Check to see if we
1349 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001350 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001351 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1352 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001353 if (Result == 0)
1354 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001355 return Result;
1356}
1357
Dan Gohmanbf2176a2009-05-04 22:23:18 +00001358SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1359 const SCEVHandle &RHS) {
Dan Gohman622ed672009-05-04 22:02:23 +00001360 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001361 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky789558d2009-01-13 09:18:58 +00001362 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001363 if (RHSC->isZero())
1364 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001365
Dan Gohman185cf032009-05-08 20:18:49 +00001366 // Determine if the division can be folded into the operands of
1367 // its operands.
1368 // TODO: Generalize this to non-constants by using known-bits information.
1369 const Type *Ty = LHS->getType();
1370 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1371 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1372 // For non-power-of-two values, effectively round the value up to the
1373 // nearest power of two.
1374 if (!RHSC->getValue()->getValue().isPowerOf2())
1375 ++MaxShiftAmt;
1376 const IntegerType *ExtTy =
1377 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1378 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1379 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1380 if (const SCEVConstant *Step =
1381 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1382 if (!Step->getValue()->getValue()
1383 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001384 getZeroExtendExpr(AR, ExtTy) ==
1385 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1386 getZeroExtendExpr(Step, ExtTy),
1387 AR->getLoop())) {
Dan Gohman185cf032009-05-08 20:18:49 +00001388 std::vector<SCEVHandle> Operands;
1389 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1390 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1391 return getAddRecExpr(Operands, AR->getLoop());
1392 }
1393 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001394 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
1395 std::vector<SCEVHandle> Operands;
1396 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1397 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1398 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001399 // Find an operand that's safely divisible.
1400 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
1401 SCEVHandle Op = M->getOperand(i);
1402 SCEVHandle Div = getUDivExpr(Op, RHSC);
1403 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohmanb0285932009-05-08 23:11:16 +00001404 Operands = M->getOperands();
Dan Gohman185cf032009-05-08 20:18:49 +00001405 Operands[i] = Div;
1406 return getMulExpr(Operands);
1407 }
1408 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001409 }
Dan Gohman185cf032009-05-08 20:18:49 +00001410 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001411 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
1412 std::vector<SCEVHandle> Operands;
1413 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1414 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1415 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1416 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001417 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
1418 SCEVHandle Op = getUDivExpr(A->getOperand(i), RHS);
1419 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1420 break;
1421 Operands.push_back(Op);
1422 }
1423 if (Operands.size() == A->getNumOperands())
1424 return getAddExpr(Operands);
1425 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001426 }
Dan Gohman185cf032009-05-08 20:18:49 +00001427
1428 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001429 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001430 Constant *LHSCV = LHSC->getValue();
1431 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001432 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001433 }
1434 }
1435
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001436 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1437 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001438 return Result;
1439}
1440
1441
1442/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1443/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001444SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Chris Lattner53e677a2004-04-02 20:23:17 +00001445 const SCEVHandle &Step, const Loop *L) {
1446 std::vector<SCEVHandle> Operands;
1447 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001448 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001449 if (StepChrec->getLoop() == L) {
1450 Operands.insert(Operands.end(), StepChrec->op_begin(),
1451 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001452 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001453 }
1454
1455 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001456 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001457}
1458
1459/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1460/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001461SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001462 const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001463 if (Operands.size() == 1) return Operands[0];
1464
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001465 if (Operands.back()->isZero()) {
1466 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001467 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001468 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001469
Dan Gohmand9cc7492008-08-08 18:33:12 +00001470 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001471 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmand9cc7492008-08-08 18:33:12 +00001472 const Loop* NestedLoop = NestedAR->getLoop();
1473 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1474 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1475 NestedAR->op_end());
1476 SCEVHandle NestedARHandle(NestedAR);
1477 Operands[0] = NestedAR->getStart();
1478 NestedOperands[0] = getAddRecExpr(Operands, L);
1479 return getAddRecExpr(NestedOperands, NestedLoop);
1480 }
1481 }
1482
Dan Gohman35738ac2009-05-04 22:30:44 +00001483 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1484 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +00001485 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1486 return Result;
1487}
1488
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001489SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1490 const SCEVHandle &RHS) {
1491 std::vector<SCEVHandle> Ops;
1492 Ops.push_back(LHS);
1493 Ops.push_back(RHS);
1494 return getSMaxExpr(Ops);
1495}
1496
1497SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1498 assert(!Ops.empty() && "Cannot get empty smax!");
1499 if (Ops.size() == 1) return Ops[0];
1500
1501 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001502 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001503
1504 // If there are any constants, fold them together.
1505 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001506 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001507 ++Idx;
1508 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001509 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001510 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001511 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001512 APIntOps::smax(LHSC->getValue()->getValue(),
1513 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001514 Ops[0] = getConstant(Fold);
1515 Ops.erase(Ops.begin()+1); // Erase the folded element
1516 if (Ops.size() == 1) return Ops[0];
1517 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001518 }
1519
1520 // If we are left with a constant -inf, strip it off.
1521 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1522 Ops.erase(Ops.begin());
1523 --Idx;
1524 }
1525 }
1526
1527 if (Ops.size() == 1) return Ops[0];
1528
1529 // Find the first SMax
1530 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1531 ++Idx;
1532
1533 // Check to see if one of the operands is an SMax. If so, expand its operands
1534 // onto our operand list, and recurse to simplify.
1535 if (Idx < Ops.size()) {
1536 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001537 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001538 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1539 Ops.erase(Ops.begin()+Idx);
1540 DeletedSMax = true;
1541 }
1542
1543 if (DeletedSMax)
1544 return getSMaxExpr(Ops);
1545 }
1546
1547 // Okay, check to see if the same value occurs in the operand list twice. If
1548 // so, delete one. Since we sorted the list, these values are required to
1549 // be adjacent.
1550 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1551 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1552 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1553 --i; --e;
1554 }
1555
1556 if (Ops.size() == 1) return Ops[0];
1557
1558 assert(!Ops.empty() && "Reduced smax down to nothing!");
1559
Nick Lewycky3e630762008-02-20 06:48:22 +00001560 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001561 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001562 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001563 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1564 SCEVOps)];
1565 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1566 return Result;
1567}
1568
Nick Lewycky3e630762008-02-20 06:48:22 +00001569SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1570 const SCEVHandle &RHS) {
1571 std::vector<SCEVHandle> Ops;
1572 Ops.push_back(LHS);
1573 Ops.push_back(RHS);
1574 return getUMaxExpr(Ops);
1575}
1576
1577SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1578 assert(!Ops.empty() && "Cannot get empty umax!");
1579 if (Ops.size() == 1) return Ops[0];
1580
1581 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001582 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00001583
1584 // If there are any constants, fold them together.
1585 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001586 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001587 ++Idx;
1588 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001589 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001590 // We found two constants, fold them together!
1591 ConstantInt *Fold = ConstantInt::get(
1592 APIntOps::umax(LHSC->getValue()->getValue(),
1593 RHSC->getValue()->getValue()));
1594 Ops[0] = getConstant(Fold);
1595 Ops.erase(Ops.begin()+1); // Erase the folded element
1596 if (Ops.size() == 1) return Ops[0];
1597 LHSC = cast<SCEVConstant>(Ops[0]);
1598 }
1599
1600 // If we are left with a constant zero, strip it off.
1601 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1602 Ops.erase(Ops.begin());
1603 --Idx;
1604 }
1605 }
1606
1607 if (Ops.size() == 1) return Ops[0];
1608
1609 // Find the first UMax
1610 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1611 ++Idx;
1612
1613 // Check to see if one of the operands is a UMax. If so, expand its operands
1614 // onto our operand list, and recurse to simplify.
1615 if (Idx < Ops.size()) {
1616 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001617 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001618 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1619 Ops.erase(Ops.begin()+Idx);
1620 DeletedUMax = true;
1621 }
1622
1623 if (DeletedUMax)
1624 return getUMaxExpr(Ops);
1625 }
1626
1627 // Okay, check to see if the same value occurs in the operand list twice. If
1628 // so, delete one. Since we sorted the list, these values are required to
1629 // be adjacent.
1630 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1631 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1632 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1633 --i; --e;
1634 }
1635
1636 if (Ops.size() == 1) return Ops[0];
1637
1638 assert(!Ops.empty() && "Reduced umax down to nothing!");
1639
1640 // Okay, it looks like we really DO need a umax expr. Check to see if we
1641 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001642 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewycky3e630762008-02-20 06:48:22 +00001643 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1644 SCEVOps)];
1645 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1646 return Result;
1647}
1648
Dan Gohman246b2562007-10-22 18:31:58 +00001649SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001650 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001651 return getConstant(CI);
Dan Gohman2d1be872009-04-16 03:18:22 +00001652 if (isa<ConstantPointerNull>(V))
1653 return getIntegerSCEV(0, V->getType());
Chris Lattnerb3364092006-10-04 21:49:37 +00001654 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001655 if (Result == 0) Result = new SCEVUnknown(V);
1656 return Result;
1657}
1658
Chris Lattner53e677a2004-04-02 20:23:17 +00001659//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001660// Basic SCEV Analysis and PHI Idiom Recognition Code
1661//
1662
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001663/// isSCEVable - Test if values of the given type are analyzable within
1664/// the SCEV framework. This primarily includes integer types, and it
1665/// can optionally include pointer types if the ScalarEvolution class
1666/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001667bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001668 // Integers are always SCEVable.
1669 if (Ty->isInteger())
1670 return true;
1671
1672 // Pointers are SCEVable if TargetData information is available
1673 // to provide pointer size information.
1674 if (isa<PointerType>(Ty))
1675 return TD != NULL;
1676
1677 // Otherwise it's not SCEVable.
1678 return false;
1679}
1680
1681/// getTypeSizeInBits - Return the size in bits of the specified type,
1682/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001683uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001684 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1685
1686 // If we have a TargetData, use it!
1687 if (TD)
1688 return TD->getTypeSizeInBits(Ty);
1689
1690 // Otherwise, we support only integer types.
1691 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1692 return Ty->getPrimitiveSizeInBits();
1693}
1694
1695/// getEffectiveSCEVType - Return a type with the same bitwidth as
1696/// the given type and which represents how SCEV will treat the given
1697/// type, for which isSCEVable must return true. For pointer types,
1698/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001699const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001700 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1701
1702 if (Ty->isInteger())
1703 return Ty;
1704
1705 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1706 return TD->getIntPtrType();
Dan Gohman2d1be872009-04-16 03:18:22 +00001707}
Chris Lattner53e677a2004-04-02 20:23:17 +00001708
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001709SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00001710 return UnknownValue;
1711}
1712
Dan Gohman92fa56e2009-05-04 22:20:30 +00001713/// hasSCEV - Return true if the SCEV for this value has already been
Torok Edwine3d12852009-05-01 08:33:47 +00001714/// computed.
1715bool ScalarEvolution::hasSCEV(Value *V) const {
1716 return Scalars.count(V);
1717}
1718
Chris Lattner53e677a2004-04-02 20:23:17 +00001719/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1720/// expression and create a new one.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001721SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001722 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00001723
Dan Gohman35738ac2009-05-04 22:30:44 +00001724 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001725 if (I != Scalars.end()) return I->second;
1726 SCEVHandle S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00001727 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00001728 return S;
1729}
1730
Dan Gohman2d1be872009-04-16 03:18:22 +00001731/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1732/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001733SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1734 Ty = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001735 Constant *C;
1736 if (Val == 0)
1737 C = Constant::getNullValue(Ty);
1738 else if (Ty->isFloatingPoint())
1739 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1740 APFloat::IEEEdouble, Val));
1741 else
1742 C = ConstantInt::get(Ty, Val);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001743 return getUnknown(C);
Dan Gohman2d1be872009-04-16 03:18:22 +00001744}
1745
1746/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1747///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001748SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohman622ed672009-05-04 22:02:23 +00001749 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001750 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman2d1be872009-04-16 03:18:22 +00001751
1752 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001753 Ty = getEffectiveSCEVType(Ty);
1754 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00001755}
1756
1757/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001758SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohman622ed672009-05-04 22:02:23 +00001759 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001760 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman2d1be872009-04-16 03:18:22 +00001761
1762 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001763 Ty = getEffectiveSCEVType(Ty);
1764 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman2d1be872009-04-16 03:18:22 +00001765 return getMinusSCEV(AllOnes, V);
1766}
1767
1768/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1769///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001770SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001771 const SCEVHandle &RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001772 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001773 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00001774}
1775
1776/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1777/// input value to the specified type. If the type must be extended, it is zero
1778/// extended.
1779SCEVHandle
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001780ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001781 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001782 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001783 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1784 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00001785 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001786 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00001787 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001788 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001789 return getTruncateExpr(V, Ty);
1790 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001791}
1792
1793/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1794/// input value to the specified type. If the type must be extended, it is sign
1795/// extended.
1796SCEVHandle
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001797ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001798 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001799 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001800 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1801 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00001802 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001803 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00001804 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001805 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001806 return getTruncateExpr(V, Ty);
1807 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001808}
1809
Chris Lattner4dc534c2005-02-13 04:37:18 +00001810/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1811/// the specified instruction and replaces any references to the symbolic value
1812/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001813void ScalarEvolution::
Chris Lattner4dc534c2005-02-13 04:37:18 +00001814ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1815 const SCEVHandle &NewVal) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001816 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
1817 Scalars.find(SCEVCallbackVH(I, this));
Chris Lattner4dc534c2005-02-13 04:37:18 +00001818 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001819
Chris Lattner4dc534c2005-02-13 04:37:18 +00001820 SCEVHandle NV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001821 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001822 if (NV == SI->second) return; // No change.
1823
1824 SI->second = NV; // Update the scalars map!
1825
1826 // Any instruction values that use this instruction might also need to be
1827 // updated!
1828 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1829 UI != E; ++UI)
1830 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1831}
Chris Lattner53e677a2004-04-02 20:23:17 +00001832
1833/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1834/// a loop header, making it a potential recurrence, or it doesn't.
1835///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001836SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001837 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001838 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00001839 if (L->getHeader() == PN->getParent()) {
1840 // If it lives in the loop header, it has two incoming values, one
1841 // from outside the loop, and one from inside.
1842 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1843 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001844
Chris Lattner53e677a2004-04-02 20:23:17 +00001845 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001846 SCEVHandle SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001847 assert(Scalars.find(PN) == Scalars.end() &&
1848 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00001849 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00001850
1851 // Using this symbolic name for the PHI, analyze the value coming around
1852 // the back-edge.
1853 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1854
1855 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1856 // has a special value for the first iteration of the loop.
1857
1858 // If the value coming around the backedge is an add with the symbolic
1859 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00001860 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001861 // If there is a single occurrence of the symbolic value, replace it
1862 // with a recurrence.
1863 unsigned FoundIndex = Add->getNumOperands();
1864 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1865 if (Add->getOperand(i) == SymbolicName)
1866 if (FoundIndex == e) {
1867 FoundIndex = i;
1868 break;
1869 }
1870
1871 if (FoundIndex != Add->getNumOperands()) {
1872 // Create an add with everything but the specified operand.
1873 std::vector<SCEVHandle> Ops;
1874 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1875 if (i != FoundIndex)
1876 Ops.push_back(Add->getOperand(i));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001877 SCEVHandle Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001878
1879 // This is not a valid addrec if the step amount is varying each
1880 // loop iteration, but is not itself an addrec in this loop.
1881 if (Accum->isLoopInvariant(L) ||
1882 (isa<SCEVAddRecExpr>(Accum) &&
1883 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1884 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001885 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001886
1887 // Okay, for the entire analysis of this edge we assumed the PHI
1888 // to be symbolic. We now need to go back and update all of the
1889 // entries for the scalars that use the PHI (except for the PHI
1890 // itself) to use the new analyzed value instead of the "symbolic"
1891 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001892 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001893 return PHISCEV;
1894 }
1895 }
Dan Gohman622ed672009-05-04 22:02:23 +00001896 } else if (const SCEVAddRecExpr *AddRec =
1897 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00001898 // Otherwise, this could be a loop like this:
1899 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1900 // In this case, j = {1,+,1} and BEValue is j.
1901 // Because the other in-value of i (0) fits the evolution of BEValue
1902 // i really is an addrec evolution.
1903 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1904 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1905
1906 // If StartVal = j.start - j.stride, we can use StartVal as the
1907 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001908 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00001909 AddRec->getOperand(1))) {
Chris Lattner97156e72006-04-26 18:34:07 +00001910 SCEVHandle PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001911 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00001912
1913 // Okay, for the entire analysis of this edge we assumed the PHI
1914 // to be symbolic. We now need to go back and update all of the
1915 // entries for the scalars that use the PHI (except for the PHI
1916 // itself) to use the new analyzed value instead of the "symbolic"
1917 // value.
1918 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1919 return PHISCEV;
1920 }
1921 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001922 }
1923
1924 return SymbolicName;
1925 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001926
Chris Lattner53e677a2004-04-02 20:23:17 +00001927 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001928 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001929}
1930
Dan Gohman26466c02009-05-08 20:26:55 +00001931/// createNodeForGEP - Expand GEP instructions into add and multiply
1932/// operations. This allows them to be analyzed by regular SCEV code.
1933///
Dan Gohmanfb791602009-05-08 20:58:38 +00001934SCEVHandle ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00001935
1936 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmane810b0d2009-05-08 20:36:47 +00001937 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00001938 // Don't attempt to analyze GEPs over unsized objects.
1939 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
1940 return getUnknown(GEP);
Dan Gohman26466c02009-05-08 20:26:55 +00001941 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00001942 gep_type_iterator GTI = gep_type_begin(GEP);
1943 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
1944 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00001945 I != E; ++I) {
1946 Value *Index = *I;
1947 // Compute the (potentially symbolic) offset in bytes for this index.
1948 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
1949 // For a struct, add the member offset.
1950 const StructLayout &SL = *TD->getStructLayout(STy);
1951 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
1952 uint64_t Offset = SL.getElementOffset(FieldNo);
1953 TotalOffset = getAddExpr(TotalOffset,
1954 getIntegerSCEV(Offset, IntPtrTy));
1955 } else {
1956 // For an array, add the element offset, explicitly scaled.
1957 SCEVHandle LocalOffset = getSCEV(Index);
1958 if (!isa<PointerType>(LocalOffset->getType()))
1959 // Getelementptr indicies are signed.
1960 LocalOffset = getTruncateOrSignExtend(LocalOffset,
1961 IntPtrTy);
1962 LocalOffset =
1963 getMulExpr(LocalOffset,
Duncan Sands777d2302009-05-09 07:06:46 +00001964 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman26466c02009-05-08 20:26:55 +00001965 IntPtrTy));
1966 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
1967 }
1968 }
1969 return getAddExpr(getSCEV(Base), TotalOffset);
1970}
1971
Nick Lewycky83bb0052007-11-22 07:59:40 +00001972/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1973/// guaranteed to end in (at every loop iteration). It is, at the same time,
1974/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1975/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001976static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Dan Gohman622ed672009-05-04 22:02:23 +00001977 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00001978 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00001979
Dan Gohman622ed672009-05-04 22:02:23 +00001980 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001981 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1982 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00001983
Dan Gohman622ed672009-05-04 22:02:23 +00001984 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001985 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1986 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
Dan Gohman42a58752009-05-12 01:23:18 +00001987 SE.getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00001988 }
1989
Dan Gohman622ed672009-05-04 22:02:23 +00001990 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001991 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1992 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
Dan Gohman42a58752009-05-12 01:23:18 +00001993 SE.getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00001994 }
1995
Dan Gohman622ed672009-05-04 22:02:23 +00001996 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001997 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001998 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky83bb0052007-11-22 07:59:40 +00001999 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002000 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002001 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002002 }
2003
Dan Gohman622ed672009-05-04 22:02:23 +00002004 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002005 // The result is the sum of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002006 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
2007 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002008 for (unsigned i = 1, e = M->getNumOperands();
2009 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002010 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002011 BitWidth);
2012 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002013 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002014
Dan Gohman622ed672009-05-04 22:02:23 +00002015 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002016 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002017 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky83bb0052007-11-22 07:59:40 +00002018 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002019 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002020 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002021 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002022
Dan Gohman622ed672009-05-04 22:02:23 +00002023 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002024 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002025 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002026 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002027 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002028 return MinOpRes;
2029 }
2030
Dan Gohman622ed672009-05-04 22:02:23 +00002031 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002032 // The result is the min of all operands results.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002033 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky3e630762008-02-20 06:48:22 +00002034 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002035 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky3e630762008-02-20 06:48:22 +00002036 return MinOpRes;
2037 }
2038
Nick Lewycky789558d2009-01-13 09:18:58 +00002039 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky83bb0052007-11-22 07:59:40 +00002040 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002041}
Chris Lattner53e677a2004-04-02 20:23:17 +00002042
2043/// createSCEV - We know that there is no SCEV for the specified value.
2044/// Analyze the expression.
2045///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002046SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002047 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002048 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00002049
Dan Gohman6c459a22008-06-22 19:56:46 +00002050 unsigned Opcode = Instruction::UserOp1;
2051 if (Instruction *I = dyn_cast<Instruction>(V))
2052 Opcode = I->getOpcode();
2053 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2054 Opcode = CE->getOpcode();
2055 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002056 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00002057
Dan Gohman6c459a22008-06-22 19:56:46 +00002058 User *U = cast<User>(V);
2059 switch (Opcode) {
2060 case Instruction::Add:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002061 return getAddExpr(getSCEV(U->getOperand(0)),
2062 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002063 case Instruction::Mul:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002064 return getMulExpr(getSCEV(U->getOperand(0)),
2065 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002066 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002067 return getUDivExpr(getSCEV(U->getOperand(0)),
2068 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002069 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002070 return getMinusSCEV(getSCEV(U->getOperand(0)),
2071 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002072 case Instruction::And:
2073 // For an expression like x&255 that merely masks off the high bits,
2074 // use zext(trunc(x)) as the SCEV expression.
2075 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002076 if (CI->isNullValue())
2077 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00002078 if (CI->isAllOnesValue())
2079 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002080 const APInt &A = CI->getValue();
2081 unsigned Ones = A.countTrailingOnes();
2082 if (APIntOps::isMask(Ones, A))
2083 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002084 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
2085 IntegerType::get(Ones)),
2086 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00002087 }
2088 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00002089 case Instruction::Or:
2090 // If the RHS of the Or is a constant, we may have something like:
2091 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2092 // optimizations will transparently handle this case.
2093 //
2094 // In order for this transformation to be safe, the LHS must be of the
2095 // form X*(2^n) and the Or constant must be less than 2^n.
2096 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
2097 SCEVHandle LHS = getSCEV(U->getOperand(0));
2098 const APInt &CIVal = CI->getValue();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002099 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman6c459a22008-06-22 19:56:46 +00002100 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002101 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00002102 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002103 break;
2104 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00002105 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00002106 // If the RHS of the xor is a signbit, then this is just an add.
2107 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00002108 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002109 return getAddExpr(getSCEV(U->getOperand(0)),
2110 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002111
2112 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman6c459a22008-06-22 19:56:46 +00002113 else if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002114 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002115 }
2116 break;
2117
2118 case Instruction::Shl:
2119 // Turn shift left of a constant amount into a multiply.
2120 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2121 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2122 Constant *X = ConstantInt::get(
2123 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002124 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00002125 }
2126 break;
2127
Nick Lewycky01eaf802008-07-07 06:15:49 +00002128 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00002129 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00002130 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2131 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2132 Constant *X = ConstantInt::get(
2133 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002134 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002135 }
2136 break;
2137
Dan Gohman4ee29af2009-04-21 02:26:00 +00002138 case Instruction::AShr:
2139 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2140 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2141 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2142 if (L->getOpcode() == Instruction::Shl &&
2143 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002144 unsigned BitWidth = getTypeSizeInBits(U->getType());
2145 uint64_t Amt = BitWidth - CI->getZExtValue();
2146 if (Amt == BitWidth)
2147 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2148 if (Amt > BitWidth)
2149 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00002150 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002151 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002152 IntegerType::get(Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00002153 U->getType());
2154 }
2155 break;
2156
Dan Gohman6c459a22008-06-22 19:56:46 +00002157 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002158 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002159
2160 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002161 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002162
2163 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002164 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002165
2166 case Instruction::BitCast:
2167 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002168 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00002169 return getSCEV(U->getOperand(0));
2170 break;
2171
Dan Gohman2d1be872009-04-16 03:18:22 +00002172 case Instruction::IntToPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002173 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002174 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002175 TD->getIntPtrType());
Dan Gohman2d1be872009-04-16 03:18:22 +00002176
2177 case Instruction::PtrToInt:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002178 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002179 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2180 U->getType());
2181
Dan Gohman26466c02009-05-08 20:26:55 +00002182 case Instruction::GetElementPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002183 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanfb791602009-05-08 20:58:38 +00002184 return createNodeForGEP(U);
Dan Gohman2d1be872009-04-16 03:18:22 +00002185
Dan Gohman6c459a22008-06-22 19:56:46 +00002186 case Instruction::PHI:
2187 return createNodeForPHI(cast<PHINode>(U));
2188
2189 case Instruction::Select:
2190 // This could be a smax or umax that was lowered earlier.
2191 // Try to recover it.
2192 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2193 Value *LHS = ICI->getOperand(0);
2194 Value *RHS = ICI->getOperand(1);
2195 switch (ICI->getPredicate()) {
2196 case ICmpInst::ICMP_SLT:
2197 case ICmpInst::ICMP_SLE:
2198 std::swap(LHS, RHS);
2199 // fall through
2200 case ICmpInst::ICMP_SGT:
2201 case ICmpInst::ICMP_SGE:
2202 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002203 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002204 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman1fbffe02008-07-30 04:36:32 +00002205 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002206 return getNotSCEV(getSMaxExpr(
2207 getNotSCEV(getSCEV(LHS)),
2208 getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00002209 break;
2210 case ICmpInst::ICMP_ULT:
2211 case ICmpInst::ICMP_ULE:
2212 std::swap(LHS, RHS);
2213 // fall through
2214 case ICmpInst::ICMP_UGT:
2215 case ICmpInst::ICMP_UGE:
2216 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002217 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002218 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2219 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002220 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2221 getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00002222 break;
2223 default:
2224 break;
2225 }
2226 }
2227
2228 default: // We cannot analyze this expression.
2229 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002230 }
2231
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002232 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002233}
2234
2235
2236
2237//===----------------------------------------------------------------------===//
2238// Iteration Count Computation Code
2239//
2240
Dan Gohman46bdfb02009-02-24 18:55:53 +00002241/// getBackedgeTakenCount - If the specified loop has a predictable
2242/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2243/// object. The backedge-taken count is the number of times the loop header
2244/// will be branched to from within the loop. This is one less than the
2245/// trip count of the loop, since it doesn't count the first iteration,
2246/// when the header is branched to from outside the loop.
2247///
2248/// Note that it is not valid to call this method on a loop without a
2249/// loop-invariant backedge-taken count (see
2250/// hasLoopInvariantBackedgeTakenCount).
2251///
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002252SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002253 return getBackedgeTakenInfo(L).Exact;
2254}
2255
2256/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2257/// return the least SCEV value that is known never to be less than the
2258/// actual backedge taken count.
2259SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2260 return getBackedgeTakenInfo(L).Max;
2261}
2262
2263const ScalarEvolution::BackedgeTakenInfo &
2264ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00002265 // Initially insert a CouldNotCompute for this loop. If the insertion
2266 // succeeds, procede to actually compute a backedge-taken count and
2267 // update the value. The temporary CouldNotCompute value tells SCEV
2268 // code elsewhere that it shouldn't attempt to request a new
2269 // backedge-taken count, which could result in infinite recursion.
Dan Gohmana1af7572009-04-30 20:47:05 +00002270 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00002271 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2272 if (Pair.second) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002273 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2274 if (ItCount.Exact != UnknownValue) {
2275 assert(ItCount.Exact->isLoopInvariant(L) &&
2276 ItCount.Max->isLoopInvariant(L) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002277 "Computed trip count isn't loop invariant for loop!");
2278 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00002279
Dan Gohman01ecca22009-04-27 20:16:15 +00002280 // Update the value in the map.
2281 Pair.first->second = ItCount;
Chris Lattner53e677a2004-04-02 20:23:17 +00002282 } else if (isa<PHINode>(L->getHeader()->begin())) {
2283 // Only count loops that have phi nodes as not being computable.
2284 ++NumTripCountsNotComputed;
2285 }
Dan Gohmana1af7572009-04-30 20:47:05 +00002286
2287 // Now that we know more about the trip count for this loop, forget any
2288 // existing SCEV values for PHI nodes in this loop since they are only
2289 // conservative estimates made without the benefit
2290 // of trip count information.
2291 if (ItCount.hasAnyInfo())
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00002292 forgetLoopPHIs(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002293 }
Dan Gohman01ecca22009-04-27 20:16:15 +00002294 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00002295}
2296
Dan Gohman46bdfb02009-02-24 18:55:53 +00002297/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohman60f8a632009-02-17 20:49:49 +00002298/// client when it has changed a loop in a way that may effect
Dan Gohman46bdfb02009-02-24 18:55:53 +00002299/// ScalarEvolution's ability to compute a trip count, or if the loop
2300/// is deleted.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002301void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00002302 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00002303 forgetLoopPHIs(L);
2304}
2305
2306/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2307/// PHI nodes in the given loop. This is used when the trip count of
2308/// the loop may have changed.
2309void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohman35738ac2009-05-04 22:30:44 +00002310 BasicBlock *Header = L->getHeader();
2311
Dan Gohmanefb9fbf2009-05-12 01:27:58 +00002312 // Push all Loop-header PHIs onto the Worklist stack, except those
2313 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2314 // a PHI either means that it has an unrecognized structure, or it's
2315 // a PHI that's in the progress of being computed by createNodeForPHI.
2316 // In the former case, additional loop trip count information isn't
2317 // going to change anything. In the later case, createNodeForPHI will
2318 // perform the necessary updates on its own when it gets to that point.
Dan Gohman35738ac2009-05-04 22:30:44 +00002319 SmallVector<Instruction *, 16> Worklist;
2320 for (BasicBlock::iterator I = Header->begin();
Dan Gohmanefb9fbf2009-05-12 01:27:58 +00002321 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
2322 std::map<SCEVCallbackVH, SCEVHandle>::iterator It = Scalars.find((Value*)I);
2323 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2324 Worklist.push_back(PN);
2325 }
Dan Gohman35738ac2009-05-04 22:30:44 +00002326
2327 while (!Worklist.empty()) {
2328 Instruction *I = Worklist.pop_back_val();
2329 if (Scalars.erase(I))
2330 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2331 UI != UE; ++UI)
2332 Worklist.push_back(cast<Instruction>(UI));
2333 }
Dan Gohman60f8a632009-02-17 20:49:49 +00002334}
2335
Dan Gohman46bdfb02009-02-24 18:55:53 +00002336/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2337/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00002338ScalarEvolution::BackedgeTakenInfo
2339ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002340 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patelb7211a22007-08-21 00:31:24 +00002341 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002342 L->getExitBlocks(ExitBlocks);
2343 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002344
2345 // Okay, there is one exit block. Try to find the condition that causes the
2346 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002347 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00002348
2349 BasicBlock *ExitingBlock = 0;
2350 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2351 PI != E; ++PI)
2352 if (L->contains(*PI)) {
2353 if (ExitingBlock == 0)
2354 ExitingBlock = *PI;
2355 else
2356 return UnknownValue; // More than one block exiting!
2357 }
2358 assert(ExitingBlock && "No exits from loop, something is broken!");
2359
2360 // Okay, we've computed the exiting block. See what condition causes us to
2361 // exit.
2362 //
2363 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00002364 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2365 if (ExitBr == 0) return UnknownValue;
2366 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00002367
2368 // At this point, we know we have a conditional branch that determines whether
2369 // the loop is exited. However, we don't know if the branch is executed each
2370 // time through the loop. If not, then the execution count of the branch will
2371 // not be equal to the trip count of the loop.
2372 //
2373 // Currently we check for this by checking to see if the Exit branch goes to
2374 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00002375 // times as the loop. We also handle the case where the exit block *is* the
2376 // loop header. This is common for un-rotated loops. More extensive analysis
2377 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00002378 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00002379 ExitBr->getSuccessor(1) != L->getHeader() &&
2380 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00002381 return UnknownValue;
2382
Reid Spencere4d87aa2006-12-23 06:05:41 +00002383 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2384
Eli Friedman361e54d2009-05-09 12:32:42 +00002385 // If it's not an integer or pointer comparison then compute it the hard way.
2386 if (ExitCond == 0)
Dan Gohman46bdfb02009-02-24 18:55:53 +00002387 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Chris Lattner7980fb92004-04-17 18:36:24 +00002388 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00002389
Reid Spencere4d87aa2006-12-23 06:05:41 +00002390 // If the condition was exit on true, convert the condition to exit on false
2391 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00002392 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00002393 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002394 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00002395 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002396
2397 // Handle common loops like: for (X = "string"; *X; ++X)
2398 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2399 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2400 SCEVHandle ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00002401 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Chris Lattner673e02b2004-10-12 01:49:27 +00002402 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2403 }
2404
Chris Lattner53e677a2004-04-02 20:23:17 +00002405 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2406 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2407
2408 // Try to evaluate any dependencies out of the loop.
2409 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2410 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2411 Tmp = getSCEVAtScope(RHS, L);
2412 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2413
Reid Spencere4d87aa2006-12-23 06:05:41 +00002414 // At this point, we would like to compute how many iterations of the
2415 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00002416 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2417 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00002418 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002419 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00002420 }
2421
Chris Lattner53e677a2004-04-02 20:23:17 +00002422 // If we have a comparison of a chrec against a constant, try to use value
2423 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00002424 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2425 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00002426 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00002427 // Form the constant range.
2428 ConstantRange CompRange(
2429 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002430
Eli Friedman361e54d2009-05-09 12:32:42 +00002431 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
2432 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00002433 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002434
Chris Lattner53e677a2004-04-02 20:23:17 +00002435 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002436 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00002437 // Convert to: while (X-Y != 0)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002438 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002439 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002440 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002441 }
2442 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00002443 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002444 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002445 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002446 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002447 }
2448 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002449 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2450 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002451 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002452 }
2453 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002454 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2455 getNotSCEV(RHS), L, true);
2456 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002457 break;
2458 }
2459 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002460 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2461 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002462 break;
2463 }
2464 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00002465 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2466 getNotSCEV(RHS), L, false);
2467 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002468 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002469 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002470 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002471#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002472 errs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002473 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002474 errs() << "[unsigned] ";
2475 errs() << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00002476 << Instruction::getOpcodeName(Instruction::ICmp)
2477 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002478#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00002479 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002480 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00002481 return
2482 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2483 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00002484}
2485
Chris Lattner673e02b2004-10-12 01:49:27 +00002486static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00002487EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2488 ScalarEvolution &SE) {
2489 SCEVHandle InVal = SE.getConstant(C);
2490 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002491 assert(isa<SCEVConstant>(Val) &&
2492 "Evaluation of SCEV at constant didn't fold correctly?");
2493 return cast<SCEVConstant>(Val)->getValue();
2494}
2495
2496/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2497/// and a GEP expression (missing the pointer index) indexing into it, return
2498/// the addressed element of the initializer or null if the index expression is
2499/// invalid.
2500static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002501GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00002502 const std::vector<ConstantInt*> &Indices) {
2503 Constant *Init = GV->getInitializer();
2504 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002505 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00002506 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2507 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2508 Init = cast<Constant>(CS->getOperand(Idx));
2509 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2510 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2511 Init = cast<Constant>(CA->getOperand(Idx));
2512 } else if (isa<ConstantAggregateZero>(Init)) {
2513 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2514 assert(Idx < STy->getNumElements() && "Bad struct index!");
2515 Init = Constant::getNullValue(STy->getElementType(Idx));
2516 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2517 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2518 Init = Constant::getNullValue(ATy->getElementType());
2519 } else {
2520 assert(0 && "Unknown constant aggregate type!");
2521 }
2522 return 0;
2523 } else {
2524 return 0; // Unknown initializer type
2525 }
2526 }
2527 return Init;
2528}
2529
Dan Gohman46bdfb02009-02-24 18:55:53 +00002530/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2531/// 'icmp op load X, cst', try to see if we can compute the backedge
2532/// execution count.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002533SCEVHandle ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00002534ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2535 const Loop *L,
2536 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002537 if (LI->isVolatile()) return UnknownValue;
2538
2539 // Check to see if the loaded pointer is a getelementptr of a global.
2540 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2541 if (!GEP) return UnknownValue;
2542
2543 // Make sure that it is really a constant global we are gepping, with an
2544 // initializer, and make sure the first IDX is really 0.
2545 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2546 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2547 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2548 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2549 return UnknownValue;
2550
2551 // Okay, we allow one non-constant index into the GEP instruction.
2552 Value *VarIdx = 0;
2553 std::vector<ConstantInt*> Indexes;
2554 unsigned VarIdxNum = 0;
2555 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2556 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2557 Indexes.push_back(CI);
2558 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2559 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2560 VarIdx = GEP->getOperand(i);
2561 VarIdxNum = i-2;
2562 Indexes.push_back(0);
2563 }
2564
2565 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2566 // Check to see if X is a loop variant variable value now.
2567 SCEVHandle Idx = getSCEV(VarIdx);
2568 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2569 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2570
2571 // We can only recognize very limited forms of loop index expressions, in
2572 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00002573 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00002574 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2575 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2576 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2577 return UnknownValue;
2578
2579 unsigned MaxSteps = MaxBruteForceIterations;
2580 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002581 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00002582 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002583 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00002584
2585 // Form the GEP offset.
2586 Indexes[VarIdxNum] = Val;
2587
2588 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2589 if (Result == 0) break; // Cannot compute!
2590
2591 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002592 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002593 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00002594 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002595#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00002596 errs() << "\n***\n*** Computed loop count " << *ItCst
2597 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2598 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00002599#endif
2600 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002601 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00002602 }
2603 }
2604 return UnknownValue;
2605}
2606
2607
Chris Lattner3221ad02004-04-17 22:58:41 +00002608/// CanConstantFold - Return true if we can constant fold an instruction of the
2609/// specified type, assuming that all operands were constants.
2610static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00002611 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00002612 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2613 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002614
Chris Lattner3221ad02004-04-17 22:58:41 +00002615 if (const CallInst *CI = dyn_cast<CallInst>(I))
2616 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00002617 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00002618 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00002619}
2620
Chris Lattner3221ad02004-04-17 22:58:41 +00002621/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2622/// in the loop that V is derived from. We allow arbitrary operations along the
2623/// way, but the operands of an operation must either be constants or a value
2624/// derived from a constant PHI. If this expression does not fit with these
2625/// constraints, return null.
2626static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2627 // If this is not an instruction, or if this is an instruction outside of the
2628 // loop, it can't be derived from a loop PHI.
2629 Instruction *I = dyn_cast<Instruction>(V);
2630 if (I == 0 || !L->contains(I->getParent())) return 0;
2631
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002632 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002633 if (L->getHeader() == I->getParent())
2634 return PN;
2635 else
2636 // We don't currently keep track of the control flow needed to evaluate
2637 // PHIs, so we cannot handle PHIs inside of loops.
2638 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002639 }
Chris Lattner3221ad02004-04-17 22:58:41 +00002640
2641 // If we won't be able to constant fold this expression even if the operands
2642 // are constants, return early.
2643 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002644
Chris Lattner3221ad02004-04-17 22:58:41 +00002645 // Otherwise, we can evaluate this instruction if all of its operands are
2646 // constant or derived from a PHI node themselves.
2647 PHINode *PHI = 0;
2648 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2649 if (!(isa<Constant>(I->getOperand(Op)) ||
2650 isa<GlobalValue>(I->getOperand(Op)))) {
2651 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2652 if (P == 0) return 0; // Not evolving from PHI
2653 if (PHI == 0)
2654 PHI = P;
2655 else if (PHI != P)
2656 return 0; // Evolving from multiple different PHIs.
2657 }
2658
2659 // This is a expression evolving from a constant PHI!
2660 return PHI;
2661}
2662
2663/// EvaluateExpression - Given an expression that passes the
2664/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2665/// in the loop has the value PHIVal. If we can't fold this expression for some
2666/// reason, return null.
2667static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2668 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00002669 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00002670 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00002671 Instruction *I = cast<Instruction>(V);
2672
2673 std::vector<Constant*> Operands;
2674 Operands.resize(I->getNumOperands());
2675
2676 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2677 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2678 if (Operands[i] == 0) return 0;
2679 }
2680
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002681 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2682 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2683 &Operands[0], Operands.size());
2684 else
2685 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2686 &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00002687}
2688
2689/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2690/// in the header of its containing loop, we know the loop executes a
2691/// constant number of times, and the PHI node is just a recurrence
2692/// involving constants, fold it.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002693Constant *ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00002694getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00002695 std::map<PHINode*, Constant*>::iterator I =
2696 ConstantEvolutionLoopExitValue.find(PN);
2697 if (I != ConstantEvolutionLoopExitValue.end())
2698 return I->second;
2699
Dan Gohman46bdfb02009-02-24 18:55:53 +00002700 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00002701 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2702
2703 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2704
2705 // Since the loop is canonicalized, the PHI node must have two entries. One
2706 // entry must be a constant (coming in from outside of the loop), and the
2707 // second must be derived from the same PHI.
2708 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2709 Constant *StartCST =
2710 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2711 if (StartCST == 0)
2712 return RetVal = 0; // Must be a constant.
2713
2714 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2715 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2716 if (PN2 != PN)
2717 return RetVal = 0; // Not derived from same PHI.
2718
2719 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00002720 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00002721 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00002722
Dan Gohman46bdfb02009-02-24 18:55:53 +00002723 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00002724 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00002725 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2726 if (IterationNum == NumIterations)
2727 return RetVal = PHIVal; // Got exit value!
2728
2729 // Compute the value of the PHI node for the next iteration.
2730 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2731 if (NextPHI == PHIVal)
2732 return RetVal = NextPHI; // Stopped evolving!
2733 if (NextPHI == 0)
2734 return 0; // Couldn't evaluate!
2735 PHIVal = NextPHI;
2736 }
2737}
2738
Dan Gohman46bdfb02009-02-24 18:55:53 +00002739/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00002740/// constant number of times (the condition evolves only from constants),
2741/// try to evaluate a few iterations of the loop until we get the exit
2742/// condition gets a value of ExitWhen (true or false). If we cannot
2743/// evaluate the trip count of the loop, return UnknownValue.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002744SCEVHandle ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00002745ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00002746 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2747 if (PN == 0) return UnknownValue;
2748
2749 // Since the loop is canonicalized, the PHI node must have two entries. One
2750 // entry must be a constant (coming in from outside of the loop), and the
2751 // second must be derived from the same PHI.
2752 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2753 Constant *StartCST =
2754 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2755 if (StartCST == 0) return UnknownValue; // Must be a constant.
2756
2757 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2758 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2759 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2760
2761 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2762 // the loop symbolically to determine when the condition gets a value of
2763 // "ExitWhen".
2764 unsigned IterationNum = 0;
2765 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2766 for (Constant *PHIVal = StartCST;
2767 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002768 ConstantInt *CondVal =
2769 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00002770
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002771 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00002772 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002773
Reid Spencere8019bb2007-03-01 07:25:48 +00002774 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002775 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00002776 ++NumBruteForceTripCountsComputed;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002777 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00002778 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002779
Chris Lattner3221ad02004-04-17 22:58:41 +00002780 // Compute the value of the PHI node for the next iteration.
2781 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2782 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00002783 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00002784 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00002785 }
2786
2787 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00002788 return UnknownValue;
2789}
2790
Dan Gohman66a7e852009-05-08 20:38:54 +00002791/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2792/// at the specified scope in the program. The L value specifies a loop
2793/// nest to evaluate the expression at, where null is the top-level or a
2794/// specified loop is immediately inside of the loop.
2795///
2796/// This method can be used to compute the exit value for a variable defined
2797/// in a loop by querying what the value will hold in the parent loop.
2798///
2799/// If this value is not computable at this scope, a SCEVCouldNotCompute
2800/// object is returned.
Dan Gohman35738ac2009-05-04 22:30:44 +00002801SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002802 // FIXME: this should be turned into a virtual method on SCEV!
2803
Chris Lattner3221ad02004-04-17 22:58:41 +00002804 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002805
Nick Lewycky3e630762008-02-20 06:48:22 +00002806 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00002807 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00002808 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002809 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002810 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00002811 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2812 if (PHINode *PN = dyn_cast<PHINode>(I))
2813 if (PN->getParent() == LI->getHeader()) {
2814 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00002815 // to see if the loop that contains it has a known backedge-taken
2816 // count. If so, we may be able to force computation of the exit
2817 // value.
2818 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00002819 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00002820 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002821 // Okay, we know how many times the containing loop executes. If
2822 // this is a constant evolving PHI node, get the final value at
2823 // the specified iteration number.
2824 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00002825 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00002826 LI);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002827 if (RV) return getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00002828 }
2829 }
2830
Reid Spencer09906f32006-12-04 21:33:23 +00002831 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00002832 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00002833 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00002834 // result. This is particularly useful for computing loop exit values.
2835 if (CanConstantFold(I)) {
Dan Gohman6bce6432009-05-08 20:47:27 +00002836 // Check to see if we've folded this instruction at this loop before.
2837 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
2838 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
2839 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
2840 if (!Pair.second)
2841 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
2842
Chris Lattner3221ad02004-04-17 22:58:41 +00002843 std::vector<Constant*> Operands;
2844 Operands.reserve(I->getNumOperands());
2845 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2846 Value *Op = I->getOperand(i);
2847 if (Constant *C = dyn_cast<Constant>(Op)) {
2848 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002849 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00002850 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00002851 // non-integer and non-pointer, don't even try to analyze them
2852 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00002853 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00002854 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00002855
Chris Lattner3221ad02004-04-17 22:58:41 +00002856 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohman622ed672009-05-04 22:02:23 +00002857 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00002858 Constant *C = SC->getValue();
2859 if (C->getType() != Op->getType())
2860 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2861 Op->getType(),
2862 false),
2863 C, Op->getType());
2864 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00002865 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00002866 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
2867 if (C->getType() != Op->getType())
2868 C =
2869 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2870 Op->getType(),
2871 false),
2872 C, Op->getType());
2873 Operands.push_back(C);
2874 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00002875 return V;
2876 } else {
2877 return V;
2878 }
2879 }
2880 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002881
2882 Constant *C;
2883 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2884 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2885 &Operands[0], Operands.size());
2886 else
2887 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2888 &Operands[0], Operands.size());
Dan Gohman6bce6432009-05-08 20:47:27 +00002889 Pair.first->second = C;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002890 return getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002891 }
2892 }
2893
2894 // This is some other type of SCEVUnknown, just return it.
2895 return V;
2896 }
2897
Dan Gohman622ed672009-05-04 22:02:23 +00002898 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002899 // Avoid performing the look-up in the common case where the specified
2900 // expression has no loop-variant portions.
2901 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2902 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2903 if (OpAtScope != Comm->getOperand(i)) {
2904 if (OpAtScope == UnknownValue) return UnknownValue;
2905 // Okay, at least one of these operands is loop variant but might be
2906 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002907 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002908 NewOps.push_back(OpAtScope);
2909
2910 for (++i; i != e; ++i) {
2911 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2912 if (OpAtScope == UnknownValue) return UnknownValue;
2913 NewOps.push_back(OpAtScope);
2914 }
2915 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002916 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002917 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002918 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002919 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002920 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00002921 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002922 return getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002923 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002924 }
2925 }
2926 // If we got here, all operands are loop invariant.
2927 return Comm;
2928 }
2929
Dan Gohman622ed672009-05-04 22:02:23 +00002930 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Nick Lewycky789558d2009-01-13 09:18:58 +00002931 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002932 if (LHS == UnknownValue) return LHS;
Nick Lewycky789558d2009-01-13 09:18:58 +00002933 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002934 if (RHS == UnknownValue) return RHS;
Nick Lewycky789558d2009-01-13 09:18:58 +00002935 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2936 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002937 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002938 }
2939
2940 // If this is a loop recurrence for a loop that does not contain L, then we
2941 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00002942 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002943 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2944 // To evaluate this recurrence, we need to know how many times the AddRec
2945 // loop iterates. Compute this now.
Dan Gohman46bdfb02009-02-24 18:55:53 +00002946 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2947 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002948
Eli Friedmanb42a6262008-08-04 23:49:06 +00002949 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002950 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00002951 }
2952 return UnknownValue;
2953 }
2954
Dan Gohman622ed672009-05-04 22:02:23 +00002955 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmaneb3948b2009-04-29 22:29:01 +00002956 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2957 if (Op == UnknownValue) return Op;
2958 if (Op == Cast->getOperand())
2959 return Cast; // must be loop invariant
2960 return getZeroExtendExpr(Op, Cast->getType());
2961 }
2962
Dan Gohman622ed672009-05-04 22:02:23 +00002963 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmaneb3948b2009-04-29 22:29:01 +00002964 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2965 if (Op == UnknownValue) return Op;
2966 if (Op == Cast->getOperand())
2967 return Cast; // must be loop invariant
2968 return getSignExtendExpr(Op, Cast->getType());
2969 }
2970
Dan Gohman622ed672009-05-04 22:02:23 +00002971 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmaneb3948b2009-04-29 22:29:01 +00002972 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2973 if (Op == UnknownValue) return Op;
2974 if (Op == Cast->getOperand())
2975 return Cast; // must be loop invariant
2976 return getTruncateExpr(Op, Cast->getType());
2977 }
2978
2979 assert(0 && "Unknown SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002980}
2981
Dan Gohman66a7e852009-05-08 20:38:54 +00002982/// getSCEVAtScope - This is a convenience function which does
2983/// getSCEVAtScope(getSCEV(V), L).
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002984SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2985 return getSCEVAtScope(getSCEV(V), L);
2986}
2987
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002988/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2989/// following equation:
2990///
2991/// A * X = B (mod N)
2992///
2993/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2994/// A and B isn't important.
2995///
2996/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2997static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2998 ScalarEvolution &SE) {
2999 uint32_t BW = A.getBitWidth();
3000 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3001 assert(A != 0 && "A must be non-zero.");
3002
3003 // 1. D = gcd(A, N)
3004 //
3005 // The gcd of A and N may have only one prime factor: 2. The number of
3006 // trailing zeros in A is its multiplicity
3007 uint32_t Mult2 = A.countTrailingZeros();
3008 // D = 2^Mult2
3009
3010 // 2. Check if B is divisible by D.
3011 //
3012 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3013 // is not less than multiplicity of this prime factor for D.
3014 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003015 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003016
3017 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3018 // modulo (N / D).
3019 //
3020 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3021 // bit width during computations.
3022 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3023 APInt Mod(BW + 1, 0);
3024 Mod.set(BW - Mult2); // Mod = N / D
3025 APInt I = AD.multiplicativeInverse(Mod);
3026
3027 // 4. Compute the minimum unsigned root of the equation:
3028 // I * (B / D) mod (N / D)
3029 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3030
3031 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3032 // bits.
3033 return SE.getConstant(Result.trunc(BW));
3034}
Chris Lattner53e677a2004-04-02 20:23:17 +00003035
3036/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3037/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3038/// might be the same) or two SCEVCouldNotCompute objects.
3039///
3040static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman246b2562007-10-22 18:31:58 +00003041SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003042 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00003043 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3044 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3045 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003046
Chris Lattner53e677a2004-04-02 20:23:17 +00003047 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00003048 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00003049 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003050 return std::make_pair(CNC, CNC);
3051 }
3052
Reid Spencere8019bb2007-03-01 07:25:48 +00003053 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00003054 const APInt &L = LC->getValue()->getValue();
3055 const APInt &M = MC->getValue()->getValue();
3056 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00003057 APInt Two(BitWidth, 2);
3058 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003059
Reid Spencere8019bb2007-03-01 07:25:48 +00003060 {
3061 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00003062 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00003063 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3064 // The B coefficient is M-N/2
3065 APInt B(M);
3066 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003067
Reid Spencere8019bb2007-03-01 07:25:48 +00003068 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00003069 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00003070
Reid Spencere8019bb2007-03-01 07:25:48 +00003071 // Compute the B^2-4ac term.
3072 APInt SqrtTerm(B);
3073 SqrtTerm *= B;
3074 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00003075
Reid Spencere8019bb2007-03-01 07:25:48 +00003076 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3077 // integer value or else APInt::sqrt() will assert.
3078 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003079
Reid Spencere8019bb2007-03-01 07:25:48 +00003080 // Compute the two solutions for the quadratic formula.
3081 // The divisions must be performed as signed divisions.
3082 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00003083 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00003084 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00003085 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00003086 return std::make_pair(CNC, CNC);
3087 }
3088
Reid Spencere8019bb2007-03-01 07:25:48 +00003089 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3090 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003091
Dan Gohman246b2562007-10-22 18:31:58 +00003092 return std::make_pair(SE.getConstant(Solution1),
3093 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00003094 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00003095}
3096
3097/// HowFarToZero - Return the number of times a backedge comparing the specified
3098/// value to zero will execute. If not computable, return UnknownValue
Dan Gohman35738ac2009-05-04 22:30:44 +00003099SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003100 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00003101 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003102 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00003103 if (C->getValue()->isZero()) return C;
Chris Lattner53e677a2004-04-02 20:23:17 +00003104 return UnknownValue; // Otherwise it will loop infinitely.
3105 }
3106
Dan Gohman35738ac2009-05-04 22:30:44 +00003107 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003108 if (!AddRec || AddRec->getLoop() != L)
3109 return UnknownValue;
3110
3111 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003112 // If this is an affine expression, the execution count of this branch is
3113 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00003114 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003115 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00003116 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003117 // equivalent to:
3118 //
3119 // Step*N = -Start (mod 2^BW)
3120 //
3121 // where BW is the common bit width of Start and Step.
3122
Chris Lattner53e677a2004-04-02 20:23:17 +00003123 // Get the initial value for the loop.
3124 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00003125 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00003126
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003127 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003128
Dan Gohman622ed672009-05-04 22:02:23 +00003129 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003130 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00003131
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003132 // First, handle unitary steps.
3133 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003134 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003135 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3136 return Start; // N = Start (as unsigned)
3137
3138 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00003139 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003140 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003141 -StartC->getValue()->getValue(),
3142 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003143 }
Chris Lattner42a75512007-01-15 02:27:26 +00003144 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003145 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3146 // the quadratic equation to solve it.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003147 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
3148 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00003149 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3150 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00003151 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003152#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003153 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3154 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003155#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00003156 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003157 if (ConstantInt *CB =
3158 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003159 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00003160 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00003161 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003162
Chris Lattner53e677a2004-04-02 20:23:17 +00003163 // We can only use this value if the chrec ends up with an exact zero
3164 // value at this index. When solving for "X*X != 5", for example, we
3165 // should not accept a root of 2.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003166 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00003167 if (Val->isZero())
3168 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00003169 }
3170 }
3171 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003172
Chris Lattner53e677a2004-04-02 20:23:17 +00003173 return UnknownValue;
3174}
3175
3176/// HowFarToNonZero - Return the number of times a backedge checking the
3177/// specified value for nonzero will execute. If not computable, return
3178/// UnknownValue
Dan Gohman35738ac2009-05-04 22:30:44 +00003179SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003180 // Loops that look like: while (X == 0) are very strange indeed. We don't
3181 // handle them yet except for the trivial case. This could be expanded in the
3182 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003183
Chris Lattner53e677a2004-04-02 20:23:17 +00003184 // If the value is a constant, check to see if it is known to be non-zero
3185 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00003186 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00003187 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003188 return getIntegerSCEV(0, C->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00003189 return UnknownValue; // Otherwise it will loop infinitely.
3190 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003191
Chris Lattner53e677a2004-04-02 20:23:17 +00003192 // We could implement others, but I really doubt anyone writes loops like
3193 // this, and if they did, they would already be constant folded.
3194 return UnknownValue;
3195}
3196
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003197/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3198/// (which may not be an immediate predecessor) which has exactly one
3199/// successor from which BB is reachable, or null if no such block is
3200/// found.
3201///
3202BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003203ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00003204 // If the block has a unique predecessor, then there is no path from the
3205 // predecessor to the block that does not go through the direct edge
3206 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003207 if (BasicBlock *Pred = BB->getSinglePredecessor())
3208 return Pred;
3209
3210 // A loop's header is defined to be a block that dominates the loop.
3211 // If the loop has a preheader, it must be a block that has exactly
3212 // one successor that can reach BB. This is slightly more strict
3213 // than necessary, but works if critical edges are split.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003214 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003215 return L->getLoopPreheader();
3216
3217 return 0;
3218}
3219
Dan Gohmanc2390b12009-02-12 22:19:27 +00003220/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman3d739fe2009-04-30 20:48:53 +00003221/// a conditional between LHS and RHS. This is used to help avoid max
3222/// expressions in loop trip counts.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003223bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman3d739fe2009-04-30 20:48:53 +00003224 ICmpInst::Predicate Pred,
Dan Gohman35738ac2009-05-04 22:30:44 +00003225 const SCEV *LHS, const SCEV *RHS) {
Nick Lewycky59cff122008-07-12 07:41:32 +00003226 BasicBlock *Preheader = L->getLoopPreheader();
3227 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00003228
Dan Gohman38372182008-08-12 20:17:31 +00003229 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003230 // there are predecessors that can be found that have unique successors
3231 // leading to the original header.
3232 for (; Preheader;
3233 PreheaderDest = Preheader,
3234 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohman38372182008-08-12 20:17:31 +00003235
3236 BranchInst *LoopEntryPredicate =
Nick Lewycky59cff122008-07-12 07:41:32 +00003237 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00003238 if (!LoopEntryPredicate ||
3239 LoopEntryPredicate->isUnconditional())
3240 continue;
3241
3242 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3243 if (!ICI) continue;
3244
3245 // Now that we found a conditional branch that dominates the loop, check to
3246 // see if it is the comparison we are looking for.
3247 Value *PreCondLHS = ICI->getOperand(0);
3248 Value *PreCondRHS = ICI->getOperand(1);
3249 ICmpInst::Predicate Cond;
3250 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3251 Cond = ICI->getPredicate();
3252 else
3253 Cond = ICI->getInversePredicate();
3254
Dan Gohmanc2390b12009-02-12 22:19:27 +00003255 if (Cond == Pred)
3256 ; // An exact match.
3257 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3258 ; // The actual condition is beyond sufficient.
3259 else
3260 // Check a few special cases.
3261 switch (Cond) {
3262 case ICmpInst::ICMP_UGT:
3263 if (Pred == ICmpInst::ICMP_ULT) {
3264 std::swap(PreCondLHS, PreCondRHS);
3265 Cond = ICmpInst::ICMP_ULT;
3266 break;
3267 }
3268 continue;
3269 case ICmpInst::ICMP_SGT:
3270 if (Pred == ICmpInst::ICMP_SLT) {
3271 std::swap(PreCondLHS, PreCondRHS);
3272 Cond = ICmpInst::ICMP_SLT;
3273 break;
3274 }
3275 continue;
3276 case ICmpInst::ICMP_NE:
3277 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3278 // so check for this case by checking if the NE is comparing against
3279 // a minimum or maximum constant.
3280 if (!ICmpInst::isTrueWhenEqual(Pred))
3281 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3282 const APInt &A = CI->getValue();
3283 switch (Pred) {
3284 case ICmpInst::ICMP_SLT:
3285 if (A.isMaxSignedValue()) break;
3286 continue;
3287 case ICmpInst::ICMP_SGT:
3288 if (A.isMinSignedValue()) break;
3289 continue;
3290 case ICmpInst::ICMP_ULT:
3291 if (A.isMaxValue()) break;
3292 continue;
3293 case ICmpInst::ICMP_UGT:
3294 if (A.isMinValue()) break;
3295 continue;
3296 default:
3297 continue;
3298 }
3299 Cond = ICmpInst::ICMP_NE;
3300 // NE is symmetric but the original comparison may not be. Swap
3301 // the operands if necessary so that they match below.
3302 if (isa<SCEVConstant>(LHS))
3303 std::swap(PreCondLHS, PreCondRHS);
3304 break;
3305 }
3306 continue;
3307 default:
3308 // We weren't able to reconcile the condition.
3309 continue;
3310 }
Dan Gohman38372182008-08-12 20:17:31 +00003311
3312 if (!PreCondLHS->getType()->isInteger()) continue;
3313
3314 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3315 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3316 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003317 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3318 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohman38372182008-08-12 20:17:31 +00003319 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00003320 }
3321
Dan Gohman38372182008-08-12 20:17:31 +00003322 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00003323}
3324
Chris Lattnerdb25de42005-08-15 23:33:51 +00003325/// HowManyLessThans - Return the number of times a backedge containing the
3326/// specified less-than comparison will execute. If not computable, return
3327/// UnknownValue.
Dan Gohmana1af7572009-04-30 20:47:05 +00003328ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Dan Gohman35738ac2009-05-04 22:30:44 +00003329HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3330 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00003331 // Only handle: "ADDREC < LoopInvariant".
3332 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3333
Dan Gohman35738ac2009-05-04 22:30:44 +00003334 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00003335 if (!AddRec || AddRec->getLoop() != L)
3336 return UnknownValue;
3337
3338 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00003339 // FORNOW: We only support unit strides.
Dan Gohmana1af7572009-04-30 20:47:05 +00003340 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3341 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3342 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3343
3344 // TODO: handle non-constant strides.
3345 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3346 if (!CStep || CStep->isZero())
3347 return UnknownValue;
3348 if (CStep->getValue()->getValue() == 1) {
3349 // With unit stride, the iteration never steps past the limit value.
3350 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3351 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3352 // Test whether a positive iteration iteration can step past the limit
3353 // value and past the maximum value for its type in a single step.
3354 if (isSigned) {
3355 APInt Max = APInt::getSignedMaxValue(BitWidth);
3356 if ((Max - CStep->getValue()->getValue())
3357 .slt(CLimit->getValue()->getValue()))
3358 return UnknownValue;
3359 } else {
3360 APInt Max = APInt::getMaxValue(BitWidth);
3361 if ((Max - CStep->getValue()->getValue())
3362 .ult(CLimit->getValue()->getValue()))
3363 return UnknownValue;
3364 }
3365 } else
3366 // TODO: handle non-constant limit values below.
3367 return UnknownValue;
3368 } else
3369 // TODO: handle negative strides below.
Chris Lattnerdb25de42005-08-15 23:33:51 +00003370 return UnknownValue;
3371
Dan Gohmana1af7572009-04-30 20:47:05 +00003372 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3373 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3374 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00003375 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00003376
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00003377 // First, we get the value of the LHS in the first iteration: n
3378 SCEVHandle Start = AddRec->getOperand(0);
3379
Dan Gohmana1af7572009-04-30 20:47:05 +00003380 // Determine the minimum constant start value.
3381 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3382 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3383 APInt::getMinValue(BitWidth));
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00003384
Dan Gohmana1af7572009-04-30 20:47:05 +00003385 // If we know that the condition is true in order to enter the loop,
3386 // then we know that it will run exactly (m-n)/s times. Otherwise, we
3387 // only know if will execute (max(m,n)-n)/s times. In both cases, the
3388 // division must round up.
3389 SCEVHandle End = RHS;
3390 if (!isLoopGuardedByCond(L,
3391 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3392 getMinusSCEV(Start, Step), RHS))
3393 End = isSigned ? getSMaxExpr(RHS, Start)
3394 : getUMaxExpr(RHS, Start);
3395
3396 // Determine the maximum constant end value.
3397 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3398 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3399 APInt::getMaxValue(BitWidth));
3400
3401 // Finally, we subtract these two values and divide, rounding up, to get
3402 // the number of times the backedge is executed.
3403 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3404 getAddExpr(Step, NegOne)),
3405 Step);
3406
3407 // The maximum backedge count is similar, except using the minimum start
3408 // value and the maximum end value.
3409 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3410 MinStart),
3411 getAddExpr(Step, NegOne)),
3412 Step);
3413
3414 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00003415 }
3416
3417 return UnknownValue;
3418}
3419
Chris Lattner53e677a2004-04-02 20:23:17 +00003420/// getNumIterationsInRange - Return the number of iterations of this loop that
3421/// produce values in the specified constant range. Another way of looking at
3422/// this is that it returns the first iteration number where the value is not in
3423/// the condition, thus computing the exit count. If the iteration count can't
3424/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman246b2562007-10-22 18:31:58 +00003425SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3426 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00003427 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003428 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003429
3430 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00003431 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00003432 if (!SC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003433 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00003434 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3435 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00003436 if (const SCEVAddRecExpr *ShiftedAddRec =
3437 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00003438 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00003439 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00003440 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003441 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003442 }
3443
3444 // The only time we can solve this is when we have all constant indices.
3445 // Otherwise, we cannot determine the overflow conditions.
3446 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3447 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003448 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003449
3450
3451 // Okay at this point we know that all elements of the chrec are constants and
3452 // that the start element is zero.
3453
3454 // First check to see if the range contains zero. If not, the first
3455 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003456 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00003457 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman246b2562007-10-22 18:31:58 +00003458 return SE.getConstant(ConstantInt::get(getType(),0));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003459
Chris Lattner53e677a2004-04-02 20:23:17 +00003460 if (isAffine()) {
3461 // If this is an affine expression then we have this situation:
3462 // Solve {0,+,A} in Range === Ax in Range
3463
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003464 // We know that zero is in the range. If A is positive then we know that
3465 // the upper value of the range must be the first possible exit value.
3466 // If A is negative then the lower of the range is the last possible loop
3467 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00003468 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003469 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3470 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00003471
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003472 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00003473 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00003474 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00003475
3476 // Evaluate at the exit value. If we really did fall out of the valid
3477 // range, then we computed our trip count, otherwise wrap around or other
3478 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00003479 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003480 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003481 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003482
3483 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00003484 assert(Range.contains(
3485 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003486 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00003487 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00003488 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00003489 } else if (isQuadratic()) {
3490 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3491 // quadratic equation to solve it. To do this, we must frame our problem in
3492 // terms of figuring out when zero is crossed, instead of when
3493 // Range.getUpper() is crossed.
3494 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00003495 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3496 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003497
3498 // Next, solve the constructed addrec
3499 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00003500 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00003501 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3502 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00003503 if (R1) {
3504 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003505 if (ConstantInt *CB =
3506 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003507 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00003508 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00003509 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003510
Chris Lattner53e677a2004-04-02 20:23:17 +00003511 // Make sure the root is not off by one. The returned iteration should
3512 // not be in the range, but the previous one should be. When solving
3513 // for "X*X < 5", for example, we should not return a root of 2.
3514 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003515 R1->getValue(),
3516 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003517 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003518 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00003519 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003520
Dan Gohman246b2562007-10-22 18:31:58 +00003521 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003522 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00003523 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003524 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003525 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003526
Chris Lattner53e677a2004-04-02 20:23:17 +00003527 // If R1 was not in the range, then it is a good return value. Make
3528 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00003529 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00003530 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003531 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00003532 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003533 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00003534 }
3535 }
3536 }
3537
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003538 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003539}
3540
3541
3542
3543//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00003544// SCEVCallbackVH Class Implementation
3545//===----------------------------------------------------------------------===//
3546
3547void SCEVCallbackVH::deleted() {
3548 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3549 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3550 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00003551 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
3552 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00003553 SE->Scalars.erase(getValPtr());
3554 // this now dangles!
3555}
3556
3557void SCEVCallbackVH::allUsesReplacedWith(Value *) {
3558 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3559
3560 // Forget all the expressions associated with users of the old value,
3561 // so that future queries will recompute the expressions using the new
3562 // value.
3563 SmallVector<User *, 16> Worklist;
3564 Value *Old = getValPtr();
3565 bool DeleteOld = false;
3566 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3567 UI != UE; ++UI)
3568 Worklist.push_back(*UI);
3569 while (!Worklist.empty()) {
3570 User *U = Worklist.pop_back_val();
3571 // Deleting the Old value will cause this to dangle. Postpone
3572 // that until everything else is done.
3573 if (U == Old) {
3574 DeleteOld = true;
3575 continue;
3576 }
3577 if (PHINode *PN = dyn_cast<PHINode>(U))
3578 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00003579 if (Instruction *I = dyn_cast<Instruction>(U))
3580 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00003581 if (SE->Scalars.erase(U))
3582 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3583 UI != UE; ++UI)
3584 Worklist.push_back(*UI);
3585 }
3586 if (DeleteOld) {
3587 if (PHINode *PN = dyn_cast<PHINode>(Old))
3588 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00003589 if (Instruction *I = dyn_cast<Instruction>(Old))
3590 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00003591 SE->Scalars.erase(Old);
3592 // this now dangles!
3593 }
3594 // this may dangle!
3595}
3596
3597SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
3598 : CallbackVH(V), SE(se) {}
3599
3600//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00003601// ScalarEvolution Class Implementation
3602//===----------------------------------------------------------------------===//
3603
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003604ScalarEvolution::ScalarEvolution()
3605 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3606}
3607
Chris Lattner53e677a2004-04-02 20:23:17 +00003608bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003609 this->F = &F;
3610 LI = &getAnalysis<LoopInfo>();
3611 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00003612 return false;
3613}
3614
3615void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003616 Scalars.clear();
3617 BackedgeTakenCounts.clear();
3618 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00003619 ValuesAtScopes.clear();
Chris Lattner53e677a2004-04-02 20:23:17 +00003620}
3621
3622void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3623 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00003624 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +00003625}
3626
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003627bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00003628 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00003629}
3630
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003631static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00003632 const Loop *L) {
3633 // Print all inner loops first
3634 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3635 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003636
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003637 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003638
Devang Patelb7211a22007-08-21 00:31:24 +00003639 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003640 L->getExitBlocks(ExitBlocks);
3641 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003642 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003643
Dan Gohman46bdfb02009-02-24 18:55:53 +00003644 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3645 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003646 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00003647 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003648 }
3649
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003650 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00003651}
3652
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003653void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003654 // ScalarEvolution's implementaiton of the print method is to print
3655 // out SCEV values of all instructions that are interesting. Doing
3656 // this potentially causes it to create new SCEV objects though,
3657 // which technically conflicts with the const qualifier. This isn't
3658 // observable from outside the class though (the hasSCEV function
3659 // notwithstanding), so casting away the const isn't dangerous.
3660 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003661
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003662 OS << "Classifying expressions for: " << F->getName() << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00003663 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00003664 if (isSCEVable(I->getType())) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00003665 OS << *I;
Dan Gohman8dae1382008-09-14 17:21:12 +00003666 OS << " --> ";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003667 SCEVHandle SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00003668 SV->print(OS);
3669 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003670
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003671 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003672 OS << "Exits: ";
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003673 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003674 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3675 OS << "<<Unknown>>";
3676 } else {
3677 OS << *ExitValue;
3678 }
3679 }
3680
3681
3682 OS << "\n";
3683 }
3684
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003685 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3686 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3687 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00003688}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003689
3690void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3691 raw_os_ostream OS(o);
3692 print(OS, M);
3693}