blob: f45562363a72f908292200f4fc51013da4b2a948 [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
Owen Anderson372b46c2009-06-22 21:39:50 +000017// can handle. These classes are reference counted, managed by the const SCEV*
Chris Lattner53e677a2004-04-02 20:23:17 +000018// 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"
Dan Gohman61ffa8e2009-06-16 19:52:01 +000071#include "llvm/Analysis/ValueTracking.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000072#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000073#include "llvm/Target/TargetData.h"
Chris Lattner95255282006-06-28 23:17:24 +000074#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000075#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000076#include "llvm/Support/ConstantRange.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000077#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000078#include "llvm/Support/InstIterator.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000079#include "llvm/Support/ManagedStatic.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000080#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000081#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000082#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000083#include "llvm/ADT/STLExtras.h"
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
Dan Gohman70a1fe72009-05-18 15:22:39 +0000130bool SCEV::isOne() const {
131 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
132 return SC->getValue()->isOne();
133 return false;
134}
Chris Lattner53e677a2004-04-02 20:23:17 +0000135
Owen Anderson4a7893b2009-06-18 22:25:12 +0000136SCEVCouldNotCompute::SCEVCouldNotCompute(const ScalarEvolution* p) :
137 SCEV(scCouldNotCompute, p) {}
Dan Gohmanf8a8be82009-04-21 23:15:49 +0000138SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
Chris Lattner53e677a2004-04-02 20:23:17 +0000139
140bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000142 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000143}
144
145const Type *SCEVCouldNotCompute::getType() const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000147 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000148}
149
150bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
151 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
152 return false;
153}
154
Owen Anderson372b46c2009-06-22 21:39:50 +0000155const SCEV* SCEVCouldNotCompute::
156replaceSymbolicValuesWithConcrete(const SCEV* Sym,
157 const SCEV* Conc,
Dan Gohman246b2562007-10-22 18:31:58 +0000158 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000159 return this;
160}
161
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000162void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000163 OS << "***COULDNOTCOMPUTE***";
164}
165
166bool SCEVCouldNotCompute::classof(const SCEV *S) {
167 return S->getSCEVType() == scCouldNotCompute;
168}
169
170
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000171// SCEVConstants - Only allow the creation of one SCEVConstant for any
Owen Anderson372b46c2009-06-22 21:39:50 +0000172// particular value. Don't use a const SCEV* here, or else the object will
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000173// never be deleted!
Chris Lattner53e677a2004-04-02 20:23:17 +0000174
Owen Anderson372b46c2009-06-22 21:39:50 +0000175const SCEV* ScalarEvolution::getConstant(ConstantInt *V) {
Owen Anderson08367b62009-06-22 18:25:46 +0000176 SCEVConstant *&R = SCEVConstants[V];
Owen Anderson4a7893b2009-06-18 22:25:12 +0000177 if (R == 0) R = new SCEVConstant(V, this);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000178 return R;
179}
Chris Lattner53e677a2004-04-02 20:23:17 +0000180
Owen Anderson372b46c2009-06-22 21:39:50 +0000181const SCEV* ScalarEvolution::getConstant(const APInt& Val) {
Dan Gohman246b2562007-10-22 18:31:58 +0000182 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000183}
184
Owen Anderson372b46c2009-06-22 21:39:50 +0000185const SCEV*
Dan Gohman6de29f82009-06-15 22:12:54 +0000186ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
187 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
188}
189
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000190const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000191
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000192void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000193 WriteAsOperand(OS, V, false);
194}
Chris Lattner53e677a2004-04-02 20:23:17 +0000195
Dan Gohman84923602009-04-21 01:25:57 +0000196SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
Owen Anderson372b46c2009-06-22 21:39:50 +0000197 const SCEV* op, const Type *ty,
Owen Anderson4a7893b2009-06-18 22:25:12 +0000198 const ScalarEvolution* p)
199 : SCEV(SCEVTy, p), Op(op), Ty(ty) {}
Dan Gohman84923602009-04-21 01:25:57 +0000200
201SCEVCastExpr::~SCEVCastExpr() {}
202
203bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
204 return Op->dominates(BB, DT);
205}
206
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000207// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
Owen Anderson372b46c2009-06-22 21:39:50 +0000208// particular input. Don't use a const SCEV* here, or else the object will
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000209// never be deleted!
Chris Lattner53e677a2004-04-02 20:23:17 +0000210
Owen Anderson372b46c2009-06-22 21:39:50 +0000211SCEVTruncateExpr::SCEVTruncateExpr(const SCEV* op, const Type *ty,
Owen Anderson4a7893b2009-06-18 22:25:12 +0000212 const ScalarEvolution* p)
213 : SCEVCastExpr(scTruncate, op, ty, p) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000214 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
215 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000216 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000217}
Chris Lattner53e677a2004-04-02 20:23:17 +0000218
Chris Lattner53e677a2004-04-02 20:23:17 +0000219
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000220void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000221 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000222}
223
224// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
Owen Anderson372b46c2009-06-22 21:39:50 +0000225// particular input. Don't use a const SCEV* here, or else the object will never
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000226// be deleted!
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000227
Owen Anderson372b46c2009-06-22 21:39:50 +0000228SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEV* op, const Type *ty,
Owen Anderson4a7893b2009-06-18 22:25:12 +0000229 const ScalarEvolution* p)
230 : SCEVCastExpr(scZeroExtend, op, ty, p) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000231 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
232 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000233 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000234}
235
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000236void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000237 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000238}
239
Dan Gohmand19534a2007-06-15 14:38:12 +0000240// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
Owen Anderson372b46c2009-06-22 21:39:50 +0000241// particular input. Don't use a const SCEV* here, or else the object will never
Dan Gohmand19534a2007-06-15 14:38:12 +0000242// be deleted!
Dan Gohmand19534a2007-06-15 14:38:12 +0000243
Owen Anderson372b46c2009-06-22 21:39:50 +0000244SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEV* op, const Type *ty,
Owen Anderson4a7893b2009-06-18 22:25:12 +0000245 const ScalarEvolution* p)
246 : SCEVCastExpr(scSignExtend, op, ty, p) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000247 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
248 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000249 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000250}
251
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000252void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000253 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000254}
255
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000256// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
Owen Anderson372b46c2009-06-22 21:39:50 +0000257// particular input. Don't use a const SCEV* here, or else the object will never
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000258// be deleted!
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000259
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000260void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000261 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
262 const char *OpStr = getOperationStr();
263 OS << "(" << *Operands[0];
264 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
265 OS << OpStr << *Operands[i];
266 OS << ")";
267}
268
Owen Anderson372b46c2009-06-22 21:39:50 +0000269const SCEV* SCEVCommutativeExpr::
270replaceSymbolicValuesWithConcrete(const SCEV* Sym,
271 const SCEV* Conc,
Dan Gohman246b2562007-10-22 18:31:58 +0000272 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000273 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000274 const SCEV* H =
Dan Gohman246b2562007-10-22 18:31:58 +0000275 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000276 if (H != getOperand(i)) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000277 SmallVector<const SCEV*, 8> NewOps;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000278 NewOps.reserve(getNumOperands());
279 for (unsigned j = 0; j != i; ++j)
280 NewOps.push_back(getOperand(j));
281 NewOps.push_back(H);
282 for (++i; i != e; ++i)
283 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000284 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000285
286 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000287 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000288 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000289 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000290 else if (isa<SCEVSMaxExpr>(this))
291 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000292 else if (isa<SCEVUMaxExpr>(this))
293 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000294 else
295 assert(0 && "Unknown commutative expr!");
296 }
297 }
298 return this;
299}
300
Dan Gohmanecb403a2009-05-07 14:00:19 +0000301bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000302 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
303 if (!getOperand(i)->dominates(BB, DT))
304 return false;
305 }
306 return true;
307}
308
Chris Lattner4dc534c2005-02-13 04:37:18 +0000309
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000310// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Owen Anderson372b46c2009-06-22 21:39:50 +0000311// input. Don't use a const SCEV* here, or else the object will never be
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000312// deleted!
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000313
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000314bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
315 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
316}
317
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000318void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000319 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000320}
321
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000322const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000323 // In most cases the types of LHS and RHS will be the same, but in some
324 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
325 // depend on the type for correctness, but handling types carefully can
326 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
327 // a pointer type than the RHS, so use the RHS' type here.
328 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000329}
330
331// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
Owen Anderson372b46c2009-06-22 21:39:50 +0000332// particular input. Don't use a const SCEV* here, or else the object will never
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000333// be deleted!
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000334
Owen Anderson372b46c2009-06-22 21:39:50 +0000335const SCEV* SCEVAddRecExpr::
336replaceSymbolicValuesWithConcrete(const SCEV* Sym,
337 const SCEV* Conc,
Dan Gohman246b2562007-10-22 18:31:58 +0000338 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000339 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000340 const SCEV* H =
Dan Gohman246b2562007-10-22 18:31:58 +0000341 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000342 if (H != getOperand(i)) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000343 SmallVector<const SCEV*, 8> NewOps;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000344 NewOps.reserve(getNumOperands());
345 for (unsigned j = 0; j != i; ++j)
346 NewOps.push_back(getOperand(j));
347 NewOps.push_back(H);
348 for (++i; i != e; ++i)
349 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000350 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000351
Dan Gohman246b2562007-10-22 18:31:58 +0000352 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000353 }
354 }
355 return this;
356}
357
358
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000359bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
360 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000361 // contain L and if the start is invariant.
Dan Gohmana3035a62009-05-20 01:01:24 +0000362 // Add recurrences are never invariant in the function-body (null loop).
363 return QueryLoop &&
364 !QueryLoop->contains(L->getHeader()) &&
Chris Lattnerff2006a2005-08-16 00:37:01 +0000365 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000366}
367
368
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000369void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000370 OS << "{" << *Operands[0];
371 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
372 OS << ",+," << *Operands[i];
373 OS << "}<" << L->getHeader()->getName() + ">";
374}
Chris Lattner53e677a2004-04-02 20:23:17 +0000375
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000376// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
Owen Anderson372b46c2009-06-22 21:39:50 +0000377// value. Don't use a const SCEV* here, or else the object will never be
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000378// deleted!
Chris Lattner53e677a2004-04-02 20:23:17 +0000379
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000380bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
381 // All non-instruction values are loop invariant. All instructions are loop
382 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000383 // Instructions are never considered invariant in the function body
384 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000385 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmana3035a62009-05-20 01:01:24 +0000386 return L && !L->contains(I->getParent());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000387 return true;
388}
Chris Lattner53e677a2004-04-02 20:23:17 +0000389
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000390bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
391 if (Instruction *I = dyn_cast<Instruction>(getValue()))
392 return DT->dominates(I->getParent(), BB);
393 return true;
394}
395
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000396const Type *SCEVUnknown::getType() const {
397 return V->getType();
398}
Chris Lattner53e677a2004-04-02 20:23:17 +0000399
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000400void SCEVUnknown::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000401 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000402}
403
Chris Lattner8d741b82004-06-20 06:23:15 +0000404//===----------------------------------------------------------------------===//
405// SCEV Utilities
406//===----------------------------------------------------------------------===//
407
408namespace {
409 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
410 /// than the complexity of the RHS. This comparator is used to canonicalize
411 /// expressions.
Dan Gohman72861302009-05-07 14:39:04 +0000412 class VISIBILITY_HIDDEN SCEVComplexityCompare {
413 LoopInfo *LI;
414 public:
415 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
416
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000417 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman72861302009-05-07 14:39:04 +0000418 // Primarily, sort the SCEVs by their getSCEVType().
419 if (LHS->getSCEVType() != RHS->getSCEVType())
420 return LHS->getSCEVType() < RHS->getSCEVType();
421
422 // Aside from the getSCEVType() ordering, the particular ordering
423 // isn't very important except that it's beneficial to be consistent,
424 // so that (a + b) and (b + a) don't end up as different expressions.
425
426 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
427 // not as complete as it could be.
428 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
429 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
430
Dan Gohman5be18e82009-05-19 02:15:55 +0000431 // Order pointer values after integer values. This helps SCEVExpander
432 // form GEPs.
433 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
434 return false;
435 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
436 return true;
437
Dan Gohman72861302009-05-07 14:39:04 +0000438 // Compare getValueID values.
439 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
440 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
441
442 // Sort arguments by their position.
443 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
444 const Argument *RA = cast<Argument>(RU->getValue());
445 return LA->getArgNo() < RA->getArgNo();
446 }
447
448 // For instructions, compare their loop depth, and their opcode.
449 // This is pretty loose.
450 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
451 Instruction *RV = cast<Instruction>(RU->getValue());
452
453 // Compare loop depths.
454 if (LI->getLoopDepth(LV->getParent()) !=
455 LI->getLoopDepth(RV->getParent()))
456 return LI->getLoopDepth(LV->getParent()) <
457 LI->getLoopDepth(RV->getParent());
458
459 // Compare opcodes.
460 if (LV->getOpcode() != RV->getOpcode())
461 return LV->getOpcode() < RV->getOpcode();
462
463 // Compare the number of operands.
464 if (LV->getNumOperands() != RV->getNumOperands())
465 return LV->getNumOperands() < RV->getNumOperands();
466 }
467
468 return false;
469 }
470
Dan Gohman4dfad292009-06-14 22:51:25 +0000471 // Compare constant values.
472 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
473 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
474 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
475 }
476
477 // Compare addrec loop depths.
478 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
479 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
480 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
481 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
482 }
Dan Gohman72861302009-05-07 14:39:04 +0000483
484 // Lexicographically compare n-ary expressions.
485 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
486 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
487 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
488 if (i >= RC->getNumOperands())
489 return false;
490 if (operator()(LC->getOperand(i), RC->getOperand(i)))
491 return true;
492 if (operator()(RC->getOperand(i), LC->getOperand(i)))
493 return false;
494 }
495 return LC->getNumOperands() < RC->getNumOperands();
496 }
497
Dan Gohmana6b35e22009-05-07 19:23:21 +0000498 // Lexicographically compare udiv expressions.
499 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
500 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
501 if (operator()(LC->getLHS(), RC->getLHS()))
502 return true;
503 if (operator()(RC->getLHS(), LC->getLHS()))
504 return false;
505 if (operator()(LC->getRHS(), RC->getRHS()))
506 return true;
507 if (operator()(RC->getRHS(), LC->getRHS()))
508 return false;
509 return false;
510 }
511
Dan Gohman72861302009-05-07 14:39:04 +0000512 // Compare cast expressions by operand.
513 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
514 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
515 return operator()(LC->getOperand(), RC->getOperand());
516 }
517
518 assert(0 && "Unknown SCEV kind!");
519 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000520 }
521 };
522}
523
524/// GroupByComplexity - Given a list of SCEV objects, order them by their
525/// complexity, and group objects of the same complexity together by value.
526/// When this routine is finished, we know that any duplicates in the vector are
527/// consecutive and that complexity is monotonically increasing.
528///
529/// Note that we go take special precautions to ensure that we get determinstic
530/// results from this routine. In other words, we don't want the results of
531/// this to depend on where the addresses of various SCEV objects happened to
532/// land in memory.
533///
Owen Anderson372b46c2009-06-22 21:39:50 +0000534static void GroupByComplexity(SmallVectorImpl<const SCEV*> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000535 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000536 if (Ops.size() < 2) return; // Noop
537 if (Ops.size() == 2) {
538 // This is the common case, which also happens to be trivially simple.
539 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000540 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000541 std::swap(Ops[0], Ops[1]);
542 return;
543 }
544
545 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000546 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000547
548 // Now that we are sorted by complexity, group elements of the same
549 // complexity. Note that this is, at worst, N^2, but the vector is likely to
550 // be extremely short in practice. Note that we take this approach because we
551 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000552 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000553 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000554 unsigned Complexity = S->getSCEVType();
555
556 // If there are any objects of the same complexity and same value as this
557 // one, group them.
558 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
559 if (Ops[j] == S) { // Found a duplicate.
560 // Move it to immediately after i'th element.
561 std::swap(Ops[i+1], Ops[j]);
562 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000563 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000564 }
565 }
566 }
567}
568
Chris Lattner53e677a2004-04-02 20:23:17 +0000569
Chris Lattner53e677a2004-04-02 20:23:17 +0000570
571//===----------------------------------------------------------------------===//
572// Simple SCEV method implementations
573//===----------------------------------------------------------------------===//
574
Eli Friedmanb42a6262008-08-04 23:49:06 +0000575/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000576/// Assume, K > 0.
Owen Anderson372b46c2009-06-22 21:39:50 +0000577static const SCEV* BinomialCoefficient(const SCEV* It, unsigned K,
Eli Friedmanb42a6262008-08-04 23:49:06 +0000578 ScalarEvolution &SE,
Dan Gohman2d1be872009-04-16 03:18:22 +0000579 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000580 // Handle the simplest case efficiently.
581 if (K == 1)
582 return SE.getTruncateOrZeroExtend(It, ResultTy);
583
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000584 // We are using the following formula for BC(It, K):
585 //
586 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
587 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000588 // Suppose, W is the bitwidth of the return value. We must be prepared for
589 // overflow. Hence, we must assure that the result of our computation is
590 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
591 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000592 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000593 // However, this code doesn't use exactly that formula; the formula it uses
594 // is something like the following, where T is the number of factors of 2 in
595 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
596 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000597 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000598 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000599 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000600 // This formula is trivially equivalent to the previous formula. However,
601 // this formula can be implemented much more efficiently. The trick is that
602 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
603 // arithmetic. To do exact division in modular arithmetic, all we have
604 // to do is multiply by the inverse. Therefore, this step can be done at
605 // width W.
606 //
607 // The next issue is how to safely do the division by 2^T. The way this
608 // is done is by doing the multiplication step at a width of at least W + T
609 // bits. This way, the bottom W+T bits of the product are accurate. Then,
610 // when we perform the division by 2^T (which is equivalent to a right shift
611 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
612 // truncated out after the division by 2^T.
613 //
614 // In comparison to just directly using the first formula, this technique
615 // is much more efficient; using the first formula requires W * K bits,
616 // but this formula less than W + K bits. Also, the first formula requires
617 // a division step, whereas this formula only requires multiplies and shifts.
618 //
619 // It doesn't matter whether the subtraction step is done in the calculation
620 // width or the input iteration count's width; if the subtraction overflows,
621 // the result must be zero anyway. We prefer here to do it in the width of
622 // the induction variable because it helps a lot for certain cases; CodeGen
623 // isn't smart enough to ignore the overflow, which leads to much less
624 // efficient code if the width of the subtraction is wider than the native
625 // register width.
626 //
627 // (It's possible to not widen at all by pulling out factors of 2 before
628 // the multiplication; for example, K=2 can be calculated as
629 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
630 // extra arithmetic, so it's not an obvious win, and it gets
631 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000632
Eli Friedmanb42a6262008-08-04 23:49:06 +0000633 // Protection from insane SCEVs; this bound is conservative,
634 // but it probably doesn't matter.
635 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000636 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000637
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000638 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000639
Eli Friedmanb42a6262008-08-04 23:49:06 +0000640 // Calculate K! / 2^T and T; we divide out the factors of two before
641 // multiplying for calculating K! / 2^T to avoid overflow.
642 // Other overflow doesn't matter because we only care about the bottom
643 // W bits of the result.
644 APInt OddFactorial(W, 1);
645 unsigned T = 1;
646 for (unsigned i = 3; i <= K; ++i) {
647 APInt Mult(W, i);
648 unsigned TwoFactors = Mult.countTrailingZeros();
649 T += TwoFactors;
650 Mult = Mult.lshr(TwoFactors);
651 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000652 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000653
Eli Friedmanb42a6262008-08-04 23:49:06 +0000654 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000655 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000656
657 // Calcuate 2^T, at width T+W.
658 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
659
660 // Calculate the multiplicative inverse of K! / 2^T;
661 // this multiplication factor will perform the exact division by
662 // K! / 2^T.
663 APInt Mod = APInt::getSignedMinValue(W+1);
664 APInt MultiplyFactor = OddFactorial.zext(W+1);
665 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
666 MultiplyFactor = MultiplyFactor.trunc(W);
667
668 // Calculate the product, at width T+W
669 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
Owen Anderson372b46c2009-06-22 21:39:50 +0000670 const SCEV* Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000671 for (unsigned i = 1; i != K; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000672 const SCEV* S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000673 Dividend = SE.getMulExpr(Dividend,
674 SE.getTruncateOrZeroExtend(S, CalculationTy));
675 }
676
677 // Divide by 2^T
Owen Anderson372b46c2009-06-22 21:39:50 +0000678 const SCEV* DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000679
680 // Truncate the result, and divide by K! / 2^T.
681
682 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
683 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000684}
685
Chris Lattner53e677a2004-04-02 20:23:17 +0000686/// evaluateAtIteration - Return the value of this chain of recurrences at
687/// the specified iteration number. We can evaluate this recurrence by
688/// multiplying each element in the chain by the binomial coefficient
689/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
690///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000691/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000692///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000693/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000694///
Owen Anderson372b46c2009-06-22 21:39:50 +0000695const SCEV* SCEVAddRecExpr::evaluateAtIteration(const SCEV* It,
Dan Gohman246b2562007-10-22 18:31:58 +0000696 ScalarEvolution &SE) const {
Owen Anderson372b46c2009-06-22 21:39:50 +0000697 const SCEV* Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000698 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000699 // The computation is correct in the face of overflow provided that the
700 // multiplication is performed _after_ the evaluation of the binomial
701 // coefficient.
Owen Anderson372b46c2009-06-22 21:39:50 +0000702 const SCEV* Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000703 if (isa<SCEVCouldNotCompute>(Coeff))
704 return Coeff;
705
706 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000707 }
708 return Result;
709}
710
Chris Lattner53e677a2004-04-02 20:23:17 +0000711//===----------------------------------------------------------------------===//
712// SCEV Expression folder implementations
713//===----------------------------------------------------------------------===//
714
Owen Anderson372b46c2009-06-22 21:39:50 +0000715const SCEV* ScalarEvolution::getTruncateExpr(const SCEV* Op,
Dan Gohman99243b32009-05-01 16:44:56 +0000716 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000717 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000718 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000719 assert(isSCEVable(Ty) &&
720 "This is not a conversion to a SCEVable type!");
721 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000722
Dan Gohman622ed672009-05-04 22:02:23 +0000723 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000724 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000725 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000726
Dan Gohman20900ca2009-04-22 16:20:48 +0000727 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000728 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000729 return getTruncateExpr(ST->getOperand(), Ty);
730
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000731 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000732 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000733 return getTruncateOrSignExtend(SS->getOperand(), Ty);
734
735 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000736 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000737 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
738
Dan Gohman6864db62009-06-18 16:24:47 +0000739 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000740 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000741 SmallVector<const SCEV*, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000742 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000743 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
744 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000745 }
746
Owen Anderson08367b62009-06-22 18:25:46 +0000747 SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)];
Owen Anderson4a7893b2009-06-18 22:25:12 +0000748 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty, this);
Chris Lattner53e677a2004-04-02 20:23:17 +0000749 return Result;
750}
751
Owen Anderson372b46c2009-06-22 21:39:50 +0000752const SCEV* ScalarEvolution::getZeroExtendExpr(const SCEV* Op,
Dan Gohman8170a682009-04-16 19:25:55 +0000753 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000754 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000755 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000756 assert(isSCEVable(Ty) &&
757 "This is not a conversion to a SCEVable type!");
758 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000759
Dan Gohman622ed672009-05-04 22:02:23 +0000760 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000761 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000762 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
763 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
764 return getUnknown(C);
765 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000766
Dan Gohman20900ca2009-04-22 16:20:48 +0000767 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000768 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000769 return getZeroExtendExpr(SZ->getOperand(), Ty);
770
Dan Gohman01ecca22009-04-27 20:16:15 +0000771 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000772 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000773 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000774 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000775 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000776 if (AR->isAffine()) {
777 // Check whether the backedge-taken count is SCEVCouldNotCompute.
778 // Note that this serves two purposes: It filters out loops that are
779 // simply not analyzable, and it covers the case where this code is
780 // being called from within backedge-taken count analysis, such that
781 // attempting to ask for the backedge-taken count would likely result
782 // in infinite recursion. In the later case, the analysis code will
783 // cope with a conservative value, and it will take care to purge
784 // that value once it has finished.
Owen Anderson372b46c2009-06-22 21:39:50 +0000785 const SCEV* MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
Dan Gohmana1af7572009-04-30 20:47:05 +0000786 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000787 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000788 // overflow.
Owen Anderson372b46c2009-06-22 21:39:50 +0000789 const SCEV* Start = AR->getStart();
790 const SCEV* Step = AR->getStepRecurrence(*this);
Dan Gohman01ecca22009-04-27 20:16:15 +0000791
792 // Check whether the backedge-taken count can be losslessly casted to
793 // the addrec's type. The count is always unsigned.
Owen Anderson372b46c2009-06-22 21:39:50 +0000794 const SCEV* CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000795 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Owen Anderson372b46c2009-06-22 21:39:50 +0000796 const SCEV* RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000797 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
798 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000799 const Type *WideTy =
800 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000801 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Owen Anderson372b46c2009-06-22 21:39:50 +0000802 const SCEV* ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000803 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000804 getTruncateOrZeroExtend(Step, Start->getType()));
Owen Anderson372b46c2009-06-22 21:39:50 +0000805 const SCEV* Add = getAddExpr(Start, ZMul);
806 const SCEV* OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000807 getAddExpr(getZeroExtendExpr(Start, WideTy),
808 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
809 getZeroExtendExpr(Step, WideTy)));
810 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000811 // Return the expression with the addrec on the outside.
812 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
813 getZeroExtendExpr(Step, Ty),
814 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000815
816 // Similar to above, only this time treat the step value as signed.
817 // This covers loops that count down.
Owen Anderson372b46c2009-06-22 21:39:50 +0000818 const SCEV* SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000819 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000820 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000821 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000822 OperandExtendedAdd =
823 getAddExpr(getZeroExtendExpr(Start, WideTy),
824 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
825 getSignExtendExpr(Step, WideTy)));
826 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000827 // Return the expression with the addrec on the outside.
828 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
829 getSignExtendExpr(Step, Ty),
830 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000831 }
832 }
833 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000834
Owen Anderson08367b62009-06-22 18:25:46 +0000835 SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)];
Owen Anderson4a7893b2009-06-18 22:25:12 +0000836 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty, this);
Chris Lattner53e677a2004-04-02 20:23:17 +0000837 return Result;
838}
839
Owen Anderson372b46c2009-06-22 21:39:50 +0000840const SCEV* ScalarEvolution::getSignExtendExpr(const SCEV* Op,
Dan Gohman01ecca22009-04-27 20:16:15 +0000841 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000842 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000843 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000844 assert(isSCEVable(Ty) &&
845 "This is not a conversion to a SCEVable type!");
846 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000847
Dan Gohman622ed672009-05-04 22:02:23 +0000848 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000849 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000850 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
851 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
852 return getUnknown(C);
853 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000854
Dan Gohman20900ca2009-04-22 16:20:48 +0000855 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000856 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000857 return getSignExtendExpr(SS->getOperand(), Ty);
858
Dan Gohman01ecca22009-04-27 20:16:15 +0000859 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000860 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000861 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000862 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000863 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000864 if (AR->isAffine()) {
865 // Check whether the backedge-taken count is SCEVCouldNotCompute.
866 // Note that this serves two purposes: It filters out loops that are
867 // simply not analyzable, and it covers the case where this code is
868 // being called from within backedge-taken count analysis, such that
869 // attempting to ask for the backedge-taken count would likely result
870 // in infinite recursion. In the later case, the analysis code will
871 // cope with a conservative value, and it will take care to purge
872 // that value once it has finished.
Owen Anderson372b46c2009-06-22 21:39:50 +0000873 const SCEV* MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
Dan Gohmana1af7572009-04-30 20:47:05 +0000874 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000875 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000876 // overflow.
Owen Anderson372b46c2009-06-22 21:39:50 +0000877 const SCEV* Start = AR->getStart();
878 const SCEV* Step = AR->getStepRecurrence(*this);
Dan Gohman01ecca22009-04-27 20:16:15 +0000879
880 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000881 // the addrec's type. The count is always unsigned.
Owen Anderson372b46c2009-06-22 21:39:50 +0000882 const SCEV* CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000883 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Owen Anderson372b46c2009-06-22 21:39:50 +0000884 const SCEV* RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000885 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
886 if (MaxBECount == RecastedMaxBECount) {
Dan Gohman01ecca22009-04-27 20:16:15 +0000887 const Type *WideTy =
888 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000889 // Check whether Start+Step*MaxBECount has no signed overflow.
Owen Anderson372b46c2009-06-22 21:39:50 +0000890 const SCEV* SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000891 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000892 getTruncateOrSignExtend(Step, Start->getType()));
Owen Anderson372b46c2009-06-22 21:39:50 +0000893 const SCEV* Add = getAddExpr(Start, SMul);
894 const SCEV* OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000895 getAddExpr(getSignExtendExpr(Start, WideTy),
896 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
897 getSignExtendExpr(Step, WideTy)));
898 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000899 // Return the expression with the addrec on the outside.
900 return getAddRecExpr(getSignExtendExpr(Start, Ty),
901 getSignExtendExpr(Step, Ty),
902 AR->getLoop());
Dan Gohman01ecca22009-04-27 20:16:15 +0000903 }
904 }
905 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000906
Owen Anderson08367b62009-06-22 18:25:46 +0000907 SCEVSignExtendExpr *&Result = SCEVSignExtends[std::make_pair(Op, Ty)];
Owen Anderson4a7893b2009-06-18 22:25:12 +0000908 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty, this);
Dan Gohmand19534a2007-06-15 14:38:12 +0000909 return Result;
910}
911
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000912/// getAnyExtendExpr - Return a SCEV for the given operand extended with
913/// unspecified bits out to the given type.
914///
Owen Anderson372b46c2009-06-22 21:39:50 +0000915const SCEV* ScalarEvolution::getAnyExtendExpr(const SCEV* Op,
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000916 const Type *Ty) {
917 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
918 "This is not an extending conversion!");
919 assert(isSCEVable(Ty) &&
920 "This is not a conversion to a SCEVable type!");
921 Ty = getEffectiveSCEVType(Ty);
922
923 // Sign-extend negative constants.
924 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
925 if (SC->getValue()->getValue().isNegative())
926 return getSignExtendExpr(Op, Ty);
927
928 // Peel off a truncate cast.
929 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Owen Anderson372b46c2009-06-22 21:39:50 +0000930 const SCEV* NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000931 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
932 return getAnyExtendExpr(NewOp, Ty);
933 return getTruncateOrNoop(NewOp, Ty);
934 }
935
936 // Next try a zext cast. If the cast is folded, use it.
Owen Anderson372b46c2009-06-22 21:39:50 +0000937 const SCEV* ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000938 if (!isa<SCEVZeroExtendExpr>(ZExt))
939 return ZExt;
940
941 // Next try a sext cast. If the cast is folded, use it.
Owen Anderson372b46c2009-06-22 21:39:50 +0000942 const SCEV* SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +0000943 if (!isa<SCEVSignExtendExpr>(SExt))
944 return SExt;
945
946 // If the expression is obviously signed, use the sext cast value.
947 if (isa<SCEVSMaxExpr>(Op))
948 return SExt;
949
950 // Absent any other information, use the zext cast value.
951 return ZExt;
952}
953
Dan Gohmanbd59d7b2009-06-14 22:58:51 +0000954/// CollectAddOperandsWithScales - Process the given Ops list, which is
955/// a list of operands to be added under the given scale, update the given
956/// map. This is a helper function for getAddRecExpr. As an example of
957/// what it does, given a sequence of operands that would form an add
958/// expression like this:
959///
960/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
961///
962/// where A and B are constants, update the map with these values:
963///
964/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
965///
966/// and add 13 + A*B*29 to AccumulatedConstant.
967/// This will allow getAddRecExpr to produce this:
968///
969/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
970///
971/// This form often exposes folding opportunities that are hidden in
972/// the original operand list.
973///
974/// Return true iff it appears that any interesting folding opportunities
975/// may be exposed. This helps getAddRecExpr short-circuit extra work in
976/// the common case where no interesting opportunities are present, and
977/// is also used as a check to avoid infinite recursion.
978///
979static bool
Owen Anderson372b46c2009-06-22 21:39:50 +0000980CollectAddOperandsWithScales(DenseMap<const SCEV*, APInt> &M,
981 SmallVector<const SCEV*, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +0000982 APInt &AccumulatedConstant,
Owen Anderson372b46c2009-06-22 21:39:50 +0000983 const SmallVectorImpl<const SCEV*> &Ops,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +0000984 const APInt &Scale,
985 ScalarEvolution &SE) {
986 bool Interesting = false;
987
988 // Iterate over the add operands.
989 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
990 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
991 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
992 APInt NewScale =
993 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
994 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
995 // A multiplication of a constant with another add; recurse.
996 Interesting |=
997 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
998 cast<SCEVAddExpr>(Mul->getOperand(1))
999 ->getOperands(),
1000 NewScale, SE);
1001 } else {
1002 // A multiplication of a constant with some other value. Update
1003 // the map.
Owen Anderson372b46c2009-06-22 21:39:50 +00001004 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1005 const SCEV* Key = SE.getMulExpr(MulOps);
1006 std::pair<DenseMap<const SCEV*, APInt>::iterator, bool> Pair =
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001007 M.insert(std::make_pair(Key, APInt()));
1008 if (Pair.second) {
1009 Pair.first->second = NewScale;
1010 NewOps.push_back(Pair.first->first);
1011 } else {
1012 Pair.first->second += NewScale;
1013 // The map already had an entry for this value, which may indicate
1014 // a folding opportunity.
1015 Interesting = true;
1016 }
1017 }
1018 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1019 // Pull a buried constant out to the outside.
1020 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1021 Interesting = true;
1022 AccumulatedConstant += Scale * C->getValue()->getValue();
1023 } else {
1024 // An ordinary operand. Update the map.
Owen Anderson372b46c2009-06-22 21:39:50 +00001025 std::pair<DenseMap<const SCEV*, APInt>::iterator, bool> Pair =
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001026 M.insert(std::make_pair(Ops[i], APInt()));
1027 if (Pair.second) {
1028 Pair.first->second = Scale;
1029 NewOps.push_back(Pair.first->first);
1030 } else {
1031 Pair.first->second += Scale;
1032 // The map already had an entry for this value, which may indicate
1033 // a folding opportunity.
1034 Interesting = true;
1035 }
1036 }
1037 }
1038
1039 return Interesting;
1040}
1041
1042namespace {
1043 struct APIntCompare {
1044 bool operator()(const APInt &LHS, const APInt &RHS) const {
1045 return LHS.ult(RHS);
1046 }
1047 };
1048}
1049
Dan Gohman6c0866c2009-05-24 23:45:28 +00001050/// getAddExpr - Get a canonical add expression, or something simpler if
1051/// possible.
Owen Anderson372b46c2009-06-22 21:39:50 +00001052const SCEV* ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV*> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001053 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001054 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001055#ifndef NDEBUG
1056 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1057 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1058 getEffectiveSCEVType(Ops[0]->getType()) &&
1059 "SCEVAddExpr operand types don't match!");
1060#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001061
1062 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001063 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001064
1065 // If there are any constants, fold them together.
1066 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001067 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001068 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001069 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001070 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001071 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001072 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1073 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001074 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001075 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001076 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001077 }
1078
1079 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001080 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001081 Ops.erase(Ops.begin());
1082 --Idx;
1083 }
1084 }
1085
Chris Lattner627018b2004-04-07 16:16:11 +00001086 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001087
Chris Lattner53e677a2004-04-02 20:23:17 +00001088 // Okay, check to see if the same value occurs in the operand list twice. If
1089 // so, merge them together into an multiply expression. Since we sorted the
1090 // list, these values are required to be adjacent.
1091 const Type *Ty = Ops[0]->getType();
1092 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1093 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1094 // Found a match, merge the two values into a multiply, and add any
1095 // remaining values to the result.
Owen Anderson372b46c2009-06-22 21:39:50 +00001096 const SCEV* Two = getIntegerSCEV(2, Ty);
1097 const SCEV* Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001098 if (Ops.size() == 2)
1099 return Mul;
1100 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1101 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +00001102 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001103 }
1104
Dan Gohman728c7f32009-05-08 21:03:19 +00001105 // Check for truncates. If all the operands are truncated from the same
1106 // type, see if factoring out the truncate would permit the result to be
1107 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1108 // if the contents of the resulting outer trunc fold to something simple.
1109 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1110 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1111 const Type *DstType = Trunc->getType();
1112 const Type *SrcType = Trunc->getOperand()->getType();
Owen Anderson372b46c2009-06-22 21:39:50 +00001113 SmallVector<const SCEV*, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001114 bool Ok = true;
1115 // Check all the operands to see if they can be represented in the
1116 // source type of the truncate.
1117 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1118 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1119 if (T->getOperand()->getType() != SrcType) {
1120 Ok = false;
1121 break;
1122 }
1123 LargeOps.push_back(T->getOperand());
1124 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1125 // This could be either sign or zero extension, but sign extension
1126 // is much more likely to be foldable here.
1127 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1128 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001129 SmallVector<const SCEV*, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001130 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1131 if (const SCEVTruncateExpr *T =
1132 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1133 if (T->getOperand()->getType() != SrcType) {
1134 Ok = false;
1135 break;
1136 }
1137 LargeMulOps.push_back(T->getOperand());
1138 } else if (const SCEVConstant *C =
1139 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1140 // This could be either sign or zero extension, but sign extension
1141 // is much more likely to be foldable here.
1142 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1143 } else {
1144 Ok = false;
1145 break;
1146 }
1147 }
1148 if (Ok)
1149 LargeOps.push_back(getMulExpr(LargeMulOps));
1150 } else {
1151 Ok = false;
1152 break;
1153 }
1154 }
1155 if (Ok) {
1156 // Evaluate the expression in the larger type.
Owen Anderson372b46c2009-06-22 21:39:50 +00001157 const SCEV* Fold = getAddExpr(LargeOps);
Dan Gohman728c7f32009-05-08 21:03:19 +00001158 // If it folds to something simple, use it. Otherwise, don't.
1159 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1160 return getTruncateExpr(Fold, DstType);
1161 }
1162 }
1163
1164 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001165 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1166 ++Idx;
1167
1168 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001169 if (Idx < Ops.size()) {
1170 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001171 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001172 // If we have an add, expand the add operands onto the end of the operands
1173 // list.
1174 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1175 Ops.erase(Ops.begin()+Idx);
1176 DeletedAdd = true;
1177 }
1178
1179 // If we deleted at least one add, we added operands to the end of the list,
1180 // and they are not necessarily sorted. Recurse to resort and resimplify
1181 // any operands we just aquired.
1182 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001183 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001184 }
1185
1186 // Skip over the add expression until we get to a multiply.
1187 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1188 ++Idx;
1189
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001190 // Check to see if there are any folding opportunities present with
1191 // operands multiplied by constant values.
1192 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1193 uint64_t BitWidth = getTypeSizeInBits(Ty);
Owen Anderson372b46c2009-06-22 21:39:50 +00001194 DenseMap<const SCEV*, APInt> M;
1195 SmallVector<const SCEV*, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001196 APInt AccumulatedConstant(BitWidth, 0);
1197 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1198 Ops, APInt(BitWidth, 1), *this)) {
1199 // Some interesting folding opportunity is present, so its worthwhile to
1200 // re-generate the operands list. Group the operands by constant scale,
1201 // to avoid multiplying by the same constant scale multiple times.
Owen Anderson372b46c2009-06-22 21:39:50 +00001202 std::map<APInt, SmallVector<const SCEV*, 4>, APIntCompare> MulOpLists;
1203 for (SmallVector<const SCEV*, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001204 E = NewOps.end(); I != E; ++I)
1205 MulOpLists[M.find(*I)->second].push_back(*I);
1206 // Re-generate the operands list.
1207 Ops.clear();
1208 if (AccumulatedConstant != 0)
1209 Ops.push_back(getConstant(AccumulatedConstant));
Owen Anderson372b46c2009-06-22 21:39:50 +00001210 for (std::map<APInt, SmallVector<const SCEV*, 4>, APIntCompare>::iterator I =
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001211 MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1212 if (I->first != 0)
1213 Ops.push_back(getMulExpr(getConstant(I->first), getAddExpr(I->second)));
1214 if (Ops.empty())
1215 return getIntegerSCEV(0, Ty);
1216 if (Ops.size() == 1)
1217 return Ops[0];
1218 return getAddExpr(Ops);
1219 }
1220 }
1221
Chris Lattner53e677a2004-04-02 20:23:17 +00001222 // If we are adding something to a multiply expression, make sure the
1223 // something is not already an operand of the multiply. If so, merge it into
1224 // the multiply.
1225 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001226 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001227 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001228 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001229 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001230 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001231 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Owen Anderson372b46c2009-06-22 21:39:50 +00001232 const SCEV* InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001233 if (Mul->getNumOperands() != 2) {
1234 // If the multiply has more than two operands, we must get the
1235 // Y*Z term.
Owen Anderson372b46c2009-06-22 21:39:50 +00001236 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001237 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001238 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001239 }
Owen Anderson372b46c2009-06-22 21:39:50 +00001240 const SCEV* One = getIntegerSCEV(1, Ty);
1241 const SCEV* AddOne = getAddExpr(InnerMul, One);
1242 const SCEV* OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001243 if (Ops.size() == 2) return OuterMul;
1244 if (AddOp < Idx) {
1245 Ops.erase(Ops.begin()+AddOp);
1246 Ops.erase(Ops.begin()+Idx-1);
1247 } else {
1248 Ops.erase(Ops.begin()+Idx);
1249 Ops.erase(Ops.begin()+AddOp-1);
1250 }
1251 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001252 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001253 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001254
Chris Lattner53e677a2004-04-02 20:23:17 +00001255 // Check this multiply against other multiplies being added together.
1256 for (unsigned OtherMulIdx = Idx+1;
1257 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1258 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001259 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001260 // If MulOp occurs in OtherMul, we can fold the two multiplies
1261 // together.
1262 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1263 OMulOp != e; ++OMulOp)
1264 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1265 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Owen Anderson372b46c2009-06-22 21:39:50 +00001266 const SCEV* InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001267 if (Mul->getNumOperands() != 2) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001268 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001269 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001270 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001271 }
Owen Anderson372b46c2009-06-22 21:39:50 +00001272 const SCEV* InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001273 if (OtherMul->getNumOperands() != 2) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001274 SmallVector<const SCEV*, 4> MulOps(OtherMul->op_begin(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001275 OtherMul->op_end());
1276 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001277 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001278 }
Owen Anderson372b46c2009-06-22 21:39:50 +00001279 const SCEV* InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1280 const SCEV* OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001281 if (Ops.size() == 2) return OuterMul;
1282 Ops.erase(Ops.begin()+Idx);
1283 Ops.erase(Ops.begin()+OtherMulIdx-1);
1284 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001285 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001286 }
1287 }
1288 }
1289 }
1290
1291 // If there are any add recurrences in the operands list, see if any other
1292 // added values are loop invariant. If so, we can fold them into the
1293 // recurrence.
1294 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1295 ++Idx;
1296
1297 // Scan over all recurrences, trying to fold loop invariants into them.
1298 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1299 // Scan all of the other operands to this add and add them to the vector if
1300 // they are loop invariant w.r.t. the recurrence.
Owen Anderson372b46c2009-06-22 21:39:50 +00001301 SmallVector<const SCEV*, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001302 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001303 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1304 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1305 LIOps.push_back(Ops[i]);
1306 Ops.erase(Ops.begin()+i);
1307 --i; --e;
1308 }
1309
1310 // If we found some loop invariants, fold them into the recurrence.
1311 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001312 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001313 LIOps.push_back(AddRec->getStart());
1314
Owen Anderson372b46c2009-06-22 21:39:50 +00001315 SmallVector<const SCEV*, 4> AddRecOps(AddRec->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001316 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001317 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001318
Owen Anderson372b46c2009-06-22 21:39:50 +00001319 const SCEV* NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001320 // If all of the other operands were loop invariant, we are done.
1321 if (Ops.size() == 1) return NewRec;
1322
1323 // Otherwise, add the folded AddRec by the non-liv parts.
1324 for (unsigned i = 0;; ++i)
1325 if (Ops[i] == AddRec) {
1326 Ops[i] = NewRec;
1327 break;
1328 }
Dan Gohman246b2562007-10-22 18:31:58 +00001329 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001330 }
1331
1332 // Okay, if there weren't any loop invariants to be folded, check to see if
1333 // there are multiple AddRec's with the same loop induction variable being
1334 // added together. If so, we can fold them.
1335 for (unsigned OtherIdx = Idx+1;
1336 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1337 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001338 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001339 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1340 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Owen Anderson372b46c2009-06-22 21:39:50 +00001341 SmallVector<const SCEV*, 4> NewOps(AddRec->op_begin(), AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001342 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1343 if (i >= NewOps.size()) {
1344 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1345 OtherAddRec->op_end());
1346 break;
1347 }
Dan Gohman246b2562007-10-22 18:31:58 +00001348 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001349 }
Owen Anderson372b46c2009-06-22 21:39:50 +00001350 const SCEV* NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001351
1352 if (Ops.size() == 2) return NewAddRec;
1353
1354 Ops.erase(Ops.begin()+Idx);
1355 Ops.erase(Ops.begin()+OtherIdx-1);
1356 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001357 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001358 }
1359 }
1360
1361 // Otherwise couldn't fold anything into this recurrence. Move onto the
1362 // next one.
1363 }
1364
1365 // Okay, it looks like we really DO need an add expr. Check to see if we
1366 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001367 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Anderson08367b62009-06-22 18:25:46 +00001368 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr,
Chris Lattnerb3364092006-10-04 21:49:37 +00001369 SCEVOps)];
Owen Anderson4a7893b2009-06-18 22:25:12 +00001370 if (Result == 0) Result = new SCEVAddExpr(Ops, this);
Chris Lattner53e677a2004-04-02 20:23:17 +00001371 return Result;
1372}
1373
1374
Dan Gohman6c0866c2009-05-24 23:45:28 +00001375/// getMulExpr - Get a canonical multiply expression, or something simpler if
1376/// possible.
Owen Anderson372b46c2009-06-22 21:39:50 +00001377const SCEV* ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV*> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001378 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00001379#ifndef NDEBUG
1380 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1381 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1382 getEffectiveSCEVType(Ops[0]->getType()) &&
1383 "SCEVMulExpr operand types don't match!");
1384#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001385
1386 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001387 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001388
1389 // If there are any constants, fold them together.
1390 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001391 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001392
1393 // C1*(C2+V) -> C1*C2 + C1*V
1394 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001395 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001396 if (Add->getNumOperands() == 2 &&
1397 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001398 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1399 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001400
1401
1402 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001403 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001404 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001405 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1406 RHSC->getValue()->getValue());
1407 Ops[0] = getConstant(Fold);
1408 Ops.erase(Ops.begin()+1); // Erase the folded element
1409 if (Ops.size() == 1) return Ops[0];
1410 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001411 }
1412
1413 // If we are left with a constant one being multiplied, strip it off.
1414 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1415 Ops.erase(Ops.begin());
1416 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001417 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001418 // If we have a multiply of zero, it will always be zero.
1419 return Ops[0];
1420 }
1421 }
1422
1423 // Skip over the add expression until we get to a multiply.
1424 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1425 ++Idx;
1426
1427 if (Ops.size() == 1)
1428 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001429
Chris Lattner53e677a2004-04-02 20:23:17 +00001430 // If there are mul operands inline them all into this expression.
1431 if (Idx < Ops.size()) {
1432 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001433 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001434 // If we have an mul, expand the mul operands onto the end of the operands
1435 // list.
1436 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1437 Ops.erase(Ops.begin()+Idx);
1438 DeletedMul = true;
1439 }
1440
1441 // If we deleted at least one mul, we added operands to the end of the list,
1442 // and they are not necessarily sorted. Recurse to resort and resimplify
1443 // any operands we just aquired.
1444 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001445 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001446 }
1447
1448 // If there are any add recurrences in the operands list, see if any other
1449 // added values are loop invariant. If so, we can fold them into the
1450 // recurrence.
1451 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1452 ++Idx;
1453
1454 // Scan over all recurrences, trying to fold loop invariants into them.
1455 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1456 // Scan all of the other operands to this mul and add them to the vector if
1457 // they are loop invariant w.r.t. the recurrence.
Owen Anderson372b46c2009-06-22 21:39:50 +00001458 SmallVector<const SCEV*, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001459 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001460 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1461 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1462 LIOps.push_back(Ops[i]);
1463 Ops.erase(Ops.begin()+i);
1464 --i; --e;
1465 }
1466
1467 // If we found some loop invariants, fold them into the recurrence.
1468 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001469 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Owen Anderson372b46c2009-06-22 21:39:50 +00001470 SmallVector<const SCEV*, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001471 NewOps.reserve(AddRec->getNumOperands());
1472 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001473 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001474 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001475 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001476 } else {
1477 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001478 SmallVector<const SCEV*, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001479 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001480 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001481 }
1482 }
1483
Owen Anderson372b46c2009-06-22 21:39:50 +00001484 const SCEV* NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001485
1486 // If all of the other operands were loop invariant, we are done.
1487 if (Ops.size() == 1) return NewRec;
1488
1489 // Otherwise, multiply the folded AddRec by the non-liv parts.
1490 for (unsigned i = 0;; ++i)
1491 if (Ops[i] == AddRec) {
1492 Ops[i] = NewRec;
1493 break;
1494 }
Dan Gohman246b2562007-10-22 18:31:58 +00001495 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001496 }
1497
1498 // Okay, if there weren't any loop invariants to be folded, check to see if
1499 // there are multiple AddRec's with the same loop induction variable being
1500 // multiplied together. If so, we can fold them.
1501 for (unsigned OtherIdx = Idx+1;
1502 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1503 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001504 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001505 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1506 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001507 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Owen Anderson372b46c2009-06-22 21:39:50 +00001508 const SCEV* NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001509 G->getStart());
Owen Anderson372b46c2009-06-22 21:39:50 +00001510 const SCEV* B = F->getStepRecurrence(*this);
1511 const SCEV* D = G->getStepRecurrence(*this);
1512 const SCEV* NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001513 getMulExpr(G, B),
1514 getMulExpr(B, D));
Owen Anderson372b46c2009-06-22 21:39:50 +00001515 const SCEV* NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001516 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001517 if (Ops.size() == 2) return NewAddRec;
1518
1519 Ops.erase(Ops.begin()+Idx);
1520 Ops.erase(Ops.begin()+OtherIdx-1);
1521 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001522 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001523 }
1524 }
1525
1526 // Otherwise couldn't fold anything into this recurrence. Move onto the
1527 // next one.
1528 }
1529
1530 // Okay, it looks like we really DO need an mul expr. Check to see if we
1531 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001532 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Anderson08367b62009-06-22 18:25:46 +00001533 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr,
Chris Lattnerb3364092006-10-04 21:49:37 +00001534 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001535 if (Result == 0)
Owen Anderson4a7893b2009-06-18 22:25:12 +00001536 Result = new SCEVMulExpr(Ops, this);
Chris Lattner53e677a2004-04-02 20:23:17 +00001537 return Result;
1538}
1539
Dan Gohman6c0866c2009-05-24 23:45:28 +00001540/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1541/// possible.
Owen Anderson372b46c2009-06-22 21:39:50 +00001542const SCEV* ScalarEvolution::getUDivExpr(const SCEV* LHS,
1543 const SCEV* RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001544 assert(getEffectiveSCEVType(LHS->getType()) ==
1545 getEffectiveSCEVType(RHS->getType()) &&
1546 "SCEVUDivExpr operand types don't match!");
1547
Dan Gohman622ed672009-05-04 22:02:23 +00001548 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001549 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky789558d2009-01-13 09:18:58 +00001550 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001551 if (RHSC->isZero())
1552 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001553
Dan Gohman185cf032009-05-08 20:18:49 +00001554 // Determine if the division can be folded into the operands of
1555 // its operands.
1556 // TODO: Generalize this to non-constants by using known-bits information.
1557 const Type *Ty = LHS->getType();
1558 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1559 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1560 // For non-power-of-two values, effectively round the value up to the
1561 // nearest power of two.
1562 if (!RHSC->getValue()->getValue().isPowerOf2())
1563 ++MaxShiftAmt;
1564 const IntegerType *ExtTy =
1565 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1566 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1567 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1568 if (const SCEVConstant *Step =
1569 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1570 if (!Step->getValue()->getValue()
1571 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001572 getZeroExtendExpr(AR, ExtTy) ==
1573 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1574 getZeroExtendExpr(Step, ExtTy),
1575 AR->getLoop())) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001576 SmallVector<const SCEV*, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001577 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1578 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1579 return getAddRecExpr(Operands, AR->getLoop());
1580 }
1581 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001582 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001583 SmallVector<const SCEV*, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001584 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1585 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1586 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001587 // Find an operand that's safely divisible.
1588 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001589 const SCEV* Op = M->getOperand(i);
1590 const SCEV* Div = getUDivExpr(Op, RHSC);
Dan Gohman185cf032009-05-08 20:18:49 +00001591 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001592 const SmallVectorImpl<const SCEV*> &MOperands = M->getOperands();
1593 Operands = SmallVector<const SCEV*, 4>(MOperands.begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001594 MOperands.end());
Dan Gohman185cf032009-05-08 20:18:49 +00001595 Operands[i] = Div;
1596 return getMulExpr(Operands);
1597 }
1598 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001599 }
Dan Gohman185cf032009-05-08 20:18:49 +00001600 // (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 +00001601 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001602 SmallVector<const SCEV*, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001603 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1604 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1605 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1606 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001607 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001608 const SCEV* Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohman185cf032009-05-08 20:18:49 +00001609 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1610 break;
1611 Operands.push_back(Op);
1612 }
1613 if (Operands.size() == A->getNumOperands())
1614 return getAddExpr(Operands);
1615 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001616 }
Dan Gohman185cf032009-05-08 20:18:49 +00001617
1618 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001619 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001620 Constant *LHSCV = LHSC->getValue();
1621 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001622 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001623 }
1624 }
1625
Owen Anderson08367b62009-06-22 18:25:46 +00001626 SCEVUDivExpr *&Result = SCEVUDivs[std::make_pair(LHS, RHS)];
Owen Anderson4a7893b2009-06-18 22:25:12 +00001627 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS, this);
Chris Lattner53e677a2004-04-02 20:23:17 +00001628 return Result;
1629}
1630
1631
Dan Gohman6c0866c2009-05-24 23:45:28 +00001632/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1633/// Simplify the expression as much as possible.
Owen Anderson372b46c2009-06-22 21:39:50 +00001634const SCEV* ScalarEvolution::getAddRecExpr(const SCEV* Start,
1635 const SCEV* Step, const Loop *L) {
1636 SmallVector<const SCEV*, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001637 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001638 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001639 if (StepChrec->getLoop() == L) {
1640 Operands.insert(Operands.end(), StepChrec->op_begin(),
1641 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001642 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001643 }
1644
1645 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001646 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001647}
1648
Dan Gohman6c0866c2009-05-24 23:45:28 +00001649/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1650/// Simplify the expression as much as possible.
Owen Anderson372b46c2009-06-22 21:39:50 +00001651const SCEV* ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV*> &Operands,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00001652 const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001653 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001654#ifndef NDEBUG
1655 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1656 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1657 getEffectiveSCEVType(Operands[0]->getType()) &&
1658 "SCEVAddRecExpr operand types don't match!");
1659#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001660
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001661 if (Operands.back()->isZero()) {
1662 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001663 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001664 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001665
Dan Gohmand9cc7492008-08-08 18:33:12 +00001666 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001667 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmand9cc7492008-08-08 18:33:12 +00001668 const Loop* NestedLoop = NestedAR->getLoop();
1669 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Owen Anderson372b46c2009-06-22 21:39:50 +00001670 SmallVector<const SCEV*, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001671 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001672 Operands[0] = NestedAR->getStart();
1673 NestedOperands[0] = getAddRecExpr(Operands, L);
1674 return getAddRecExpr(NestedOperands, NestedLoop);
1675 }
1676 }
1677
Dan Gohman35738ac2009-05-04 22:30:44 +00001678 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
Owen Anderson08367b62009-06-22 18:25:46 +00001679 SCEVAddRecExpr *&Result = SCEVAddRecExprs[std::make_pair(L, SCEVOps)];
Owen Anderson4a7893b2009-06-18 22:25:12 +00001680 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L, this);
Chris Lattner53e677a2004-04-02 20:23:17 +00001681 return Result;
1682}
1683
Owen Anderson372b46c2009-06-22 21:39:50 +00001684const SCEV* ScalarEvolution::getSMaxExpr(const SCEV* LHS,
1685 const SCEV* RHS) {
1686 SmallVector<const SCEV*, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001687 Ops.push_back(LHS);
1688 Ops.push_back(RHS);
1689 return getSMaxExpr(Ops);
1690}
1691
Owen Anderson372b46c2009-06-22 21:39:50 +00001692const SCEV*
1693ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV*> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001694 assert(!Ops.empty() && "Cannot get empty smax!");
1695 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001696#ifndef NDEBUG
1697 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1698 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1699 getEffectiveSCEVType(Ops[0]->getType()) &&
1700 "SCEVSMaxExpr operand types don't match!");
1701#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001702
1703 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001704 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001705
1706 // If there are any constants, fold them together.
1707 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001708 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001709 ++Idx;
1710 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001711 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001712 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001713 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001714 APIntOps::smax(LHSC->getValue()->getValue(),
1715 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001716 Ops[0] = getConstant(Fold);
1717 Ops.erase(Ops.begin()+1); // Erase the folded element
1718 if (Ops.size() == 1) return Ops[0];
1719 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001720 }
1721
1722 // If we are left with a constant -inf, strip it off.
1723 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1724 Ops.erase(Ops.begin());
1725 --Idx;
1726 }
1727 }
1728
1729 if (Ops.size() == 1) return Ops[0];
1730
1731 // Find the first SMax
1732 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1733 ++Idx;
1734
1735 // Check to see if one of the operands is an SMax. If so, expand its operands
1736 // onto our operand list, and recurse to simplify.
1737 if (Idx < Ops.size()) {
1738 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001739 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001740 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1741 Ops.erase(Ops.begin()+Idx);
1742 DeletedSMax = true;
1743 }
1744
1745 if (DeletedSMax)
1746 return getSMaxExpr(Ops);
1747 }
1748
1749 // Okay, check to see if the same value occurs in the operand list twice. If
1750 // so, delete one. Since we sorted the list, these values are required to
1751 // be adjacent.
1752 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1753 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1754 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1755 --i; --e;
1756 }
1757
1758 if (Ops.size() == 1) return Ops[0];
1759
1760 assert(!Ops.empty() && "Reduced smax down to nothing!");
1761
Nick Lewycky3e630762008-02-20 06:48:22 +00001762 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001763 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001764 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Anderson08367b62009-06-22 18:25:46 +00001765 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scSMaxExpr,
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001766 SCEVOps)];
Owen Anderson4a7893b2009-06-18 22:25:12 +00001767 if (Result == 0) Result = new SCEVSMaxExpr(Ops, this);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001768 return Result;
1769}
1770
Owen Anderson372b46c2009-06-22 21:39:50 +00001771const SCEV* ScalarEvolution::getUMaxExpr(const SCEV* LHS,
1772 const SCEV* RHS) {
1773 SmallVector<const SCEV*, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00001774 Ops.push_back(LHS);
1775 Ops.push_back(RHS);
1776 return getUMaxExpr(Ops);
1777}
1778
Owen Anderson372b46c2009-06-22 21:39:50 +00001779const SCEV*
1780ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV*> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001781 assert(!Ops.empty() && "Cannot get empty umax!");
1782 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001783#ifndef NDEBUG
1784 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1785 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1786 getEffectiveSCEVType(Ops[0]->getType()) &&
1787 "SCEVUMaxExpr operand types don't match!");
1788#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00001789
1790 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001791 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00001792
1793 // If there are any constants, fold them together.
1794 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001795 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001796 ++Idx;
1797 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001798 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001799 // We found two constants, fold them together!
1800 ConstantInt *Fold = ConstantInt::get(
1801 APIntOps::umax(LHSC->getValue()->getValue(),
1802 RHSC->getValue()->getValue()));
1803 Ops[0] = getConstant(Fold);
1804 Ops.erase(Ops.begin()+1); // Erase the folded element
1805 if (Ops.size() == 1) return Ops[0];
1806 LHSC = cast<SCEVConstant>(Ops[0]);
1807 }
1808
1809 // If we are left with a constant zero, strip it off.
1810 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1811 Ops.erase(Ops.begin());
1812 --Idx;
1813 }
1814 }
1815
1816 if (Ops.size() == 1) return Ops[0];
1817
1818 // Find the first UMax
1819 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1820 ++Idx;
1821
1822 // Check to see if one of the operands is a UMax. If so, expand its operands
1823 // onto our operand list, and recurse to simplify.
1824 if (Idx < Ops.size()) {
1825 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001826 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001827 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1828 Ops.erase(Ops.begin()+Idx);
1829 DeletedUMax = true;
1830 }
1831
1832 if (DeletedUMax)
1833 return getUMaxExpr(Ops);
1834 }
1835
1836 // Okay, check to see if the same value occurs in the operand list twice. If
1837 // so, delete one. Since we sorted the list, these values are required to
1838 // be adjacent.
1839 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1840 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1841 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1842 --i; --e;
1843 }
1844
1845 if (Ops.size() == 1) return Ops[0];
1846
1847 assert(!Ops.empty() && "Reduced umax down to nothing!");
1848
1849 // Okay, it looks like we really DO need a umax expr. Check to see if we
1850 // already have one, otherwise create a new one.
Dan Gohman35738ac2009-05-04 22:30:44 +00001851 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Anderson08367b62009-06-22 18:25:46 +00001852 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scUMaxExpr,
Nick Lewycky3e630762008-02-20 06:48:22 +00001853 SCEVOps)];
Owen Anderson4a7893b2009-06-18 22:25:12 +00001854 if (Result == 0) Result = new SCEVUMaxExpr(Ops, this);
Nick Lewycky3e630762008-02-20 06:48:22 +00001855 return Result;
1856}
1857
Owen Anderson372b46c2009-06-22 21:39:50 +00001858const SCEV* ScalarEvolution::getSMinExpr(const SCEV* LHS,
1859 const SCEV* RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00001860 // ~smax(~x, ~y) == smin(x, y).
1861 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1862}
1863
Owen Anderson372b46c2009-06-22 21:39:50 +00001864const SCEV* ScalarEvolution::getUMinExpr(const SCEV* LHS,
1865 const SCEV* RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00001866 // ~umax(~x, ~y) == umin(x, y)
1867 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1868}
1869
Owen Anderson372b46c2009-06-22 21:39:50 +00001870const SCEV* ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001871 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001872 return getConstant(CI);
Dan Gohman2d1be872009-04-16 03:18:22 +00001873 if (isa<ConstantPointerNull>(V))
1874 return getIntegerSCEV(0, V->getType());
Owen Anderson08367b62009-06-22 18:25:46 +00001875 SCEVUnknown *&Result = SCEVUnknowns[V];
Owen Anderson4a7893b2009-06-18 22:25:12 +00001876 if (Result == 0) Result = new SCEVUnknown(V, this);
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001877 return Result;
1878}
1879
Chris Lattner53e677a2004-04-02 20:23:17 +00001880//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001881// Basic SCEV Analysis and PHI Idiom Recognition Code
1882//
1883
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001884/// isSCEVable - Test if values of the given type are analyzable within
1885/// the SCEV framework. This primarily includes integer types, and it
1886/// can optionally include pointer types if the ScalarEvolution class
1887/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001888bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001889 // Integers are always SCEVable.
1890 if (Ty->isInteger())
1891 return true;
1892
1893 // Pointers are SCEVable if TargetData information is available
1894 // to provide pointer size information.
1895 if (isa<PointerType>(Ty))
1896 return TD != NULL;
1897
1898 // Otherwise it's not SCEVable.
1899 return false;
1900}
1901
1902/// getTypeSizeInBits - Return the size in bits of the specified type,
1903/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001904uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001905 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1906
1907 // If we have a TargetData, use it!
1908 if (TD)
1909 return TD->getTypeSizeInBits(Ty);
1910
1911 // Otherwise, we support only integer types.
1912 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1913 return Ty->getPrimitiveSizeInBits();
1914}
1915
1916/// getEffectiveSCEVType - Return a type with the same bitwidth as
1917/// the given type and which represents how SCEV will treat the given
1918/// type, for which isSCEVable must return true. For pointer types,
1919/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001920const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001921 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1922
1923 if (Ty->isInteger())
1924 return Ty;
1925
1926 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1927 return TD->getIntPtrType();
Dan Gohman2d1be872009-04-16 03:18:22 +00001928}
Chris Lattner53e677a2004-04-02 20:23:17 +00001929
Owen Anderson372b46c2009-06-22 21:39:50 +00001930const SCEV* ScalarEvolution::getCouldNotCompute() {
Dan Gohman86fbf2f2009-06-06 14:37:11 +00001931 return CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00001932}
1933
Dan Gohman92fa56e2009-05-04 22:20:30 +00001934/// hasSCEV - Return true if the SCEV for this value has already been
Torok Edwine3d12852009-05-01 08:33:47 +00001935/// computed.
1936bool ScalarEvolution::hasSCEV(Value *V) const {
1937 return Scalars.count(V);
1938}
1939
Chris Lattner53e677a2004-04-02 20:23:17 +00001940/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1941/// expression and create a new one.
Owen Anderson372b46c2009-06-22 21:39:50 +00001942const SCEV* ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00001943 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00001944
Owen Anderson372b46c2009-06-22 21:39:50 +00001945 std::map<SCEVCallbackVH, const SCEV*>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001946 if (I != Scalars.end()) return I->second;
Owen Anderson372b46c2009-06-22 21:39:50 +00001947 const SCEV* S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00001948 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00001949 return S;
1950}
1951
Dan Gohman2d1be872009-04-16 03:18:22 +00001952/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1953/// specified signed integer value and return a SCEV for the constant.
Owen Anderson372b46c2009-06-22 21:39:50 +00001954const SCEV* ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001955 Ty = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00001956 Constant *C;
1957 if (Val == 0)
1958 C = Constant::getNullValue(Ty);
1959 else if (Ty->isFloatingPoint())
1960 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1961 APFloat::IEEEdouble, Val));
1962 else
1963 C = ConstantInt::get(Ty, Val);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001964 return getUnknown(C);
Dan Gohman2d1be872009-04-16 03:18:22 +00001965}
1966
1967/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1968///
Owen Anderson372b46c2009-06-22 21:39:50 +00001969const SCEV* ScalarEvolution::getNegativeSCEV(const SCEV* V) {
Dan Gohman622ed672009-05-04 22:02:23 +00001970 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001971 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman2d1be872009-04-16 03:18:22 +00001972
1973 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001974 Ty = getEffectiveSCEVType(Ty);
1975 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00001976}
1977
1978/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Owen Anderson372b46c2009-06-22 21:39:50 +00001979const SCEV* ScalarEvolution::getNotSCEV(const SCEV* V) {
Dan Gohman622ed672009-05-04 22:02:23 +00001980 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001981 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman2d1be872009-04-16 03:18:22 +00001982
1983 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001984 Ty = getEffectiveSCEVType(Ty);
Owen Anderson372b46c2009-06-22 21:39:50 +00001985 const SCEV* AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman2d1be872009-04-16 03:18:22 +00001986 return getMinusSCEV(AllOnes, V);
1987}
1988
1989/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1990///
Owen Anderson372b46c2009-06-22 21:39:50 +00001991const SCEV* ScalarEvolution::getMinusSCEV(const SCEV* LHS,
1992 const SCEV* RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00001993 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00001994 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00001995}
1996
1997/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1998/// input value to the specified type. If the type must be extended, it is zero
1999/// extended.
Owen Anderson372b46c2009-06-22 21:39:50 +00002000const SCEV*
2001ScalarEvolution::getTruncateOrZeroExtend(const SCEV* V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002002 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002003 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002004 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2005 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002006 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002007 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002008 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002009 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002010 return getTruncateExpr(V, Ty);
2011 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002012}
2013
2014/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2015/// input value to the specified type. If the type must be extended, it is sign
2016/// extended.
Owen Anderson372b46c2009-06-22 21:39:50 +00002017const SCEV*
2018ScalarEvolution::getTruncateOrSignExtend(const SCEV* V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002019 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002020 const Type *SrcTy = V->getType();
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002021 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2022 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002023 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002024 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002025 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002026 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002027 return getTruncateExpr(V, Ty);
2028 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002029}
2030
Dan Gohman467c4302009-05-13 03:46:30 +00002031/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2032/// input value to the specified type. If the type must be extended, it is zero
2033/// extended. The conversion must not be narrowing.
Owen Anderson372b46c2009-06-22 21:39:50 +00002034const SCEV*
2035ScalarEvolution::getNoopOrZeroExtend(const SCEV* V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002036 const Type *SrcTy = V->getType();
2037 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2038 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2039 "Cannot noop or zero extend with non-integer arguments!");
2040 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2041 "getNoopOrZeroExtend cannot truncate!");
2042 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2043 return V; // No conversion
2044 return getZeroExtendExpr(V, Ty);
2045}
2046
2047/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2048/// input value to the specified type. If the type must be extended, it is sign
2049/// extended. The conversion must not be narrowing.
Owen Anderson372b46c2009-06-22 21:39:50 +00002050const SCEV*
2051ScalarEvolution::getNoopOrSignExtend(const SCEV* V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002052 const Type *SrcTy = V->getType();
2053 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2054 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2055 "Cannot noop or sign extend with non-integer arguments!");
2056 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2057 "getNoopOrSignExtend cannot truncate!");
2058 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2059 return V; // No conversion
2060 return getSignExtendExpr(V, Ty);
2061}
2062
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002063/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2064/// the input value to the specified type. If the type must be extended,
2065/// it is extended with unspecified bits. The conversion must not be
2066/// narrowing.
Owen Anderson372b46c2009-06-22 21:39:50 +00002067const SCEV*
2068ScalarEvolution::getNoopOrAnyExtend(const SCEV* V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002069 const Type *SrcTy = V->getType();
2070 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2071 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2072 "Cannot noop or any extend with non-integer arguments!");
2073 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2074 "getNoopOrAnyExtend cannot truncate!");
2075 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2076 return V; // No conversion
2077 return getAnyExtendExpr(V, Ty);
2078}
2079
Dan Gohman467c4302009-05-13 03:46:30 +00002080/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2081/// input value to the specified type. The conversion must not be widening.
Owen Anderson372b46c2009-06-22 21:39:50 +00002082const SCEV*
2083ScalarEvolution::getTruncateOrNoop(const SCEV* V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002084 const Type *SrcTy = V->getType();
2085 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2086 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2087 "Cannot truncate or noop with non-integer arguments!");
2088 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2089 "getTruncateOrNoop cannot extend!");
2090 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2091 return V; // No conversion
2092 return getTruncateExpr(V, Ty);
2093}
2094
Dan Gohmana334aa72009-06-22 00:31:57 +00002095/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2096/// the types using zero-extension, and then perform a umax operation
2097/// with them.
Owen Anderson372b46c2009-06-22 21:39:50 +00002098const SCEV* ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV* LHS,
2099 const SCEV* RHS) {
2100 const SCEV* PromotedLHS = LHS;
2101 const SCEV* PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002102
2103 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2104 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2105 else
2106 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2107
2108 return getUMaxExpr(PromotedLHS, PromotedRHS);
2109}
2110
Dan Gohmanc9759e82009-06-22 15:03:27 +00002111/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2112/// the types using zero-extension, and then perform a umin operation
2113/// with them.
Owen Anderson372b46c2009-06-22 21:39:50 +00002114const SCEV* ScalarEvolution::getUMinFromMismatchedTypes(const SCEV* LHS,
2115 const SCEV* RHS) {
2116 const SCEV* PromotedLHS = LHS;
2117 const SCEV* PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002118
2119 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2120 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2121 else
2122 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2123
2124 return getUMinExpr(PromotedLHS, PromotedRHS);
2125}
2126
Chris Lattner4dc534c2005-02-13 04:37:18 +00002127/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2128/// the specified instruction and replaces any references to the symbolic value
2129/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002130void ScalarEvolution::
Owen Anderson372b46c2009-06-22 21:39:50 +00002131ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEV* SymName,
2132 const SCEV* NewVal) {
2133 std::map<SCEVCallbackVH, const SCEV*>::iterator SI =
Dan Gohman35738ac2009-05-04 22:30:44 +00002134 Scalars.find(SCEVCallbackVH(I, this));
Chris Lattner4dc534c2005-02-13 04:37:18 +00002135 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00002136
Owen Anderson372b46c2009-06-22 21:39:50 +00002137 const SCEV* NV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002138 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Chris Lattner4dc534c2005-02-13 04:37:18 +00002139 if (NV == SI->second) return; // No change.
2140
2141 SI->second = NV; // Update the scalars map!
2142
2143 // Any instruction values that use this instruction might also need to be
2144 // updated!
2145 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2146 UI != E; ++UI)
2147 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2148}
Chris Lattner53e677a2004-04-02 20:23:17 +00002149
2150/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2151/// a loop header, making it a potential recurrence, or it doesn't.
2152///
Owen Anderson372b46c2009-06-22 21:39:50 +00002153const SCEV* ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002154 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002155 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002156 if (L->getHeader() == PN->getParent()) {
2157 // If it lives in the loop header, it has two incoming values, one
2158 // from outside the loop, and one from inside.
2159 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2160 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002161
Chris Lattner53e677a2004-04-02 20:23:17 +00002162 // While we are analyzing this PHI node, handle its value symbolically.
Owen Anderson372b46c2009-06-22 21:39:50 +00002163 const SCEV* SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002164 assert(Scalars.find(PN) == Scalars.end() &&
2165 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002166 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002167
2168 // Using this symbolic name for the PHI, analyze the value coming around
2169 // the back-edge.
Owen Anderson372b46c2009-06-22 21:39:50 +00002170 const SCEV* BEValue = getSCEV(PN->getIncomingValue(BackEdge));
Chris Lattner53e677a2004-04-02 20:23:17 +00002171
2172 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2173 // has a special value for the first iteration of the loop.
2174
2175 // If the value coming around the backedge is an add with the symbolic
2176 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002177 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002178 // If there is a single occurrence of the symbolic value, replace it
2179 // with a recurrence.
2180 unsigned FoundIndex = Add->getNumOperands();
2181 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2182 if (Add->getOperand(i) == SymbolicName)
2183 if (FoundIndex == e) {
2184 FoundIndex = i;
2185 break;
2186 }
2187
2188 if (FoundIndex != Add->getNumOperands()) {
2189 // Create an add with everything but the specified operand.
Owen Anderson372b46c2009-06-22 21:39:50 +00002190 SmallVector<const SCEV*, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002191 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2192 if (i != FoundIndex)
2193 Ops.push_back(Add->getOperand(i));
Owen Anderson372b46c2009-06-22 21:39:50 +00002194 const SCEV* Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002195
2196 // This is not a valid addrec if the step amount is varying each
2197 // loop iteration, but is not itself an addrec in this loop.
2198 if (Accum->isLoopInvariant(L) ||
2199 (isa<SCEVAddRecExpr>(Accum) &&
2200 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Owen Anderson372b46c2009-06-22 21:39:50 +00002201 const SCEV* StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2202 const SCEV* PHISCEV = getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002203
2204 // Okay, for the entire analysis of this edge we assumed the PHI
2205 // to be symbolic. We now need to go back and update all of the
2206 // entries for the scalars that use the PHI (except for the PHI
2207 // itself) to use the new analyzed value instead of the "symbolic"
2208 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00002209 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002210 return PHISCEV;
2211 }
2212 }
Dan Gohman622ed672009-05-04 22:02:23 +00002213 } else if (const SCEVAddRecExpr *AddRec =
2214 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002215 // Otherwise, this could be a loop like this:
2216 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2217 // In this case, j = {1,+,1} and BEValue is j.
2218 // Because the other in-value of i (0) fits the evolution of BEValue
2219 // i really is an addrec evolution.
2220 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Owen Anderson372b46c2009-06-22 21:39:50 +00002221 const SCEV* StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Chris Lattner97156e72006-04-26 18:34:07 +00002222
2223 // If StartVal = j.start - j.stride, we can use StartVal as the
2224 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002225 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002226 AddRec->getOperand(1))) {
Owen Anderson372b46c2009-06-22 21:39:50 +00002227 const SCEV* PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002228 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002229
2230 // Okay, for the entire analysis of this edge we assumed the PHI
2231 // to be symbolic. We now need to go back and update all of the
2232 // entries for the scalars that use the PHI (except for the PHI
2233 // itself) to use the new analyzed value instead of the "symbolic"
2234 // value.
2235 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2236 return PHISCEV;
2237 }
2238 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002239 }
2240
2241 return SymbolicName;
2242 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002243
Chris Lattner53e677a2004-04-02 20:23:17 +00002244 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002245 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002246}
2247
Dan Gohman26466c02009-05-08 20:26:55 +00002248/// createNodeForGEP - Expand GEP instructions into add and multiply
2249/// operations. This allows them to be analyzed by regular SCEV code.
2250///
Owen Anderson372b46c2009-06-22 21:39:50 +00002251const SCEV* ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002252
2253 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmane810b0d2009-05-08 20:36:47 +00002254 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002255 // Don't attempt to analyze GEPs over unsized objects.
2256 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2257 return getUnknown(GEP);
Owen Anderson372b46c2009-06-22 21:39:50 +00002258 const SCEV* TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002259 gep_type_iterator GTI = gep_type_begin(GEP);
2260 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2261 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002262 I != E; ++I) {
2263 Value *Index = *I;
2264 // Compute the (potentially symbolic) offset in bytes for this index.
2265 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2266 // For a struct, add the member offset.
2267 const StructLayout &SL = *TD->getStructLayout(STy);
2268 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2269 uint64_t Offset = SL.getElementOffset(FieldNo);
2270 TotalOffset = getAddExpr(TotalOffset,
2271 getIntegerSCEV(Offset, IntPtrTy));
2272 } else {
2273 // For an array, add the element offset, explicitly scaled.
Owen Anderson372b46c2009-06-22 21:39:50 +00002274 const SCEV* LocalOffset = getSCEV(Index);
Dan Gohman26466c02009-05-08 20:26:55 +00002275 if (!isa<PointerType>(LocalOffset->getType()))
2276 // Getelementptr indicies are signed.
2277 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2278 IntPtrTy);
2279 LocalOffset =
2280 getMulExpr(LocalOffset,
Duncan Sands777d2302009-05-09 07:06:46 +00002281 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman26466c02009-05-08 20:26:55 +00002282 IntPtrTy));
2283 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2284 }
2285 }
2286 return getAddExpr(getSCEV(Base), TotalOffset);
2287}
2288
Nick Lewycky83bb0052007-11-22 07:59:40 +00002289/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2290/// guaranteed to end in (at every loop iteration). It is, at the same time,
2291/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2292/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002293uint32_t
Owen Anderson372b46c2009-06-22 21:39:50 +00002294ScalarEvolution::GetMinTrailingZeros(const SCEV* S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002295 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002296 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002297
Dan Gohman622ed672009-05-04 22:02:23 +00002298 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002299 return std::min(GetMinTrailingZeros(T->getOperand()),
2300 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002301
Dan Gohman622ed672009-05-04 22:02:23 +00002302 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002303 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2304 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2305 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002306 }
2307
Dan Gohman622ed672009-05-04 22:02:23 +00002308 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002309 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2310 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2311 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002312 }
2313
Dan Gohman622ed672009-05-04 22:02:23 +00002314 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002315 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002316 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002317 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002318 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002319 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002320 }
2321
Dan Gohman622ed672009-05-04 22:02:23 +00002322 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002323 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002324 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2325 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002326 for (unsigned i = 1, e = M->getNumOperands();
2327 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002328 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002329 BitWidth);
2330 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002331 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002332
Dan Gohman622ed672009-05-04 22:02:23 +00002333 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002334 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002335 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002336 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002337 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002338 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002339 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002340
Dan Gohman622ed672009-05-04 22:02:23 +00002341 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002342 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002343 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002344 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002345 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002346 return MinOpRes;
2347 }
2348
Dan Gohman622ed672009-05-04 22:02:23 +00002349 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002350 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002351 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002352 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002353 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002354 return MinOpRes;
2355 }
2356
Dan Gohman2c364ad2009-06-19 23:29:04 +00002357 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2358 // For a SCEVUnknown, ask ValueTracking.
2359 unsigned BitWidth = getTypeSizeInBits(U->getType());
2360 APInt Mask = APInt::getAllOnesValue(BitWidth);
2361 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2362 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2363 return Zeros.countTrailingOnes();
2364 }
2365
2366 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002367 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002368}
Chris Lattner53e677a2004-04-02 20:23:17 +00002369
Dan Gohman2c364ad2009-06-19 23:29:04 +00002370uint32_t
Owen Anderson372b46c2009-06-22 21:39:50 +00002371ScalarEvolution::GetMinLeadingZeros(const SCEV* S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002372 // TODO: Handle other SCEV expression types here.
2373
2374 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2375 return C->getValue()->getValue().countLeadingZeros();
2376
2377 if (const SCEVZeroExtendExpr *C = dyn_cast<SCEVZeroExtendExpr>(S)) {
2378 // A zero-extension cast adds zero bits.
2379 return GetMinLeadingZeros(C->getOperand()) +
2380 (getTypeSizeInBits(C->getType()) -
2381 getTypeSizeInBits(C->getOperand()->getType()));
2382 }
2383
2384 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2385 // For a SCEVUnknown, ask ValueTracking.
2386 unsigned BitWidth = getTypeSizeInBits(U->getType());
2387 APInt Mask = APInt::getAllOnesValue(BitWidth);
2388 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2389 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2390 return Zeros.countLeadingOnes();
2391 }
2392
2393 return 1;
2394}
2395
2396uint32_t
Owen Anderson372b46c2009-06-22 21:39:50 +00002397ScalarEvolution::GetMinSignBits(const SCEV* S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002398 // TODO: Handle other SCEV expression types here.
2399
2400 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
2401 const APInt &A = C->getValue()->getValue();
2402 return A.isNegative() ? A.countLeadingOnes() :
2403 A.countLeadingZeros();
2404 }
2405
2406 if (const SCEVSignExtendExpr *C = dyn_cast<SCEVSignExtendExpr>(S)) {
2407 // A sign-extension cast adds sign bits.
2408 return GetMinSignBits(C->getOperand()) +
2409 (getTypeSizeInBits(C->getType()) -
2410 getTypeSizeInBits(C->getOperand()->getType()));
2411 }
2412
2413 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2414 // For a SCEVUnknown, ask ValueTracking.
2415 return ComputeNumSignBits(U->getValue(), TD);
2416 }
2417
2418 return 1;
2419}
2420
Chris Lattner53e677a2004-04-02 20:23:17 +00002421/// createSCEV - We know that there is no SCEV for the specified value.
2422/// Analyze the expression.
2423///
Owen Anderson372b46c2009-06-22 21:39:50 +00002424const SCEV* ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002425 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002426 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00002427
Dan Gohman6c459a22008-06-22 19:56:46 +00002428 unsigned Opcode = Instruction::UserOp1;
2429 if (Instruction *I = dyn_cast<Instruction>(V))
2430 Opcode = I->getOpcode();
2431 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2432 Opcode = CE->getOpcode();
2433 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002434 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00002435
Dan Gohman6c459a22008-06-22 19:56:46 +00002436 User *U = cast<User>(V);
2437 switch (Opcode) {
2438 case Instruction::Add:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002439 return getAddExpr(getSCEV(U->getOperand(0)),
2440 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002441 case Instruction::Mul:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002442 return getMulExpr(getSCEV(U->getOperand(0)),
2443 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002444 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002445 return getUDivExpr(getSCEV(U->getOperand(0)),
2446 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002447 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002448 return getMinusSCEV(getSCEV(U->getOperand(0)),
2449 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002450 case Instruction::And:
2451 // For an expression like x&255 that merely masks off the high bits,
2452 // use zext(trunc(x)) as the SCEV expression.
2453 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002454 if (CI->isNullValue())
2455 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00002456 if (CI->isAllOnesValue())
2457 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002458 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002459
2460 // Instcombine's ShrinkDemandedConstant may strip bits out of
2461 // constants, obscuring what would otherwise be a low-bits mask.
2462 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2463 // knew about to reconstruct a low-bits mask value.
2464 unsigned LZ = A.countLeadingZeros();
2465 unsigned BitWidth = A.getBitWidth();
2466 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2467 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2468 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2469
2470 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2471
Dan Gohmanfc3641b2009-06-17 23:54:37 +00002472 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00002473 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002474 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002475 IntegerType::get(BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002476 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00002477 }
2478 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002479
Dan Gohman6c459a22008-06-22 19:56:46 +00002480 case Instruction::Or:
2481 // If the RHS of the Or is a constant, we may have something like:
2482 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2483 // optimizations will transparently handle this case.
2484 //
2485 // In order for this transformation to be safe, the LHS must be of the
2486 // form X*(2^n) and the Or constant must be less than 2^n.
2487 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Owen Anderson372b46c2009-06-22 21:39:50 +00002488 const SCEV* LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00002489 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00002490 if (GetMinTrailingZeros(LHS) >=
Dan Gohman6c459a22008-06-22 19:56:46 +00002491 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002492 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00002493 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002494 break;
2495 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00002496 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00002497 // If the RHS of the xor is a signbit, then this is just an add.
2498 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00002499 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002500 return getAddExpr(getSCEV(U->getOperand(0)),
2501 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002502
2503 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00002504 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002505 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00002506
2507 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2508 // This is a variant of the check for xor with -1, and it handles
2509 // the case where instcombine has trimmed non-demanded bits out
2510 // of an xor with -1.
2511 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2512 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2513 if (BO->getOpcode() == Instruction::And &&
2514 LCI->getValue() == CI->getValue())
2515 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00002516 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00002517 const Type *UTy = U->getType();
Owen Anderson372b46c2009-06-22 21:39:50 +00002518 const SCEV* Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00002519 const Type *Z0Ty = Z0->getType();
2520 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2521
2522 // If C is a low-bits mask, the zero extend is zerving to
2523 // mask off the high bits. Complement the operand and
2524 // re-apply the zext.
2525 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2526 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2527
2528 // If C is a single bit, it may be in the sign-bit position
2529 // before the zero-extend. In this case, represent the xor
2530 // using an add, which is equivalent, and re-apply the zext.
2531 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2532 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2533 Trunc.isSignBit())
2534 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2535 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00002536 }
Dan Gohman6c459a22008-06-22 19:56:46 +00002537 }
2538 break;
2539
2540 case Instruction::Shl:
2541 // Turn shift left of a constant amount into a multiply.
2542 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2543 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2544 Constant *X = ConstantInt::get(
2545 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002546 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00002547 }
2548 break;
2549
Nick Lewycky01eaf802008-07-07 06:15:49 +00002550 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00002551 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00002552 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2553 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2554 Constant *X = ConstantInt::get(
2555 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002556 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00002557 }
2558 break;
2559
Dan Gohman4ee29af2009-04-21 02:26:00 +00002560 case Instruction::AShr:
2561 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2562 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2563 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2564 if (L->getOpcode() == Instruction::Shl &&
2565 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002566 unsigned BitWidth = getTypeSizeInBits(U->getType());
2567 uint64_t Amt = BitWidth - CI->getZExtValue();
2568 if (Amt == BitWidth)
2569 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2570 if (Amt > BitWidth)
2571 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00002572 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002573 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002574 IntegerType::get(Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00002575 U->getType());
2576 }
2577 break;
2578
Dan Gohman6c459a22008-06-22 19:56:46 +00002579 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002580 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002581
2582 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002583 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002584
2585 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002586 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00002587
2588 case Instruction::BitCast:
2589 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002590 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00002591 return getSCEV(U->getOperand(0));
2592 break;
2593
Dan Gohman2d1be872009-04-16 03:18:22 +00002594 case Instruction::IntToPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002595 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002596 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002597 TD->getIntPtrType());
Dan Gohman2d1be872009-04-16 03:18:22 +00002598
2599 case Instruction::PtrToInt:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002600 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman2d1be872009-04-16 03:18:22 +00002601 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2602 U->getType());
2603
Dan Gohman26466c02009-05-08 20:26:55 +00002604 case Instruction::GetElementPtr:
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002605 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanfb791602009-05-08 20:58:38 +00002606 return createNodeForGEP(U);
Dan Gohman2d1be872009-04-16 03:18:22 +00002607
Dan Gohman6c459a22008-06-22 19:56:46 +00002608 case Instruction::PHI:
2609 return createNodeForPHI(cast<PHINode>(U));
2610
2611 case Instruction::Select:
2612 // This could be a smax or umax that was lowered earlier.
2613 // Try to recover it.
2614 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2615 Value *LHS = ICI->getOperand(0);
2616 Value *RHS = ICI->getOperand(1);
2617 switch (ICI->getPredicate()) {
2618 case ICmpInst::ICMP_SLT:
2619 case ICmpInst::ICMP_SLE:
2620 std::swap(LHS, RHS);
2621 // fall through
2622 case ICmpInst::ICMP_SGT:
2623 case ICmpInst::ICMP_SGE:
2624 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002625 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002626 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002627 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002628 break;
2629 case ICmpInst::ICMP_ULT:
2630 case ICmpInst::ICMP_ULE:
2631 std::swap(LHS, RHS);
2632 // fall through
2633 case ICmpInst::ICMP_UGT:
2634 case ICmpInst::ICMP_UGE:
2635 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002636 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002637 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002638 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00002639 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00002640 case ICmpInst::ICMP_NE:
2641 // n != 0 ? n : 1 -> umax(n, 1)
2642 if (LHS == U->getOperand(1) &&
2643 isa<ConstantInt>(U->getOperand(2)) &&
2644 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2645 isa<ConstantInt>(RHS) &&
2646 cast<ConstantInt>(RHS)->isZero())
2647 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2648 break;
2649 case ICmpInst::ICMP_EQ:
2650 // n == 0 ? 1 : n -> umax(n, 1)
2651 if (LHS == U->getOperand(2) &&
2652 isa<ConstantInt>(U->getOperand(1)) &&
2653 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2654 isa<ConstantInt>(RHS) &&
2655 cast<ConstantInt>(RHS)->isZero())
2656 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2657 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00002658 default:
2659 break;
2660 }
2661 }
2662
2663 default: // We cannot analyze this expression.
2664 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002665 }
2666
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002667 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002668}
2669
2670
2671
2672//===----------------------------------------------------------------------===//
2673// Iteration Count Computation Code
2674//
2675
Dan Gohman46bdfb02009-02-24 18:55:53 +00002676/// getBackedgeTakenCount - If the specified loop has a predictable
2677/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2678/// object. The backedge-taken count is the number of times the loop header
2679/// will be branched to from within the loop. This is one less than the
2680/// trip count of the loop, since it doesn't count the first iteration,
2681/// when the header is branched to from outside the loop.
2682///
2683/// Note that it is not valid to call this method on a loop without a
2684/// loop-invariant backedge-taken count (see
2685/// hasLoopInvariantBackedgeTakenCount).
2686///
Owen Anderson372b46c2009-06-22 21:39:50 +00002687const SCEV* ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002688 return getBackedgeTakenInfo(L).Exact;
2689}
2690
2691/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2692/// return the least SCEV value that is known never to be less than the
2693/// actual backedge taken count.
Owen Anderson372b46c2009-06-22 21:39:50 +00002694const SCEV* ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002695 return getBackedgeTakenInfo(L).Max;
2696}
2697
2698const ScalarEvolution::BackedgeTakenInfo &
2699ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00002700 // Initially insert a CouldNotCompute for this loop. If the insertion
2701 // succeeds, procede to actually compute a backedge-taken count and
2702 // update the value. The temporary CouldNotCompute value tells SCEV
2703 // code elsewhere that it shouldn't attempt to request a new
2704 // backedge-taken count, which could result in infinite recursion.
Dan Gohmana1af7572009-04-30 20:47:05 +00002705 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00002706 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2707 if (Pair.second) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002708 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman86fbf2f2009-06-06 14:37:11 +00002709 if (ItCount.Exact != CouldNotCompute) {
Dan Gohmana1af7572009-04-30 20:47:05 +00002710 assert(ItCount.Exact->isLoopInvariant(L) &&
2711 ItCount.Max->isLoopInvariant(L) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002712 "Computed trip count isn't loop invariant for loop!");
2713 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00002714
Dan Gohman01ecca22009-04-27 20:16:15 +00002715 // Update the value in the map.
2716 Pair.first->second = ItCount;
Dan Gohmana334aa72009-06-22 00:31:57 +00002717 } else {
2718 if (ItCount.Max != CouldNotCompute)
2719 // Update the value in the map.
2720 Pair.first->second = ItCount;
2721 if (isa<PHINode>(L->getHeader()->begin()))
2722 // Only count loops that have phi nodes as not being computable.
2723 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00002724 }
Dan Gohmana1af7572009-04-30 20:47:05 +00002725
2726 // Now that we know more about the trip count for this loop, forget any
2727 // existing SCEV values for PHI nodes in this loop since they are only
2728 // conservative estimates made without the benefit
2729 // of trip count information.
2730 if (ItCount.hasAnyInfo())
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00002731 forgetLoopPHIs(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002732 }
Dan Gohman01ecca22009-04-27 20:16:15 +00002733 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00002734}
2735
Dan Gohman46bdfb02009-02-24 18:55:53 +00002736/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohman60f8a632009-02-17 20:49:49 +00002737/// client when it has changed a loop in a way that may effect
Dan Gohman46bdfb02009-02-24 18:55:53 +00002738/// ScalarEvolution's ability to compute a trip count, or if the loop
2739/// is deleted.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002740void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00002741 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00002742 forgetLoopPHIs(L);
2743}
2744
2745/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2746/// PHI nodes in the given loop. This is used when the trip count of
2747/// the loop may have changed.
2748void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohman35738ac2009-05-04 22:30:44 +00002749 BasicBlock *Header = L->getHeader();
2750
Dan Gohmanefb9fbf2009-05-12 01:27:58 +00002751 // Push all Loop-header PHIs onto the Worklist stack, except those
2752 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2753 // a PHI either means that it has an unrecognized structure, or it's
2754 // a PHI that's in the progress of being computed by createNodeForPHI.
2755 // In the former case, additional loop trip count information isn't
2756 // going to change anything. In the later case, createNodeForPHI will
2757 // perform the necessary updates on its own when it gets to that point.
Dan Gohman35738ac2009-05-04 22:30:44 +00002758 SmallVector<Instruction *, 16> Worklist;
2759 for (BasicBlock::iterator I = Header->begin();
Dan Gohmanefb9fbf2009-05-12 01:27:58 +00002760 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Owen Anderson372b46c2009-06-22 21:39:50 +00002761 std::map<SCEVCallbackVH, const SCEV*>::iterator It = Scalars.find((Value*)I);
Dan Gohmanefb9fbf2009-05-12 01:27:58 +00002762 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2763 Worklist.push_back(PN);
2764 }
Dan Gohman35738ac2009-05-04 22:30:44 +00002765
2766 while (!Worklist.empty()) {
2767 Instruction *I = Worklist.pop_back_val();
2768 if (Scalars.erase(I))
2769 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2770 UI != UE; ++UI)
2771 Worklist.push_back(cast<Instruction>(UI));
2772 }
Dan Gohman60f8a632009-02-17 20:49:49 +00002773}
2774
Dan Gohman46bdfb02009-02-24 18:55:53 +00002775/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2776/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00002777ScalarEvolution::BackedgeTakenInfo
2778ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmana334aa72009-06-22 00:31:57 +00002779 SmallVector<BasicBlock*, 8> ExitingBlocks;
2780 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00002781
Dan Gohmana334aa72009-06-22 00:31:57 +00002782 // Examine all exits and pick the most conservative values.
Owen Anderson372b46c2009-06-22 21:39:50 +00002783 const SCEV* BECount = CouldNotCompute;
2784 const SCEV* MaxBECount = CouldNotCompute;
Dan Gohmana334aa72009-06-22 00:31:57 +00002785 bool CouldNotComputeBECount = false;
2786 bool CouldNotComputeMaxBECount = false;
2787 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
2788 BackedgeTakenInfo NewBTI =
2789 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00002790
Dan Gohmana334aa72009-06-22 00:31:57 +00002791 if (NewBTI.Exact == CouldNotCompute) {
2792 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00002793 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00002794 CouldNotComputeBECount = true;
2795 BECount = CouldNotCompute;
2796 } else if (!CouldNotComputeBECount) {
2797 if (BECount == CouldNotCompute)
2798 BECount = NewBTI.Exact;
2799 else {
2800 // TODO: More analysis could be done here. For example, a
2801 // loop with a short-circuiting && operator has an exact count
2802 // of the min of both sides.
2803 CouldNotComputeBECount = true;
2804 BECount = CouldNotCompute;
2805 }
2806 }
2807 if (NewBTI.Max == CouldNotCompute) {
2808 // We couldn't compute an maximum value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00002809 // we won't be able to compute an maximum value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00002810 CouldNotComputeMaxBECount = true;
2811 MaxBECount = CouldNotCompute;
2812 } else if (!CouldNotComputeMaxBECount) {
2813 if (MaxBECount == CouldNotCompute)
2814 MaxBECount = NewBTI.Max;
2815 else
2816 MaxBECount = getUMaxFromMismatchedTypes(MaxBECount, NewBTI.Max);
2817 }
2818 }
2819
2820 return BackedgeTakenInfo(BECount, MaxBECount);
2821}
2822
2823/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
2824/// of the specified loop will execute if it exits via the specified block.
2825ScalarEvolution::BackedgeTakenInfo
2826ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
2827 BasicBlock *ExitingBlock) {
2828
2829 // Okay, we've chosen an exiting block. See what condition causes us to
2830 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00002831 //
2832 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00002833 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman86fbf2f2009-06-06 14:37:11 +00002834 if (ExitBr == 0) return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00002835 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00002836
2837 // At this point, we know we have a conditional branch that determines whether
2838 // the loop is exited. However, we don't know if the branch is executed each
2839 // time through the loop. If not, then the execution count of the branch will
2840 // not be equal to the trip count of the loop.
2841 //
2842 // Currently we check for this by checking to see if the Exit branch goes to
2843 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00002844 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00002845 // loop header. This is common for un-rotated loops.
2846 //
2847 // If both of those tests fail, walk up the unique predecessor chain to the
2848 // header, stopping if there is an edge that doesn't exit the loop. If the
2849 // header is reached, the execution count of the branch will be equal to the
2850 // trip count of the loop.
2851 //
2852 // More extensive analysis could be done to handle more cases here.
2853 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00002854 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00002855 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00002856 ExitBr->getParent() != L->getHeader()) {
2857 // The simple checks failed, try climbing the unique predecessor chain
2858 // up to the header.
2859 bool Ok = false;
2860 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
2861 BasicBlock *Pred = BB->getUniquePredecessor();
2862 if (!Pred)
2863 return CouldNotCompute;
2864 TerminatorInst *PredTerm = Pred->getTerminator();
2865 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
2866 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
2867 if (PredSucc == BB)
2868 continue;
2869 // If the predecessor has a successor that isn't BB and isn't
2870 // outside the loop, assume the worst.
2871 if (L->contains(PredSucc))
2872 return CouldNotCompute;
2873 }
2874 if (Pred == L->getHeader()) {
2875 Ok = true;
2876 break;
2877 }
2878 BB = Pred;
2879 }
2880 if (!Ok)
2881 return CouldNotCompute;
2882 }
2883
2884 // Procede to the next level to examine the exit condition expression.
2885 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
2886 ExitBr->getSuccessor(0),
2887 ExitBr->getSuccessor(1));
2888}
2889
2890/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
2891/// backedge of the specified loop will execute if its exit condition
2892/// were a conditional branch of ExitCond, TBB, and FBB.
2893ScalarEvolution::BackedgeTakenInfo
2894ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
2895 Value *ExitCond,
2896 BasicBlock *TBB,
2897 BasicBlock *FBB) {
2898 // Check if the controlling expression for this loop is an and or or. In
2899 // such cases, an exact backedge-taken count may be infeasible, but a
2900 // maximum count may still be feasible.
2901 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
2902 if (BO->getOpcode() == Instruction::And) {
2903 // Recurse on the operands of the and.
2904 BackedgeTakenInfo BTI0 =
2905 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
2906 BackedgeTakenInfo BTI1 =
2907 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Owen Anderson372b46c2009-06-22 21:39:50 +00002908 const SCEV* BECount = CouldNotCompute;
2909 const SCEV* MaxBECount = CouldNotCompute;
Dan Gohmana334aa72009-06-22 00:31:57 +00002910 if (L->contains(TBB)) {
2911 // Both conditions must be true for the loop to continue executing.
2912 // Choose the less conservative count.
Dan Gohman60e9b072009-06-22 15:09:28 +00002913 if (BTI0.Exact == CouldNotCompute)
2914 BECount = BTI1.Exact;
2915 else if (BTI1.Exact == CouldNotCompute)
Dan Gohmana334aa72009-06-22 00:31:57 +00002916 BECount = BTI0.Exact;
Dan Gohman60e9b072009-06-22 15:09:28 +00002917 else
2918 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00002919 if (BTI0.Max == CouldNotCompute)
2920 MaxBECount = BTI1.Max;
2921 else if (BTI1.Max == CouldNotCompute)
2922 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00002923 else
2924 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00002925 } else {
2926 // Both conditions must be true for the loop to exit.
2927 assert(L->contains(FBB) && "Loop block has no successor in loop!");
2928 if (BTI0.Exact != CouldNotCompute && BTI1.Exact != CouldNotCompute)
2929 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
2930 if (BTI0.Max != CouldNotCompute && BTI1.Max != CouldNotCompute)
2931 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
2932 }
2933
2934 return BackedgeTakenInfo(BECount, MaxBECount);
2935 }
2936 if (BO->getOpcode() == Instruction::Or) {
2937 // Recurse on the operands of the or.
2938 BackedgeTakenInfo BTI0 =
2939 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
2940 BackedgeTakenInfo BTI1 =
2941 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Owen Anderson372b46c2009-06-22 21:39:50 +00002942 const SCEV* BECount = CouldNotCompute;
2943 const SCEV* MaxBECount = CouldNotCompute;
Dan Gohmana334aa72009-06-22 00:31:57 +00002944 if (L->contains(FBB)) {
2945 // Both conditions must be false for the loop to continue executing.
2946 // Choose the less conservative count.
Dan Gohman60e9b072009-06-22 15:09:28 +00002947 if (BTI0.Exact == CouldNotCompute)
2948 BECount = BTI1.Exact;
2949 else if (BTI1.Exact == CouldNotCompute)
Dan Gohmana334aa72009-06-22 00:31:57 +00002950 BECount = BTI0.Exact;
Dan Gohman60e9b072009-06-22 15:09:28 +00002951 else
2952 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00002953 if (BTI0.Max == CouldNotCompute)
2954 MaxBECount = BTI1.Max;
2955 else if (BTI1.Max == CouldNotCompute)
2956 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00002957 else
2958 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00002959 } else {
2960 // Both conditions must be false for the loop to exit.
2961 assert(L->contains(TBB) && "Loop block has no successor in loop!");
2962 if (BTI0.Exact != CouldNotCompute && BTI1.Exact != CouldNotCompute)
2963 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
2964 if (BTI0.Max != CouldNotCompute && BTI1.Max != CouldNotCompute)
2965 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
2966 }
2967
2968 return BackedgeTakenInfo(BECount, MaxBECount);
2969 }
2970 }
2971
2972 // With an icmp, it may be feasible to compute an exact backedge-taken count.
2973 // Procede to the next level to examine the icmp.
2974 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
2975 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002976
Eli Friedman361e54d2009-05-09 12:32:42 +00002977 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00002978 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
2979}
2980
2981/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
2982/// backedge of the specified loop will execute if its exit condition
2983/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
2984ScalarEvolution::BackedgeTakenInfo
2985ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
2986 ICmpInst *ExitCond,
2987 BasicBlock *TBB,
2988 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002989
Reid Spencere4d87aa2006-12-23 06:05:41 +00002990 // If the condition was exit on true, convert the condition to exit on false
2991 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00002992 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00002993 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002994 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00002995 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002996
2997 // Handle common loops like: for (X = "string"; *X; ++X)
2998 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2999 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Owen Anderson372b46c2009-06-22 21:39:50 +00003000 const SCEV* ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003001 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmana334aa72009-06-22 00:31:57 +00003002 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3003 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3004 return BackedgeTakenInfo(ItCnt,
3005 isa<SCEVConstant>(ItCnt) ? ItCnt :
3006 getConstant(APInt::getMaxValue(BitWidth)-1));
3007 }
Chris Lattner673e02b2004-10-12 01:49:27 +00003008 }
3009
Owen Anderson372b46c2009-06-22 21:39:50 +00003010 const SCEV* LHS = getSCEV(ExitCond->getOperand(0));
3011 const SCEV* RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003012
3013 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003014 LHS = getSCEVAtScope(LHS, L);
3015 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003016
Reid Spencere4d87aa2006-12-23 06:05:41 +00003017 // At this point, we would like to compute how many iterations of the
3018 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003019 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3020 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003021 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003022 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003023 }
3024
Chris Lattner53e677a2004-04-02 20:23:17 +00003025 // If we have a comparison of a chrec against a constant, try to use value
3026 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003027 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3028 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003029 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003030 // Form the constant range.
3031 ConstantRange CompRange(
3032 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003033
Owen Anderson372b46c2009-06-22 21:39:50 +00003034 const SCEV* Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003035 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003036 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003037
Chris Lattner53e677a2004-04-02 20:23:17 +00003038 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003039 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003040 // Convert to: while (X-Y != 0)
Owen Anderson372b46c2009-06-22 21:39:50 +00003041 const SCEV* TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003042 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003043 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003044 }
3045 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00003046 // Convert to: while (X-Y == 0) // while (X == Y)
Owen Anderson372b46c2009-06-22 21:39:50 +00003047 const SCEV* TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003048 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003049 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003050 }
3051 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003052 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3053 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003054 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003055 }
3056 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003057 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3058 getNotSCEV(RHS), L, true);
3059 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003060 break;
3061 }
3062 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003063 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3064 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003065 break;
3066 }
3067 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003068 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3069 getNotSCEV(RHS), L, false);
3070 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003071 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003072 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003073 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003074#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003075 errs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003076 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003077 errs() << "[unsigned] ";
3078 errs() << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00003079 << Instruction::getOpcodeName(Instruction::ICmp)
3080 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003081#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003082 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003083 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003084 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003085 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003086}
3087
Chris Lattner673e02b2004-10-12 01:49:27 +00003088static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003089EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3090 ScalarEvolution &SE) {
Owen Anderson372b46c2009-06-22 21:39:50 +00003091 const SCEV* InVal = SE.getConstant(C);
3092 const SCEV* Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003093 assert(isa<SCEVConstant>(Val) &&
3094 "Evaluation of SCEV at constant didn't fold correctly?");
3095 return cast<SCEVConstant>(Val)->getValue();
3096}
3097
3098/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3099/// and a GEP expression (missing the pointer index) indexing into it, return
3100/// the addressed element of the initializer or null if the index expression is
3101/// invalid.
3102static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003103GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003104 const std::vector<ConstantInt*> &Indices) {
3105 Constant *Init = GV->getInitializer();
3106 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003107 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003108 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3109 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3110 Init = cast<Constant>(CS->getOperand(Idx));
3111 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3112 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3113 Init = cast<Constant>(CA->getOperand(Idx));
3114 } else if (isa<ConstantAggregateZero>(Init)) {
3115 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3116 assert(Idx < STy->getNumElements() && "Bad struct index!");
3117 Init = Constant::getNullValue(STy->getElementType(Idx));
3118 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3119 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3120 Init = Constant::getNullValue(ATy->getElementType());
3121 } else {
3122 assert(0 && "Unknown constant aggregate type!");
3123 }
3124 return 0;
3125 } else {
3126 return 0; // Unknown initializer type
3127 }
3128 }
3129 return Init;
3130}
3131
Dan Gohman46bdfb02009-02-24 18:55:53 +00003132/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3133/// 'icmp op load X, cst', try to see if we can compute the backedge
3134/// execution count.
Owen Anderson372b46c2009-06-22 21:39:50 +00003135const SCEV* ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00003136ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
3137 const Loop *L,
3138 ICmpInst::Predicate predicate) {
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003139 if (LI->isVolatile()) return CouldNotCompute;
Chris Lattner673e02b2004-10-12 01:49:27 +00003140
3141 // Check to see if the loaded pointer is a getelementptr of a global.
3142 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003143 if (!GEP) return CouldNotCompute;
Chris Lattner673e02b2004-10-12 01:49:27 +00003144
3145 // Make sure that it is really a constant global we are gepping, with an
3146 // initializer, and make sure the first IDX is really 0.
3147 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3148 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3149 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3150 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003151 return CouldNotCompute;
Chris Lattner673e02b2004-10-12 01:49:27 +00003152
3153 // Okay, we allow one non-constant index into the GEP instruction.
3154 Value *VarIdx = 0;
3155 std::vector<ConstantInt*> Indexes;
3156 unsigned VarIdxNum = 0;
3157 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3158 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3159 Indexes.push_back(CI);
3160 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003161 if (VarIdx) return CouldNotCompute; // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003162 VarIdx = GEP->getOperand(i);
3163 VarIdxNum = i-2;
3164 Indexes.push_back(0);
3165 }
3166
3167 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3168 // Check to see if X is a loop variant variable value now.
Owen Anderson372b46c2009-06-22 21:39:50 +00003169 const SCEV* Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003170 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003171
3172 // We can only recognize very limited forms of loop index expressions, in
3173 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003174 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003175 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3176 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3177 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003178 return CouldNotCompute;
Chris Lattner673e02b2004-10-12 01:49:27 +00003179
3180 unsigned MaxSteps = MaxBruteForceIterations;
3181 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003182 ConstantInt *ItCst =
Dan Gohman6de29f82009-06-15 22:12:54 +00003183 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003184 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003185
3186 // Form the GEP offset.
3187 Indexes[VarIdxNum] = Val;
3188
3189 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3190 if (Result == 0) break; // Cannot compute!
3191
3192 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003193 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003194 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003195 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003196#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003197 errs() << "\n***\n*** Computed loop count " << *ItCst
3198 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3199 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003200#endif
3201 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003202 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003203 }
3204 }
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003205 return CouldNotCompute;
Chris Lattner673e02b2004-10-12 01:49:27 +00003206}
3207
3208
Chris Lattner3221ad02004-04-17 22:58:41 +00003209/// CanConstantFold - Return true if we can constant fold an instruction of the
3210/// specified type, assuming that all operands were constants.
3211static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003212 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00003213 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3214 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003215
Chris Lattner3221ad02004-04-17 22:58:41 +00003216 if (const CallInst *CI = dyn_cast<CallInst>(I))
3217 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00003218 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00003219 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00003220}
3221
Chris Lattner3221ad02004-04-17 22:58:41 +00003222/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3223/// in the loop that V is derived from. We allow arbitrary operations along the
3224/// way, but the operands of an operation must either be constants or a value
3225/// derived from a constant PHI. If this expression does not fit with these
3226/// constraints, return null.
3227static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3228 // If this is not an instruction, or if this is an instruction outside of the
3229 // loop, it can't be derived from a loop PHI.
3230 Instruction *I = dyn_cast<Instruction>(V);
3231 if (I == 0 || !L->contains(I->getParent())) return 0;
3232
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003233 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003234 if (L->getHeader() == I->getParent())
3235 return PN;
3236 else
3237 // We don't currently keep track of the control flow needed to evaluate
3238 // PHIs, so we cannot handle PHIs inside of loops.
3239 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003240 }
Chris Lattner3221ad02004-04-17 22:58:41 +00003241
3242 // If we won't be able to constant fold this expression even if the operands
3243 // are constants, return early.
3244 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003245
Chris Lattner3221ad02004-04-17 22:58:41 +00003246 // Otherwise, we can evaluate this instruction if all of its operands are
3247 // constant or derived from a PHI node themselves.
3248 PHINode *PHI = 0;
3249 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3250 if (!(isa<Constant>(I->getOperand(Op)) ||
3251 isa<GlobalValue>(I->getOperand(Op)))) {
3252 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3253 if (P == 0) return 0; // Not evolving from PHI
3254 if (PHI == 0)
3255 PHI = P;
3256 else if (PHI != P)
3257 return 0; // Evolving from multiple different PHIs.
3258 }
3259
3260 // This is a expression evolving from a constant PHI!
3261 return PHI;
3262}
3263
3264/// EvaluateExpression - Given an expression that passes the
3265/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3266/// in the loop has the value PHIVal. If we can't fold this expression for some
3267/// reason, return null.
3268static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3269 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00003270 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00003271 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00003272 Instruction *I = cast<Instruction>(V);
3273
3274 std::vector<Constant*> Operands;
3275 Operands.resize(I->getNumOperands());
3276
3277 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3278 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3279 if (Operands[i] == 0) return 0;
3280 }
3281
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003282 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3283 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3284 &Operands[0], Operands.size());
3285 else
3286 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3287 &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00003288}
3289
3290/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3291/// in the header of its containing loop, we know the loop executes a
3292/// constant number of times, and the PHI node is just a recurrence
3293/// involving constants, fold it.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003294Constant *ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00003295getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00003296 std::map<PHINode*, Constant*>::iterator I =
3297 ConstantEvolutionLoopExitValue.find(PN);
3298 if (I != ConstantEvolutionLoopExitValue.end())
3299 return I->second;
3300
Dan Gohman46bdfb02009-02-24 18:55:53 +00003301 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00003302 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3303
3304 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3305
3306 // Since the loop is canonicalized, the PHI node must have two entries. One
3307 // entry must be a constant (coming in from outside of the loop), and the
3308 // second must be derived from the same PHI.
3309 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3310 Constant *StartCST =
3311 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3312 if (StartCST == 0)
3313 return RetVal = 0; // Must be a constant.
3314
3315 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3316 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3317 if (PN2 != PN)
3318 return RetVal = 0; // Not derived from same PHI.
3319
3320 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003321 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00003322 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00003323
Dan Gohman46bdfb02009-02-24 18:55:53 +00003324 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00003325 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003326 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3327 if (IterationNum == NumIterations)
3328 return RetVal = PHIVal; // Got exit value!
3329
3330 // Compute the value of the PHI node for the next iteration.
3331 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3332 if (NextPHI == PHIVal)
3333 return RetVal = NextPHI; // Stopped evolving!
3334 if (NextPHI == 0)
3335 return 0; // Couldn't evaluate!
3336 PHIVal = NextPHI;
3337 }
3338}
3339
Dan Gohman46bdfb02009-02-24 18:55:53 +00003340/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00003341/// constant number of times (the condition evolves only from constants),
3342/// try to evaluate a few iterations of the loop until we get the exit
3343/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003344/// evaluate the trip count of the loop, return CouldNotCompute.
Owen Anderson372b46c2009-06-22 21:39:50 +00003345const SCEV* ScalarEvolution::
Dan Gohman46bdfb02009-02-24 18:55:53 +00003346ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003347 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003348 if (PN == 0) return CouldNotCompute;
Chris Lattner7980fb92004-04-17 18:36:24 +00003349
3350 // Since the loop is canonicalized, the PHI node must have two entries. One
3351 // entry must be a constant (coming in from outside of the loop), and the
3352 // second must be derived from the same PHI.
3353 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3354 Constant *StartCST =
3355 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003356 if (StartCST == 0) return CouldNotCompute; // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00003357
3358 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3359 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003360 if (PN2 != PN) return CouldNotCompute; // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00003361
3362 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3363 // the loop symbolically to determine when the condition gets a value of
3364 // "ExitWhen".
3365 unsigned IterationNum = 0;
3366 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3367 for (Constant *PHIVal = StartCST;
3368 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003369 ConstantInt *CondVal =
3370 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00003371
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003372 // Couldn't symbolically evaluate.
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003373 if (!CondVal) return CouldNotCompute;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003374
Reid Spencere8019bb2007-03-01 07:25:48 +00003375 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003376 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00003377 ++NumBruteForceTripCountsComputed;
Dan Gohman6de29f82009-06-15 22:12:54 +00003378 return getConstant(Type::Int32Ty, IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00003379 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003380
Chris Lattner3221ad02004-04-17 22:58:41 +00003381 // Compute the value of the PHI node for the next iteration.
3382 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3383 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003384 return CouldNotCompute; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00003385 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00003386 }
3387
3388 // Too many iterations were needed to evaluate.
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003389 return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00003390}
3391
Dan Gohman66a7e852009-05-08 20:38:54 +00003392/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3393/// at the specified scope in the program. The L value specifies a loop
3394/// nest to evaluate the expression at, where null is the top-level or a
3395/// specified loop is immediately inside of the loop.
3396///
3397/// This method can be used to compute the exit value for a variable defined
3398/// in a loop by querying what the value will hold in the parent loop.
3399///
Dan Gohmand594e6f2009-05-24 23:25:42 +00003400/// In the case that a relevant loop exit value cannot be computed, the
3401/// original value V is returned.
Owen Anderson372b46c2009-06-22 21:39:50 +00003402const SCEV* ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003403 // FIXME: this should be turned into a virtual method on SCEV!
3404
Chris Lattner3221ad02004-04-17 22:58:41 +00003405 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003406
Nick Lewycky3e630762008-02-20 06:48:22 +00003407 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00003408 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00003409 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003410 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003411 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00003412 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3413 if (PHINode *PN = dyn_cast<PHINode>(I))
3414 if (PN->getParent() == LI->getHeader()) {
3415 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00003416 // to see if the loop that contains it has a known backedge-taken
3417 // count. If so, we may be able to force computation of the exit
3418 // value.
Owen Anderson372b46c2009-06-22 21:39:50 +00003419 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00003420 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003421 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003422 // Okay, we know how many times the containing loop executes. If
3423 // this is a constant evolving PHI node, get the final value at
3424 // the specified iteration number.
3425 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00003426 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00003427 LI);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003428 if (RV) return getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00003429 }
3430 }
3431
Reid Spencer09906f32006-12-04 21:33:23 +00003432 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00003433 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00003434 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00003435 // result. This is particularly useful for computing loop exit values.
3436 if (CanConstantFold(I)) {
Dan Gohman6bce6432009-05-08 20:47:27 +00003437 // Check to see if we've folded this instruction at this loop before.
3438 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3439 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3440 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3441 if (!Pair.second)
3442 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
3443
Chris Lattner3221ad02004-04-17 22:58:41 +00003444 std::vector<Constant*> Operands;
3445 Operands.reserve(I->getNumOperands());
3446 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3447 Value *Op = I->getOperand(i);
3448 if (Constant *C = dyn_cast<Constant>(Op)) {
3449 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003450 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00003451 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00003452 // non-integer and non-pointer, don't even try to analyze them
3453 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00003454 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00003455 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00003456
Owen Anderson372b46c2009-06-22 21:39:50 +00003457 const SCEV* OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohman622ed672009-05-04 22:02:23 +00003458 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003459 Constant *C = SC->getValue();
3460 if (C->getType() != Op->getType())
3461 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3462 Op->getType(),
3463 false),
3464 C, Op->getType());
3465 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00003466 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00003467 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3468 if (C->getType() != Op->getType())
3469 C =
3470 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3471 Op->getType(),
3472 false),
3473 C, Op->getType());
3474 Operands.push_back(C);
3475 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00003476 return V;
3477 } else {
3478 return V;
3479 }
3480 }
3481 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003482
3483 Constant *C;
3484 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3485 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3486 &Operands[0], Operands.size());
3487 else
3488 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3489 &Operands[0], Operands.size());
Dan Gohman6bce6432009-05-08 20:47:27 +00003490 Pair.first->second = C;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003491 return getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00003492 }
3493 }
3494
3495 // This is some other type of SCEVUnknown, just return it.
3496 return V;
3497 }
3498
Dan Gohman622ed672009-05-04 22:02:23 +00003499 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003500 // Avoid performing the look-up in the common case where the specified
3501 // expression has no loop-variant portions.
3502 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Owen Anderson372b46c2009-06-22 21:39:50 +00003503 const SCEV* OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003504 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003505 // Okay, at least one of these operands is loop variant but might be
3506 // foldable. Build a new instance of the folded commutative expression.
Owen Anderson372b46c2009-06-22 21:39:50 +00003507 SmallVector<const SCEV*, 8> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00003508 NewOps.push_back(OpAtScope);
3509
3510 for (++i; i != e; ++i) {
3511 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003512 NewOps.push_back(OpAtScope);
3513 }
3514 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003515 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003516 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003517 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003518 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003519 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00003520 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003521 return getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00003522 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00003523 }
3524 }
3525 // If we got here, all operands are loop invariant.
3526 return Comm;
3527 }
3528
Dan Gohman622ed672009-05-04 22:02:23 +00003529 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Owen Anderson372b46c2009-06-22 21:39:50 +00003530 const SCEV* LHS = getSCEVAtScope(Div->getLHS(), L);
3531 const SCEV* RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00003532 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3533 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003534 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00003535 }
3536
3537 // If this is a loop recurrence for a loop that does not contain L, then we
3538 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00003539 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003540 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3541 // To evaluate this recurrence, we need to know how many times the AddRec
3542 // loop iterates. Compute this now.
Owen Anderson372b46c2009-06-22 21:39:50 +00003543 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003544 if (BackedgeTakenCount == CouldNotCompute) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003545
Eli Friedmanb42a6262008-08-04 23:49:06 +00003546 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003547 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003548 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00003549 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00003550 }
3551
Dan Gohman622ed672009-05-04 22:02:23 +00003552 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Owen Anderson372b46c2009-06-22 21:39:50 +00003553 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003554 if (Op == Cast->getOperand())
3555 return Cast; // must be loop invariant
3556 return getZeroExtendExpr(Op, Cast->getType());
3557 }
3558
Dan Gohman622ed672009-05-04 22:02:23 +00003559 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Owen Anderson372b46c2009-06-22 21:39:50 +00003560 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003561 if (Op == Cast->getOperand())
3562 return Cast; // must be loop invariant
3563 return getSignExtendExpr(Op, Cast->getType());
3564 }
3565
Dan Gohman622ed672009-05-04 22:02:23 +00003566 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Owen Anderson372b46c2009-06-22 21:39:50 +00003567 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00003568 if (Op == Cast->getOperand())
3569 return Cast; // must be loop invariant
3570 return getTruncateExpr(Op, Cast->getType());
3571 }
3572
3573 assert(0 && "Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00003574 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00003575}
3576
Dan Gohman66a7e852009-05-08 20:38:54 +00003577/// getSCEVAtScope - This is a convenience function which does
3578/// getSCEVAtScope(getSCEV(V), L).
Owen Anderson372b46c2009-06-22 21:39:50 +00003579const SCEV* ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003580 return getSCEVAtScope(getSCEV(V), L);
3581}
3582
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003583/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3584/// following equation:
3585///
3586/// A * X = B (mod N)
3587///
3588/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3589/// A and B isn't important.
3590///
3591/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Owen Anderson372b46c2009-06-22 21:39:50 +00003592static const SCEV* SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003593 ScalarEvolution &SE) {
3594 uint32_t BW = A.getBitWidth();
3595 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3596 assert(A != 0 && "A must be non-zero.");
3597
3598 // 1. D = gcd(A, N)
3599 //
3600 // The gcd of A and N may have only one prime factor: 2. The number of
3601 // trailing zeros in A is its multiplicity
3602 uint32_t Mult2 = A.countTrailingZeros();
3603 // D = 2^Mult2
3604
3605 // 2. Check if B is divisible by D.
3606 //
3607 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3608 // is not less than multiplicity of this prime factor for D.
3609 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00003610 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003611
3612 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3613 // modulo (N / D).
3614 //
3615 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3616 // bit width during computations.
3617 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3618 APInt Mod(BW + 1, 0);
3619 Mod.set(BW - Mult2); // Mod = N / D
3620 APInt I = AD.multiplicativeInverse(Mod);
3621
3622 // 4. Compute the minimum unsigned root of the equation:
3623 // I * (B / D) mod (N / D)
3624 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3625
3626 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3627 // bits.
3628 return SE.getConstant(Result.trunc(BW));
3629}
Chris Lattner53e677a2004-04-02 20:23:17 +00003630
3631/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3632/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3633/// might be the same) or two SCEVCouldNotCompute objects.
3634///
Owen Anderson372b46c2009-06-22 21:39:50 +00003635static std::pair<const SCEV*,const SCEV*>
Dan Gohman246b2562007-10-22 18:31:58 +00003636SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003637 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00003638 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3639 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3640 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003641
Chris Lattner53e677a2004-04-02 20:23:17 +00003642 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00003643 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00003644 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003645 return std::make_pair(CNC, CNC);
3646 }
3647
Reid Spencere8019bb2007-03-01 07:25:48 +00003648 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00003649 const APInt &L = LC->getValue()->getValue();
3650 const APInt &M = MC->getValue()->getValue();
3651 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00003652 APInt Two(BitWidth, 2);
3653 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003654
Reid Spencere8019bb2007-03-01 07:25:48 +00003655 {
3656 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00003657 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00003658 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3659 // The B coefficient is M-N/2
3660 APInt B(M);
3661 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003662
Reid Spencere8019bb2007-03-01 07:25:48 +00003663 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00003664 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00003665
Reid Spencere8019bb2007-03-01 07:25:48 +00003666 // Compute the B^2-4ac term.
3667 APInt SqrtTerm(B);
3668 SqrtTerm *= B;
3669 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00003670
Reid Spencere8019bb2007-03-01 07:25:48 +00003671 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3672 // integer value or else APInt::sqrt() will assert.
3673 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003674
Reid Spencere8019bb2007-03-01 07:25:48 +00003675 // Compute the two solutions for the quadratic formula.
3676 // The divisions must be performed as signed divisions.
3677 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00003678 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00003679 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00003680 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00003681 return std::make_pair(CNC, CNC);
3682 }
3683
Reid Spencere8019bb2007-03-01 07:25:48 +00003684 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3685 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003686
Dan Gohman246b2562007-10-22 18:31:58 +00003687 return std::make_pair(SE.getConstant(Solution1),
3688 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00003689 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00003690}
3691
3692/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003693/// value to zero will execute. If not computable, return CouldNotCompute.
Owen Anderson372b46c2009-06-22 21:39:50 +00003694const SCEV* ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003695 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00003696 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003697 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00003698 if (C->getValue()->isZero()) return C;
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003699 return CouldNotCompute; // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00003700 }
3701
Dan Gohman35738ac2009-05-04 22:30:44 +00003702 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003703 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003704 return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00003705
3706 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003707 // If this is an affine expression, the execution count of this branch is
3708 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00003709 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003710 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00003711 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003712 // equivalent to:
3713 //
3714 // Step*N = -Start (mod 2^BW)
3715 //
3716 // where BW is the common bit width of Start and Step.
3717
Chris Lattner53e677a2004-04-02 20:23:17 +00003718 // Get the initial value for the loop.
Owen Anderson372b46c2009-06-22 21:39:50 +00003719 const SCEV* Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
3720 const SCEV* Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003721
Dan Gohman622ed672009-05-04 22:02:23 +00003722 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003723 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00003724
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003725 // First, handle unitary steps.
3726 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003727 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003728 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3729 return Start; // N = Start (as unsigned)
3730
3731 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00003732 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00003733 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003734 -StartC->getValue()->getValue(),
3735 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00003736 }
Chris Lattner42a75512007-01-15 02:27:26 +00003737 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003738 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3739 // the quadratic equation to solve it.
Owen Anderson372b46c2009-06-22 21:39:50 +00003740 std::pair<const SCEV*,const SCEV*> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003741 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00003742 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3743 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00003744 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003745#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003746 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3747 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003748#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00003749 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003750 if (ConstantInt *CB =
3751 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003752 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00003753 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00003754 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003755
Chris Lattner53e677a2004-04-02 20:23:17 +00003756 // We can only use this value if the chrec ends up with an exact zero
3757 // value at this index. When solving for "X*X != 5", for example, we
3758 // should not accept a root of 2.
Owen Anderson372b46c2009-06-22 21:39:50 +00003759 const SCEV* Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00003760 if (Val->isZero())
3761 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00003762 }
3763 }
3764 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003765
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003766 return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00003767}
3768
3769/// HowFarToNonZero - Return the number of times a backedge checking the
3770/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003771/// CouldNotCompute
Owen Anderson372b46c2009-06-22 21:39:50 +00003772const SCEV* ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003773 // Loops that look like: while (X == 0) are very strange indeed. We don't
3774 // handle them yet except for the trivial case. This could be expanded in the
3775 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003776
Chris Lattner53e677a2004-04-02 20:23:17 +00003777 // If the value is a constant, check to see if it is known to be non-zero
3778 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00003779 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00003780 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003781 return getIntegerSCEV(0, C->getType());
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003782 return CouldNotCompute; // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00003783 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003784
Chris Lattner53e677a2004-04-02 20:23:17 +00003785 // We could implement others, but I really doubt anyone writes loops like
3786 // this, and if they did, they would already be constant folded.
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003787 return CouldNotCompute;
Chris Lattner53e677a2004-04-02 20:23:17 +00003788}
3789
Dan Gohman859b4822009-05-18 15:36:09 +00003790/// getLoopPredecessor - If the given loop's header has exactly one unique
3791/// predecessor outside the loop, return it. Otherwise return null.
3792///
3793BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3794 BasicBlock *Header = L->getHeader();
3795 BasicBlock *Pred = 0;
3796 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3797 PI != E; ++PI)
3798 if (!L->contains(*PI)) {
3799 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3800 Pred = *PI;
3801 }
3802 return Pred;
3803}
3804
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003805/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3806/// (which may not be an immediate predecessor) which has exactly one
3807/// successor from which BB is reachable, or null if no such block is
3808/// found.
3809///
3810BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003811ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00003812 // If the block has a unique predecessor, then there is no path from the
3813 // predecessor to the block that does not go through the direct edge
3814 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003815 if (BasicBlock *Pred = BB->getSinglePredecessor())
3816 return Pred;
3817
3818 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00003819 // If the header has a unique predecessor outside the loop, it must be
3820 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003821 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00003822 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003823
3824 return 0;
3825}
3826
Dan Gohman763bad12009-06-20 00:35:32 +00003827/// HasSameValue - SCEV structural equivalence is usually sufficient for
3828/// testing whether two expressions are equal, however for the purposes of
3829/// looking for a condition guarding a loop, it can be useful to be a little
3830/// more general, since a front-end may have replicated the controlling
3831/// expression.
3832///
Owen Anderson372b46c2009-06-22 21:39:50 +00003833static bool HasSameValue(const SCEV* A, const SCEV* B) {
Dan Gohman763bad12009-06-20 00:35:32 +00003834 // Quick check to see if they are the same SCEV.
3835 if (A == B) return true;
3836
3837 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
3838 // two different instructions with the same value. Check for this case.
3839 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
3840 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
3841 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
3842 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
3843 if (AI->isIdenticalTo(BI))
3844 return true;
3845
3846 // Otherwise assume they may have a different value.
3847 return false;
3848}
3849
Dan Gohmanc2390b12009-02-12 22:19:27 +00003850/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman3d739fe2009-04-30 20:48:53 +00003851/// a conditional between LHS and RHS. This is used to help avoid max
3852/// expressions in loop trip counts.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003853bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman3d739fe2009-04-30 20:48:53 +00003854 ICmpInst::Predicate Pred,
Dan Gohman35738ac2009-05-04 22:30:44 +00003855 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00003856 // Interpret a null as meaning no loop, where there is obviously no guard
3857 // (interprocedural conditions notwithstanding).
3858 if (!L) return false;
3859
Dan Gohman859b4822009-05-18 15:36:09 +00003860 BasicBlock *Predecessor = getLoopPredecessor(L);
3861 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00003862
Dan Gohman859b4822009-05-18 15:36:09 +00003863 // Starting at the loop predecessor, climb up the predecessor chain, as long
3864 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00003865 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00003866 for (; Predecessor;
3867 PredecessorDest = Predecessor,
3868 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00003869
3870 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00003871 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00003872 if (!LoopEntryPredicate ||
3873 LoopEntryPredicate->isUnconditional())
3874 continue;
3875
3876 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3877 if (!ICI) continue;
3878
3879 // Now that we found a conditional branch that dominates the loop, check to
3880 // see if it is the comparison we are looking for.
3881 Value *PreCondLHS = ICI->getOperand(0);
3882 Value *PreCondRHS = ICI->getOperand(1);
3883 ICmpInst::Predicate Cond;
Dan Gohman859b4822009-05-18 15:36:09 +00003884 if (LoopEntryPredicate->getSuccessor(0) == PredecessorDest)
Dan Gohman38372182008-08-12 20:17:31 +00003885 Cond = ICI->getPredicate();
3886 else
3887 Cond = ICI->getInversePredicate();
3888
Dan Gohmanc2390b12009-02-12 22:19:27 +00003889 if (Cond == Pred)
3890 ; // An exact match.
3891 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3892 ; // The actual condition is beyond sufficient.
3893 else
3894 // Check a few special cases.
3895 switch (Cond) {
3896 case ICmpInst::ICMP_UGT:
3897 if (Pred == ICmpInst::ICMP_ULT) {
3898 std::swap(PreCondLHS, PreCondRHS);
3899 Cond = ICmpInst::ICMP_ULT;
3900 break;
3901 }
3902 continue;
3903 case ICmpInst::ICMP_SGT:
3904 if (Pred == ICmpInst::ICMP_SLT) {
3905 std::swap(PreCondLHS, PreCondRHS);
3906 Cond = ICmpInst::ICMP_SLT;
3907 break;
3908 }
3909 continue;
3910 case ICmpInst::ICMP_NE:
3911 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3912 // so check for this case by checking if the NE is comparing against
3913 // a minimum or maximum constant.
3914 if (!ICmpInst::isTrueWhenEqual(Pred))
3915 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3916 const APInt &A = CI->getValue();
3917 switch (Pred) {
3918 case ICmpInst::ICMP_SLT:
3919 if (A.isMaxSignedValue()) break;
3920 continue;
3921 case ICmpInst::ICMP_SGT:
3922 if (A.isMinSignedValue()) break;
3923 continue;
3924 case ICmpInst::ICMP_ULT:
3925 if (A.isMaxValue()) break;
3926 continue;
3927 case ICmpInst::ICMP_UGT:
3928 if (A.isMinValue()) break;
3929 continue;
3930 default:
3931 continue;
3932 }
3933 Cond = ICmpInst::ICMP_NE;
3934 // NE is symmetric but the original comparison may not be. Swap
3935 // the operands if necessary so that they match below.
3936 if (isa<SCEVConstant>(LHS))
3937 std::swap(PreCondLHS, PreCondRHS);
3938 break;
3939 }
3940 continue;
3941 default:
3942 // We weren't able to reconcile the condition.
3943 continue;
3944 }
Dan Gohman38372182008-08-12 20:17:31 +00003945
3946 if (!PreCondLHS->getType()->isInteger()) continue;
3947
Owen Anderson372b46c2009-06-22 21:39:50 +00003948 const SCEV* PreCondLHSSCEV = getSCEV(PreCondLHS);
3949 const SCEV* PreCondRHSSCEV = getSCEV(PreCondRHS);
Dan Gohman763bad12009-06-20 00:35:32 +00003950 if ((HasSameValue(LHS, PreCondLHSSCEV) &&
3951 HasSameValue(RHS, PreCondRHSSCEV)) ||
3952 (HasSameValue(LHS, getNotSCEV(PreCondRHSSCEV)) &&
3953 HasSameValue(RHS, getNotSCEV(PreCondLHSSCEV))))
Dan Gohman38372182008-08-12 20:17:31 +00003954 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00003955 }
3956
Dan Gohman38372182008-08-12 20:17:31 +00003957 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00003958}
3959
Dan Gohman51f53b72009-06-21 23:46:38 +00003960/// getBECount - Subtract the end and start values and divide by the step,
3961/// rounding up, to get the number of times the backedge is executed. Return
3962/// CouldNotCompute if an intermediate computation overflows.
Owen Anderson372b46c2009-06-22 21:39:50 +00003963const SCEV* ScalarEvolution::getBECount(const SCEV* Start,
3964 const SCEV* End,
3965 const SCEV* Step) {
Dan Gohman51f53b72009-06-21 23:46:38 +00003966 const Type *Ty = Start->getType();
Owen Anderson372b46c2009-06-22 21:39:50 +00003967 const SCEV* NegOne = getIntegerSCEV(-1, Ty);
3968 const SCEV* Diff = getMinusSCEV(End, Start);
3969 const SCEV* RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00003970
3971 // Add an adjustment to the difference between End and Start so that
3972 // the division will effectively round up.
Owen Anderson372b46c2009-06-22 21:39:50 +00003973 const SCEV* Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00003974
3975 // Check Add for unsigned overflow.
3976 // TODO: More sophisticated things could be done here.
3977 const Type *WideTy = IntegerType::get(getTypeSizeInBits(Ty) + 1);
Owen Anderson372b46c2009-06-22 21:39:50 +00003978 const SCEV* OperandExtendedAdd =
Dan Gohman51f53b72009-06-21 23:46:38 +00003979 getAddExpr(getZeroExtendExpr(Diff, WideTy),
3980 getZeroExtendExpr(RoundUp, WideTy));
3981 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
3982 return CouldNotCompute;
3983
3984 return getUDivExpr(Add, Step);
3985}
3986
Chris Lattnerdb25de42005-08-15 23:33:51 +00003987/// HowManyLessThans - Return the number of times a backedge containing the
3988/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003989/// CouldNotCompute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003990ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Dan Gohman35738ac2009-05-04 22:30:44 +00003991HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3992 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00003993 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003994 if (!RHS->isLoopInvariant(L)) return CouldNotCompute;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003995
Dan Gohman35738ac2009-05-04 22:30:44 +00003996 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00003997 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman86fbf2f2009-06-06 14:37:11 +00003998 return CouldNotCompute;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003999
4000 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00004001 // FORNOW: We only support unit strides.
Dan Gohmana1af7572009-04-30 20:47:05 +00004002 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Owen Anderson372b46c2009-06-22 21:39:50 +00004003 const SCEV* Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00004004
4005 // TODO: handle non-constant strides.
4006 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4007 if (!CStep || CStep->isZero())
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004008 return CouldNotCompute;
Dan Gohman70a1fe72009-05-18 15:22:39 +00004009 if (CStep->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00004010 // With unit stride, the iteration never steps past the limit value.
4011 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4012 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4013 // Test whether a positive iteration iteration can step past the limit
4014 // value and past the maximum value for its type in a single step.
4015 if (isSigned) {
4016 APInt Max = APInt::getSignedMaxValue(BitWidth);
4017 if ((Max - CStep->getValue()->getValue())
4018 .slt(CLimit->getValue()->getValue()))
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004019 return CouldNotCompute;
Dan Gohmana1af7572009-04-30 20:47:05 +00004020 } else {
4021 APInt Max = APInt::getMaxValue(BitWidth);
4022 if ((Max - CStep->getValue()->getValue())
4023 .ult(CLimit->getValue()->getValue()))
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004024 return CouldNotCompute;
Dan Gohmana1af7572009-04-30 20:47:05 +00004025 }
4026 } else
4027 // TODO: handle non-constant limit values below.
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004028 return CouldNotCompute;
Dan Gohmana1af7572009-04-30 20:47:05 +00004029 } else
4030 // TODO: handle negative strides below.
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004031 return CouldNotCompute;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004032
Dan Gohmana1af7572009-04-30 20:47:05 +00004033 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4034 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4035 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00004036 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00004037
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004038 // First, we get the value of the LHS in the first iteration: n
Owen Anderson372b46c2009-06-22 21:39:50 +00004039 const SCEV* Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004040
Dan Gohmana1af7572009-04-30 20:47:05 +00004041 // Determine the minimum constant start value.
Owen Anderson372b46c2009-06-22 21:39:50 +00004042 const SCEV* MinStart = isa<SCEVConstant>(Start) ? Start :
Dan Gohmana1af7572009-04-30 20:47:05 +00004043 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
4044 APInt::getMinValue(BitWidth));
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004045
Dan Gohmana1af7572009-04-30 20:47:05 +00004046 // If we know that the condition is true in order to enter the loop,
4047 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00004048 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4049 // the division must round up.
Owen Anderson372b46c2009-06-22 21:39:50 +00004050 const SCEV* End = RHS;
Dan Gohmana1af7572009-04-30 20:47:05 +00004051 if (!isLoopGuardedByCond(L,
4052 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
4053 getMinusSCEV(Start, Step), RHS))
4054 End = isSigned ? getSMaxExpr(RHS, Start)
4055 : getUMaxExpr(RHS, Start);
4056
4057 // Determine the maximum constant end value.
Owen Anderson372b46c2009-06-22 21:39:50 +00004058 const SCEV* MaxEnd =
Dan Gohman3964acc2009-06-20 00:32:22 +00004059 isa<SCEVConstant>(End) ? End :
4060 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth)
4061 .ashr(GetMinSignBits(End) - 1) :
4062 APInt::getMaxValue(BitWidth)
4063 .lshr(GetMinLeadingZeros(End)));
Dan Gohmana1af7572009-04-30 20:47:05 +00004064
4065 // Finally, we subtract these two values and divide, rounding up, to get
4066 // the number of times the backedge is executed.
Owen Anderson372b46c2009-06-22 21:39:50 +00004067 const SCEV* BECount = getBECount(Start, End, Step);
Dan Gohmana1af7572009-04-30 20:47:05 +00004068
4069 // The maximum backedge count is similar, except using the minimum start
4070 // value and the maximum end value.
Owen Anderson372b46c2009-06-22 21:39:50 +00004071 const SCEV* MaxBECount = getBECount(MinStart, MaxEnd, Step);;
Dan Gohmana1af7572009-04-30 20:47:05 +00004072
4073 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004074 }
4075
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004076 return CouldNotCompute;
Chris Lattnerdb25de42005-08-15 23:33:51 +00004077}
4078
Chris Lattner53e677a2004-04-02 20:23:17 +00004079/// getNumIterationsInRange - Return the number of iterations of this loop that
4080/// produce values in the specified constant range. Another way of looking at
4081/// this is that it returns the first iteration number where the value is not in
4082/// the condition, thus computing the exit count. If the iteration count can't
4083/// be computed, an instance of SCEVCouldNotCompute is returned.
Owen Anderson372b46c2009-06-22 21:39:50 +00004084const SCEV* SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman246b2562007-10-22 18:31:58 +00004085 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00004086 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004087 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004088
4089 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00004090 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00004091 if (!SC->getValue()->isZero()) {
Owen Anderson372b46c2009-06-22 21:39:50 +00004092 SmallVector<const SCEV*, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004093 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Owen Anderson372b46c2009-06-22 21:39:50 +00004094 const SCEV* Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00004095 if (const SCEVAddRecExpr *ShiftedAddRec =
4096 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00004097 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00004098 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00004099 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004100 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004101 }
4102
4103 // The only time we can solve this is when we have all constant indices.
4104 // Otherwise, we cannot determine the overflow conditions.
4105 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4106 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004107 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004108
4109
4110 // Okay at this point we know that all elements of the chrec are constants and
4111 // that the start element is zero.
4112
4113 // First check to see if the range contains zero. If not, the first
4114 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00004115 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00004116 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00004117 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004118
Chris Lattner53e677a2004-04-02 20:23:17 +00004119 if (isAffine()) {
4120 // If this is an affine expression then we have this situation:
4121 // Solve {0,+,A} in Range === Ax in Range
4122
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004123 // We know that zero is in the range. If A is positive then we know that
4124 // the upper value of the range must be the first possible exit value.
4125 // If A is negative then the lower of the range is the last possible loop
4126 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00004127 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004128 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4129 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00004130
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00004131 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00004132 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00004133 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00004134
4135 // Evaluate at the exit value. If we really did fall out of the valid
4136 // range, then we computed our trip count, otherwise wrap around or other
4137 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00004138 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004139 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004140 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004141
4142 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00004143 assert(Range.contains(
4144 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00004145 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00004146 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00004147 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00004148 } else if (isQuadratic()) {
4149 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4150 // quadratic equation to solve it. To do this, we must frame our problem in
4151 // terms of figuring out when zero is crossed, instead of when
4152 // Range.getUpper() is crossed.
Owen Anderson372b46c2009-06-22 21:39:50 +00004153 SmallVector<const SCEV*, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004154 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Owen Anderson372b46c2009-06-22 21:39:50 +00004155 const SCEV* NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004156
4157 // Next, solve the constructed addrec
Owen Anderson372b46c2009-06-22 21:39:50 +00004158 std::pair<const SCEV*,const SCEV*> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00004159 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00004160 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4161 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004162 if (R1) {
4163 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004164 if (ConstantInt *CB =
4165 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004166 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004167 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004168 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004169
Chris Lattner53e677a2004-04-02 20:23:17 +00004170 // Make sure the root is not off by one. The returned iteration should
4171 // not be in the range, but the previous one should be. When solving
4172 // for "X*X < 5", for example, we should not return a root of 2.
4173 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00004174 R1->getValue(),
4175 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004176 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004177 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00004178 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004179
Dan Gohman246b2562007-10-22 18:31:58 +00004180 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004181 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00004182 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004183 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004184 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004185
Chris Lattner53e677a2004-04-02 20:23:17 +00004186 // If R1 was not in the range, then it is a good return value. Make
4187 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00004188 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00004189 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00004190 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00004191 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004192 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00004193 }
4194 }
4195 }
4196
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004197 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004198}
4199
4200
4201
4202//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00004203// SCEVCallbackVH Class Implementation
4204//===----------------------------------------------------------------------===//
4205
Dan Gohman1959b752009-05-19 19:22:47 +00004206void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohman35738ac2009-05-04 22:30:44 +00004207 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4208 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4209 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004210 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4211 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004212 SE->Scalars.erase(getValPtr());
4213 // this now dangles!
4214}
4215
Dan Gohman1959b752009-05-19 19:22:47 +00004216void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004217 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4218
4219 // Forget all the expressions associated with users of the old value,
4220 // so that future queries will recompute the expressions using the new
4221 // value.
4222 SmallVector<User *, 16> Worklist;
4223 Value *Old = getValPtr();
4224 bool DeleteOld = false;
4225 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4226 UI != UE; ++UI)
4227 Worklist.push_back(*UI);
4228 while (!Worklist.empty()) {
4229 User *U = Worklist.pop_back_val();
4230 // Deleting the Old value will cause this to dangle. Postpone
4231 // that until everything else is done.
4232 if (U == Old) {
4233 DeleteOld = true;
4234 continue;
4235 }
4236 if (PHINode *PN = dyn_cast<PHINode>(U))
4237 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004238 if (Instruction *I = dyn_cast<Instruction>(U))
4239 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004240 if (SE->Scalars.erase(U))
4241 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4242 UI != UE; ++UI)
4243 Worklist.push_back(*UI);
4244 }
4245 if (DeleteOld) {
4246 if (PHINode *PN = dyn_cast<PHINode>(Old))
4247 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman6bce6432009-05-08 20:47:27 +00004248 if (Instruction *I = dyn_cast<Instruction>(Old))
4249 SE->ValuesAtScopes.erase(I);
Dan Gohman35738ac2009-05-04 22:30:44 +00004250 SE->Scalars.erase(Old);
4251 // this now dangles!
4252 }
4253 // this may dangle!
4254}
4255
Dan Gohman1959b752009-05-19 19:22:47 +00004256ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00004257 : CallbackVH(V), SE(se) {}
4258
4259//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00004260// ScalarEvolution Class Implementation
4261//===----------------------------------------------------------------------===//
4262
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004263ScalarEvolution::ScalarEvolution()
Owen Anderson4a7893b2009-06-18 22:25:12 +00004264 : FunctionPass(&ID), CouldNotCompute(new SCEVCouldNotCompute(0)) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004265}
4266
Chris Lattner53e677a2004-04-02 20:23:17 +00004267bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004268 this->F = &F;
4269 LI = &getAnalysis<LoopInfo>();
4270 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00004271 return false;
4272}
4273
4274void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004275 Scalars.clear();
4276 BackedgeTakenCounts.clear();
4277 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00004278 ValuesAtScopes.clear();
Owen Anderson08367b62009-06-22 18:25:46 +00004279
4280 for (std::map<ConstantInt*, SCEVConstant*>::iterator
4281 I = SCEVConstants.begin(), E = SCEVConstants.end(); I != E; ++I)
4282 delete I->second;
4283 for (std::map<std::pair<const SCEV*, const Type*>,
4284 SCEVTruncateExpr*>::iterator I = SCEVTruncates.begin(),
4285 E = SCEVTruncates.end(); I != E; ++I)
4286 delete I->second;
4287 for (std::map<std::pair<const SCEV*, const Type*>,
4288 SCEVZeroExtendExpr*>::iterator I = SCEVZeroExtends.begin(),
4289 E = SCEVZeroExtends.end(); I != E; ++I)
4290 delete I->second;
4291 for (std::map<std::pair<unsigned, std::vector<const SCEV*> >,
4292 SCEVCommutativeExpr*>::iterator I = SCEVCommExprs.begin(),
4293 E = SCEVCommExprs.end(); I != E; ++I)
4294 delete I->second;
4295 for (std::map<std::pair<const SCEV*, const SCEV*>, SCEVUDivExpr*>::iterator
4296 I = SCEVUDivs.begin(), E = SCEVUDivs.end(); I != E; ++I)
4297 delete I->second;
4298 for (std::map<std::pair<const SCEV*, const Type*>,
4299 SCEVSignExtendExpr*>::iterator I = SCEVSignExtends.begin(),
4300 E = SCEVSignExtends.end(); I != E; ++I)
4301 delete I->second;
4302 for (std::map<std::pair<const Loop *, std::vector<const SCEV*> >,
4303 SCEVAddRecExpr*>::iterator I = SCEVAddRecExprs.begin(),
4304 E = SCEVAddRecExprs.end(); I != E; ++I)
4305 delete I->second;
4306 for (std::map<Value*, SCEVUnknown*>::iterator I = SCEVUnknowns.begin(),
4307 E = SCEVUnknowns.end(); I != E; ++I)
4308 delete I->second;
4309
4310 SCEVConstants.clear();
4311 SCEVTruncates.clear();
4312 SCEVZeroExtends.clear();
4313 SCEVCommExprs.clear();
4314 SCEVUDivs.clear();
4315 SCEVSignExtends.clear();
4316 SCEVAddRecExprs.clear();
4317 SCEVUnknowns.clear();
Chris Lattner53e677a2004-04-02 20:23:17 +00004318}
4319
4320void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4321 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00004322 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +00004323}
4324
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004325bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00004326 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00004327}
4328
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004329static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00004330 const Loop *L) {
4331 // Print all inner loops first
4332 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4333 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004334
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004335 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00004336
Devang Patelb7211a22007-08-21 00:31:24 +00004337 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00004338 L->getExitBlocks(ExitBlocks);
4339 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004340 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004341
Dan Gohman46bdfb02009-02-24 18:55:53 +00004342 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4343 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004344 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00004345 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00004346 }
4347
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00004348 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00004349}
4350
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004351void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004352 // ScalarEvolution's implementaiton of the print method is to print
4353 // out SCEV values of all instructions that are interesting. Doing
4354 // this potentially causes it to create new SCEV objects though,
4355 // which technically conflicts with the const qualifier. This isn't
4356 // observable from outside the class though (the hasSCEV function
4357 // notwithstanding), so casting away the const isn't dangerous.
4358 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004359
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004360 OS << "Classifying expressions for: " << F->getName() << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00004361 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00004362 if (isSCEVable(I->getType())) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00004363 OS << *I;
Dan Gohman8dae1382008-09-14 17:21:12 +00004364 OS << " --> ";
Owen Anderson372b46c2009-06-22 21:39:50 +00004365 const SCEV* SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00004366 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004367
Dan Gohman0c689c52009-06-19 17:49:54 +00004368 const Loop *L = LI->getLoopFor((*I).getParent());
4369
Owen Anderson372b46c2009-06-22 21:39:50 +00004370 const SCEV* AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00004371 if (AtUse != SV) {
4372 OS << " --> ";
4373 AtUse->print(OS);
4374 }
4375
4376 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00004377 OS << "\t\t" "Exits: ";
Owen Anderson372b46c2009-06-22 21:39:50 +00004378 const SCEV* ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00004379 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004380 OS << "<<Unknown>>";
4381 } else {
4382 OS << *ExitValue;
4383 }
4384 }
4385
Chris Lattner53e677a2004-04-02 20:23:17 +00004386 OS << "\n";
4387 }
4388
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004389 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4390 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4391 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00004392}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004393
4394void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4395 raw_os_ostream OS(o);
4396 print(OS, M);
4397}