blob: 75572a7ba20f1d3d2e29efe6c40dd3b3b1854d45 [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
Dan Gohmanbc3d77a2009-07-25 16:18:07 +000017// can handle. We only create one SCEV of a particular shape, so
18// pointer-comparisons for equality are legal.
Chris Lattner53e677a2004-04-02 20:23:17 +000019//
20// One important aspect of the SCEV objects is that they are never cyclic, even
21// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
22// the PHI node is one of the idioms that we can represent (e.g., a polynomial
23// recurrence) then we represent it directly as a recurrence node, otherwise we
24// represent it as a SCEVUnknown node.
25//
26// In addition to being able to represent expressions of various types, we also
27// have folders that are used to build the *canonical* representation for a
28// particular expression. These folders are capable of using a variety of
29// rewrite rules to simplify the expressions.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000030//
Chris Lattner53e677a2004-04-02 20:23:17 +000031// Once the folders are defined, we can implement the more interesting
32// higher-level code, such as the code that recognizes PHI nodes of various
33// types, computes the execution count of a loop, etc.
34//
Chris Lattner53e677a2004-04-02 20:23:17 +000035// TODO: We should use these routines and value representations to implement
36// dependence analysis!
37//
38//===----------------------------------------------------------------------===//
39//
40// There are several good references for the techniques used in this analysis.
41//
42// Chains of recurrences -- a method to expedite the evaluation
43// of closed-form functions
44// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45//
46// On computational properties of chains of recurrences
47// Eugene V. Zima
48//
49// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50// Robert A. van Engelen
51//
52// Efficient Symbolic Analysis for Optimizing Compilers
53// Robert A. van Engelen
54//
55// Using the chains of recurrences algebra for data dependence testing and
56// induction variable substitution
57// MS Thesis, Johnie Birch
58//
59//===----------------------------------------------------------------------===//
60
Chris Lattner3b27d682006-12-19 22:30:33 +000061#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000062#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000063#include "llvm/Constants.h"
64#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000065#include "llvm/GlobalVariable.h"
Dan Gohman26812322009-08-25 17:49:57 +000066#include "llvm/GlobalAlias.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
Owen Anderson76f600b2009-07-06 22:37:39 +000068#include "llvm/LLVMContext.h"
Dan Gohmanca178902009-07-17 20:47:02 +000069#include "llvm/Operator.h"
John Criswella1156432005-10-27 15:54:34 +000070#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng5a6c1a82009-02-17 00:13:06 +000071#include "llvm/Analysis/Dominators.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000072#include "llvm/Analysis/LoopInfo.h"
Dan Gohman61ffa8e2009-06-16 19:52:01 +000073#include "llvm/Analysis/ValueTracking.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000074#include "llvm/Assembly/Writer.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000075#include "llvm/Target/TargetData.h"
Chris Lattner95255282006-06-28 23:17:24 +000076#include "llvm/Support/CommandLine.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000077#include "llvm/Support/ConstantRange.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000078#include "llvm/Support/ErrorHandling.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000079#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000080#include "llvm/Support/InstIterator.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000081#include "llvm/Support/MathExtras.h"
Dan Gohmanb7ef7292009-04-21 00:47:46 +000082#include "llvm/Support/raw_ostream.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000083#include "llvm/ADT/Statistic.h"
Dan Gohman2d1be872009-04-16 03:18:22 +000084#include "llvm/ADT/STLExtras.h"
Dan Gohman59ae6b92009-07-08 19:23:34 +000085#include "llvm/ADT/SmallPtrSet.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000086#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000087using namespace llvm;
88
Chris Lattner3b27d682006-12-19 22:30:33 +000089STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
97
Dan Gohman844731a2008-05-13 00:00:25 +000098static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +000099MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman64a845e2009-06-24 04:48:43 +0000101 "symbolically execute a constant "
102 "derived loop"),
Chris Lattner3b27d682006-12-19 22:30:33 +0000103 cl::init(100));
104
Dan Gohman844731a2008-05-13 00:00:25 +0000105static RegisterPass<ScalarEvolution>
106R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000107char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000108
109//===----------------------------------------------------------------------===//
110// SCEV class definitions
111//===----------------------------------------------------------------------===//
112
113//===----------------------------------------------------------------------===//
114// Implementation of the SCEV class.
115//
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000116
Chris Lattner53e677a2004-04-02 20:23:17 +0000117SCEV::~SCEV() {}
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000118
Chris Lattner53e677a2004-04-02 20:23:17 +0000119void SCEV::dump() const {
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000120 print(errs());
121 errs() << '\n';
122}
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
Dan Gohman4d289bf2009-06-24 00:30:26 +0000136bool SCEV::isAllOnesValue() const {
137 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
138 return SC->getValue()->isAllOnesValue();
139 return false;
140}
141
Owen Anderson753ad612009-06-22 21:57:23 +0000142SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohmanc050fd92009-07-13 20:50:19 +0000143 SCEV(FoldingSetNodeID(), scCouldNotCompute) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000144
Chris Lattner53e677a2004-04-02 20:23:17 +0000145bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000146 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000147 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000148}
149
150const Type *SCEVCouldNotCompute::getType() const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000151 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000152 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000153}
154
155bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
Torok Edwinc23197a2009-07-14 16:55:14 +0000156 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000157 return false;
158}
159
Dan Gohmanfef8bb22009-07-25 01:13:03 +0000160bool SCEVCouldNotCompute::hasOperand(const SCEV *) const {
161 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
162 return false;
Chris Lattner4dc534c2005-02-13 04:37:18 +0000163}
164
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000165void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000166 OS << "***COULDNOTCOMPUTE***";
167}
168
169bool SCEVCouldNotCompute::classof(const SCEV *S) {
170 return S->getSCEVType() == scCouldNotCompute;
171}
172
Dan Gohman0bba49c2009-07-07 17:06:11 +0000173const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohman1c343752009-06-27 21:21:31 +0000174 FoldingSetNodeID ID;
175 ID.AddInteger(scConstant);
176 ID.AddPointer(V);
177 void *IP = 0;
178 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
179 SCEV *S = SCEVAllocator.Allocate<SCEVConstant>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000180 new (S) SCEVConstant(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +0000181 UniqueSCEVs.InsertNode(S, IP);
182 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000183}
Chris Lattner53e677a2004-04-02 20:23:17 +0000184
Dan Gohman0bba49c2009-07-07 17:06:11 +0000185const SCEV *ScalarEvolution::getConstant(const APInt& Val) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000186 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000187}
188
Dan Gohman0bba49c2009-07-07 17:06:11 +0000189const SCEV *
Dan Gohman6de29f82009-06-15 22:12:54 +0000190ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000191 return getConstant(
Owen Andersoneed707b2009-07-24 23:12:02 +0000192 ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
Dan Gohman6de29f82009-06-15 22:12:54 +0000193}
194
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000195const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000196
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000197void SCEVConstant::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000198 WriteAsOperand(OS, V, false);
199}
Chris Lattner53e677a2004-04-02 20:23:17 +0000200
Dan Gohmanc050fd92009-07-13 20:50:19 +0000201SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeID &ID,
202 unsigned SCEVTy, const SCEV *op, const Type *ty)
203 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohman1c343752009-06-27 21:21:31 +0000204
Dan Gohman84923602009-04-21 01:25:57 +0000205bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
206 return Op->dominates(BB, DT);
207}
208
Dan Gohman6e70e312009-09-27 15:26:03 +0000209bool SCEVCastExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
210 return Op->properlyDominates(BB, DT);
211}
212
Dan Gohmanc050fd92009-07-13 20:50:19 +0000213SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeID &ID,
214 const SCEV *op, const Type *ty)
215 : SCEVCastExpr(ID, scTruncate, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000216 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
217 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000218 "Cannot truncate non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219}
Chris Lattner53e677a2004-04-02 20:23:17 +0000220
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000221void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000222 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000223}
224
Dan Gohmanc050fd92009-07-13 20:50:19 +0000225SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeID &ID,
226 const SCEV *op, const Type *ty)
227 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000228 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
229 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000230 "Cannot zero extend non-integer value!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000231}
232
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000233void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000234 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000235}
236
Dan Gohmanc050fd92009-07-13 20:50:19 +0000237SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeID &ID,
238 const SCEV *op, const Type *ty)
239 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +0000240 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
241 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmand19534a2007-06-15 14:38:12 +0000242 "Cannot sign extend non-integer value!");
Dan Gohmand19534a2007-06-15 14:38:12 +0000243}
244
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000245void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohman36b8e532009-04-29 20:27:52 +0000246 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmand19534a2007-06-15 14:38:12 +0000247}
248
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000249void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000250 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
251 const char *OpStr = getOperationStr();
252 OS << "(" << *Operands[0];
253 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
254 OS << OpStr << *Operands[i];
255 OS << ")";
256}
257
Dan Gohmanecb403a2009-05-07 14:00:19 +0000258bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000259 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
260 if (!getOperand(i)->dominates(BB, DT))
261 return false;
262 }
263 return true;
264}
265
Dan Gohman6e70e312009-09-27 15:26:03 +0000266bool SCEVNAryExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
267 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
268 if (!getOperand(i)->properlyDominates(BB, DT))
269 return false;
270 }
271 return true;
272}
273
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000274bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
275 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
276}
277
Dan Gohman6e70e312009-09-27 15:26:03 +0000278bool SCEVUDivExpr::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
279 return LHS->properlyDominates(BB, DT) && RHS->properlyDominates(BB, DT);
280}
281
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000282void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000283 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000284}
285
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000286const Type *SCEVUDivExpr::getType() const {
Dan Gohman91bb61a2009-05-26 17:44:05 +0000287 // In most cases the types of LHS and RHS will be the same, but in some
288 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
289 // depend on the type for correctness, but handling types carefully can
290 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
291 // a pointer type than the RHS, so use the RHS' type here.
292 return RHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000293}
294
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000295bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
Dan Gohmana3035a62009-05-20 01:01:24 +0000296 // Add recurrences are never invariant in the function-body (null loop).
Dan Gohmane890eea2009-06-26 22:17:21 +0000297 if (!QueryLoop)
298 return false;
299
300 // This recurrence is variant w.r.t. QueryLoop if QueryLoop contains L.
Dan Gohman92329c72009-12-18 01:24:09 +0000301 if (QueryLoop->contains(L))
Dan Gohmane890eea2009-06-26 22:17:21 +0000302 return false;
303
304 // This recurrence is variant w.r.t. QueryLoop if any of its operands
305 // are variant.
306 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
307 if (!getOperand(i)->isLoopInvariant(QueryLoop))
308 return false;
309
310 // Otherwise it's loop-invariant.
311 return true;
Chris Lattner53e677a2004-04-02 20:23:17 +0000312}
313
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000314void SCEVAddRecExpr::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000315 OS << "{" << *Operands[0];
316 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
317 OS << ",+," << *Operands[i];
318 OS << "}<" << L->getHeader()->getName() + ">";
319}
Chris Lattner53e677a2004-04-02 20:23:17 +0000320
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000321void SCEVFieldOffsetExpr::print(raw_ostream &OS) const {
322 // LLVM struct fields don't have names, so just print the field number.
323 OS << "offsetof(" << *STy << ", " << FieldNo << ")";
324}
325
326void SCEVAllocSizeExpr::print(raw_ostream &OS) const {
327 OS << "sizeof(" << *AllocTy << ")";
328}
329
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000330bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
331 // All non-instruction values are loop invariant. All instructions are loop
332 // invariant if they are not contained in the specified loop.
Dan Gohmana3035a62009-05-20 01:01:24 +0000333 // Instructions are never considered invariant in the function body
334 // (null loop) because they are defined within the "loop".
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000335 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman92329c72009-12-18 01:24:09 +0000336 return L && !L->contains(I);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000337 return true;
338}
Chris Lattner53e677a2004-04-02 20:23:17 +0000339
Evan Cheng5a6c1a82009-02-17 00:13:06 +0000340bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
341 if (Instruction *I = dyn_cast<Instruction>(getValue()))
342 return DT->dominates(I->getParent(), BB);
343 return true;
344}
345
Dan Gohman6e70e312009-09-27 15:26:03 +0000346bool SCEVUnknown::properlyDominates(BasicBlock *BB, DominatorTree *DT) const {
347 if (Instruction *I = dyn_cast<Instruction>(getValue()))
348 return DT->properlyDominates(I->getParent(), BB);
349 return true;
350}
351
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000352const Type *SCEVUnknown::getType() const {
353 return V->getType();
354}
Chris Lattner53e677a2004-04-02 20:23:17 +0000355
Dan Gohmanb7ef7292009-04-21 00:47:46 +0000356void SCEVUnknown::print(raw_ostream &OS) const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000357 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000358}
359
Chris Lattner8d741b82004-06-20 06:23:15 +0000360//===----------------------------------------------------------------------===//
361// SCEV Utilities
362//===----------------------------------------------------------------------===//
363
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000364static bool CompareTypes(const Type *A, const Type *B) {
365 if (A->getTypeID() != B->getTypeID())
366 return A->getTypeID() < B->getTypeID();
367 if (const IntegerType *AI = dyn_cast<IntegerType>(A)) {
368 const IntegerType *BI = cast<IntegerType>(B);
369 return AI->getBitWidth() < BI->getBitWidth();
370 }
371 if (const PointerType *AI = dyn_cast<PointerType>(A)) {
372 const PointerType *BI = cast<PointerType>(B);
373 return CompareTypes(AI->getElementType(), BI->getElementType());
374 }
375 if (const ArrayType *AI = dyn_cast<ArrayType>(A)) {
376 const ArrayType *BI = cast<ArrayType>(B);
377 if (AI->getNumElements() != BI->getNumElements())
378 return AI->getNumElements() < BI->getNumElements();
379 return CompareTypes(AI->getElementType(), BI->getElementType());
380 }
381 if (const VectorType *AI = dyn_cast<VectorType>(A)) {
382 const VectorType *BI = cast<VectorType>(B);
383 if (AI->getNumElements() != BI->getNumElements())
384 return AI->getNumElements() < BI->getNumElements();
385 return CompareTypes(AI->getElementType(), BI->getElementType());
386 }
387 if (const StructType *AI = dyn_cast<StructType>(A)) {
388 const StructType *BI = cast<StructType>(B);
389 if (AI->getNumElements() != BI->getNumElements())
390 return AI->getNumElements() < BI->getNumElements();
391 for (unsigned i = 0, e = AI->getNumElements(); i != e; ++i)
392 if (CompareTypes(AI->getElementType(i), BI->getElementType(i)) ||
393 CompareTypes(BI->getElementType(i), AI->getElementType(i)))
394 return CompareTypes(AI->getElementType(i), BI->getElementType(i));
395 }
396 return false;
397}
398
Chris Lattner8d741b82004-06-20 06:23:15 +0000399namespace {
400 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
401 /// than the complexity of the RHS. This comparator is used to canonicalize
402 /// expressions.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000403 class SCEVComplexityCompare {
Dan Gohman72861302009-05-07 14:39:04 +0000404 LoopInfo *LI;
405 public:
406 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
407
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000408 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman42214892009-08-31 21:15:23 +0000409 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
410 if (LHS == RHS)
411 return false;
412
Dan Gohman72861302009-05-07 14:39:04 +0000413 // Primarily, sort the SCEVs by their getSCEVType().
414 if (LHS->getSCEVType() != RHS->getSCEVType())
415 return LHS->getSCEVType() < RHS->getSCEVType();
416
417 // Aside from the getSCEVType() ordering, the particular ordering
418 // isn't very important except that it's beneficial to be consistent,
419 // so that (a + b) and (b + a) don't end up as different expressions.
420
421 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
422 // not as complete as it could be.
423 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
424 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
425
Dan Gohman5be18e82009-05-19 02:15:55 +0000426 // Order pointer values after integer values. This helps SCEVExpander
427 // form GEPs.
428 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
429 return false;
430 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
431 return true;
432
Dan Gohman72861302009-05-07 14:39:04 +0000433 // Compare getValueID values.
434 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
435 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
436
437 // Sort arguments by their position.
438 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
439 const Argument *RA = cast<Argument>(RU->getValue());
440 return LA->getArgNo() < RA->getArgNo();
441 }
442
443 // For instructions, compare their loop depth, and their opcode.
444 // This is pretty loose.
445 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
446 Instruction *RV = cast<Instruction>(RU->getValue());
447
448 // Compare loop depths.
449 if (LI->getLoopDepth(LV->getParent()) !=
450 LI->getLoopDepth(RV->getParent()))
451 return LI->getLoopDepth(LV->getParent()) <
452 LI->getLoopDepth(RV->getParent());
453
454 // Compare opcodes.
455 if (LV->getOpcode() != RV->getOpcode())
456 return LV->getOpcode() < RV->getOpcode();
457
458 // Compare the number of operands.
459 if (LV->getNumOperands() != RV->getNumOperands())
460 return LV->getNumOperands() < RV->getNumOperands();
461 }
462
463 return false;
464 }
465
Dan Gohman4dfad292009-06-14 22:51:25 +0000466 // Compare constant values.
467 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
468 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Nick Lewyckyd1ec9892009-07-04 17:24:52 +0000469 if (LC->getValue()->getBitWidth() != RC->getValue()->getBitWidth())
470 return LC->getValue()->getBitWidth() < RC->getValue()->getBitWidth();
Dan Gohman4dfad292009-06-14 22:51:25 +0000471 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
472 }
473
474 // Compare addrec loop depths.
475 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
476 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
477 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
478 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
479 }
Dan Gohman72861302009-05-07 14:39:04 +0000480
481 // Lexicographically compare n-ary expressions.
482 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
483 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
484 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
485 if (i >= RC->getNumOperands())
486 return false;
487 if (operator()(LC->getOperand(i), RC->getOperand(i)))
488 return true;
489 if (operator()(RC->getOperand(i), LC->getOperand(i)))
490 return false;
491 }
492 return LC->getNumOperands() < RC->getNumOperands();
493 }
494
Dan Gohmana6b35e22009-05-07 19:23:21 +0000495 // Lexicographically compare udiv expressions.
496 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
497 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
498 if (operator()(LC->getLHS(), RC->getLHS()))
499 return true;
500 if (operator()(RC->getLHS(), LC->getLHS()))
501 return false;
502 if (operator()(LC->getRHS(), RC->getRHS()))
503 return true;
504 if (operator()(RC->getRHS(), LC->getRHS()))
505 return false;
506 return false;
507 }
508
Dan Gohman72861302009-05-07 14:39:04 +0000509 // Compare cast expressions by operand.
510 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
511 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
512 return operator()(LC->getOperand(), RC->getOperand());
513 }
514
Dan Gohmanc40f17b2009-08-18 16:46:41 +0000515 // Compare offsetof expressions.
516 if (const SCEVFieldOffsetExpr *LA = dyn_cast<SCEVFieldOffsetExpr>(LHS)) {
517 const SCEVFieldOffsetExpr *RA = cast<SCEVFieldOffsetExpr>(RHS);
518 if (CompareTypes(LA->getStructType(), RA->getStructType()) ||
519 CompareTypes(RA->getStructType(), LA->getStructType()))
520 return CompareTypes(LA->getStructType(), RA->getStructType());
521 return LA->getFieldNo() < RA->getFieldNo();
522 }
523
524 // Compare sizeof expressions by the allocation type.
525 if (const SCEVAllocSizeExpr *LA = dyn_cast<SCEVAllocSizeExpr>(LHS)) {
526 const SCEVAllocSizeExpr *RA = cast<SCEVAllocSizeExpr>(RHS);
527 return CompareTypes(LA->getAllocType(), RA->getAllocType());
528 }
529
Torok Edwinc23197a2009-07-14 16:55:14 +0000530 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman72861302009-05-07 14:39:04 +0000531 return false;
Chris Lattner8d741b82004-06-20 06:23:15 +0000532 }
533 };
534}
535
536/// GroupByComplexity - Given a list of SCEV objects, order them by their
537/// complexity, and group objects of the same complexity together by value.
538/// When this routine is finished, we know that any duplicates in the vector are
539/// consecutive and that complexity is monotonically increasing.
540///
541/// Note that we go take special precautions to ensure that we get determinstic
542/// results from this routine. In other words, we don't want the results of
543/// this to depend on where the addresses of various SCEV objects happened to
544/// land in memory.
545///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000546static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman72861302009-05-07 14:39:04 +0000547 LoopInfo *LI) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000548 if (Ops.size() < 2) return; // Noop
549 if (Ops.size() == 2) {
550 // This is the common case, which also happens to be trivially simple.
551 // Special case it.
Dan Gohman72861302009-05-07 14:39:04 +0000552 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000553 std::swap(Ops[0], Ops[1]);
554 return;
555 }
556
557 // Do the rough sort by complexity.
Dan Gohman72861302009-05-07 14:39:04 +0000558 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Chris Lattner8d741b82004-06-20 06:23:15 +0000559
560 // Now that we are sorted by complexity, group elements of the same
561 // complexity. Note that this is, at worst, N^2, but the vector is likely to
562 // be extremely short in practice. Note that we take this approach because we
563 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000564 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohman35738ac2009-05-04 22:30:44 +0000565 const SCEV *S = Ops[i];
Chris Lattner8d741b82004-06-20 06:23:15 +0000566 unsigned Complexity = S->getSCEVType();
567
568 // If there are any objects of the same complexity and same value as this
569 // one, group them.
570 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
571 if (Ops[j] == S) { // Found a duplicate.
572 // Move it to immediately after i'th element.
573 std::swap(Ops[i+1], Ops[j]);
574 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000575 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000576 }
577 }
578 }
579}
580
Chris Lattner53e677a2004-04-02 20:23:17 +0000581
Chris Lattner53e677a2004-04-02 20:23:17 +0000582
583//===----------------------------------------------------------------------===//
584// Simple SCEV method implementations
585//===----------------------------------------------------------------------===//
586
Eli Friedmanb42a6262008-08-04 23:49:06 +0000587/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman6c0866c2009-05-24 23:45:28 +0000588/// Assume, K > 0.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000589static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000590 ScalarEvolution &SE,
591 const Type* ResultTy) {
Eli Friedmanb42a6262008-08-04 23:49:06 +0000592 // Handle the simplest case efficiently.
593 if (K == 1)
594 return SE.getTruncateOrZeroExtend(It, ResultTy);
595
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000596 // We are using the following formula for BC(It, K):
597 //
598 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
599 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000600 // Suppose, W is the bitwidth of the return value. We must be prepared for
601 // overflow. Hence, we must assure that the result of our computation is
602 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
603 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000604 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000605 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman64a845e2009-06-24 04:48:43 +0000606 // is something like the following, where T is the number of factors of 2 in
Eli Friedmanb42a6262008-08-04 23:49:06 +0000607 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
608 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000609 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000610 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000611 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000612 // This formula is trivially equivalent to the previous formula. However,
613 // this formula can be implemented much more efficiently. The trick is that
614 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
615 // arithmetic. To do exact division in modular arithmetic, all we have
616 // to do is multiply by the inverse. Therefore, this step can be done at
617 // width W.
Dan Gohman64a845e2009-06-24 04:48:43 +0000618 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000619 // The next issue is how to safely do the division by 2^T. The way this
620 // is done is by doing the multiplication step at a width of at least W + T
621 // bits. This way, the bottom W+T bits of the product are accurate. Then,
622 // when we perform the division by 2^T (which is equivalent to a right shift
623 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
624 // truncated out after the division by 2^T.
625 //
626 // In comparison to just directly using the first formula, this technique
627 // is much more efficient; using the first formula requires W * K bits,
628 // but this formula less than W + K bits. Also, the first formula requires
629 // a division step, whereas this formula only requires multiplies and shifts.
630 //
631 // It doesn't matter whether the subtraction step is done in the calculation
632 // width or the input iteration count's width; if the subtraction overflows,
633 // the result must be zero anyway. We prefer here to do it in the width of
634 // the induction variable because it helps a lot for certain cases; CodeGen
635 // isn't smart enough to ignore the overflow, which leads to much less
636 // efficient code if the width of the subtraction is wider than the native
637 // register width.
638 //
639 // (It's possible to not widen at all by pulling out factors of 2 before
640 // the multiplication; for example, K=2 can be calculated as
641 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
642 // extra arithmetic, so it's not an obvious win, and it gets
643 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000644
Eli Friedmanb42a6262008-08-04 23:49:06 +0000645 // Protection from insane SCEVs; this bound is conservative,
646 // but it probably doesn't matter.
647 if (K > 1000)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +0000648 return SE.getCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000649
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000650 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000651
Eli Friedmanb42a6262008-08-04 23:49:06 +0000652 // Calculate K! / 2^T and T; we divide out the factors of two before
653 // multiplying for calculating K! / 2^T to avoid overflow.
654 // Other overflow doesn't matter because we only care about the bottom
655 // W bits of the result.
656 APInt OddFactorial(W, 1);
657 unsigned T = 1;
658 for (unsigned i = 3; i <= K; ++i) {
659 APInt Mult(W, i);
660 unsigned TwoFactors = Mult.countTrailingZeros();
661 T += TwoFactors;
662 Mult = Mult.lshr(TwoFactors);
663 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000664 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000665
Eli Friedmanb42a6262008-08-04 23:49:06 +0000666 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000667 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000668
669 // Calcuate 2^T, at width T+W.
670 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
671
672 // Calculate the multiplicative inverse of K! / 2^T;
673 // this multiplication factor will perform the exact division by
674 // K! / 2^T.
675 APInt Mod = APInt::getSignedMinValue(W+1);
676 APInt MultiplyFactor = OddFactorial.zext(W+1);
677 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
678 MultiplyFactor = MultiplyFactor.trunc(W);
679
680 // Calculate the product, at width T+W
Owen Anderson1d0be152009-08-13 21:58:54 +0000681 const IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
682 CalculationBits);
Dan Gohman0bba49c2009-07-07 17:06:11 +0000683 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedmanb42a6262008-08-04 23:49:06 +0000684 for (unsigned i = 1; i != K; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000685 const SCEV *S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000686 Dividend = SE.getMulExpr(Dividend,
687 SE.getTruncateOrZeroExtend(S, CalculationTy));
688 }
689
690 // Divide by 2^T
Dan Gohman0bba49c2009-07-07 17:06:11 +0000691 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedmanb42a6262008-08-04 23:49:06 +0000692
693 // Truncate the result, and divide by K! / 2^T.
694
695 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
696 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000697}
698
Chris Lattner53e677a2004-04-02 20:23:17 +0000699/// evaluateAtIteration - Return the value of this chain of recurrences at
700/// the specified iteration number. We can evaluate this recurrence by
701/// multiplying each element in the chain by the binomial coefficient
702/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
703///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000704/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000705///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000706/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000707///
Dan Gohman0bba49c2009-07-07 17:06:11 +0000708const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohmanc2b015e2009-07-21 00:38:55 +0000709 ScalarEvolution &SE) const {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000710 const SCEV *Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000711 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000712 // The computation is correct in the face of overflow provided that the
713 // multiplication is performed _after_ the evaluation of the binomial
714 // coefficient.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000715 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000716 if (isa<SCEVCouldNotCompute>(Coeff))
717 return Coeff;
718
719 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000720 }
721 return Result;
722}
723
Chris Lattner53e677a2004-04-02 20:23:17 +0000724//===----------------------------------------------------------------------===//
725// SCEV Expression folder implementations
726//===----------------------------------------------------------------------===//
727
Dan Gohman0bba49c2009-07-07 17:06:11 +0000728const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000729 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000730 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000731 "This is not a truncating conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000732 assert(isSCEVable(Ty) &&
733 "This is not a conversion to a SCEVable type!");
734 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000735
Dan Gohmanc050fd92009-07-13 20:50:19 +0000736 FoldingSetNodeID ID;
737 ID.AddInteger(scTruncate);
738 ID.AddPointer(Op);
739 ID.AddPointer(Ty);
740 void *IP = 0;
741 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
742
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000743 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000744 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000745 return getConstant(
746 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000747
Dan Gohman20900ca2009-04-22 16:20:48 +0000748 // trunc(trunc(x)) --> trunc(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000749 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000750 return getTruncateExpr(ST->getOperand(), Ty);
751
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000752 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000753 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000754 return getTruncateOrSignExtend(SS->getOperand(), Ty);
755
756 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohman622ed672009-05-04 22:02:23 +0000757 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky5cd28fa2009-04-23 05:15:08 +0000758 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
759
Dan Gohman6864db62009-06-18 16:24:47 +0000760 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohman622ed672009-05-04 22:02:23 +0000761 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +0000762 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +0000763 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman728c7f32009-05-08 21:03:19 +0000764 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
765 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000766 }
767
Dan Gohmanc050fd92009-07-13 20:50:19 +0000768 // The cast wasn't folded; create an explicit cast node.
769 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000770 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
771 SCEV *S = SCEVAllocator.Allocate<SCEVTruncateExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000772 new (S) SCEVTruncateExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000773 UniqueSCEVs.InsertNode(S, IP);
774 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000775}
776
Dan Gohman0bba49c2009-07-07 17:06:11 +0000777const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000778 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000779 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman8170a682009-04-16 19:25:55 +0000780 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000781 assert(isSCEVable(Ty) &&
782 "This is not a conversion to a SCEVable type!");
783 Ty = getEffectiveSCEVType(Ty);
Dan Gohman8170a682009-04-16 19:25:55 +0000784
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000785 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000786 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000787 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000788 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
789 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000790 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000791 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000792
Dan Gohman20900ca2009-04-22 16:20:48 +0000793 // zext(zext(x)) --> zext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000794 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000795 return getZeroExtendExpr(SZ->getOperand(), Ty);
796
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000797 // Before doing any expensive analysis, check to see if we've already
798 // computed a SCEV for this Op and Ty.
799 FoldingSetNodeID ID;
800 ID.AddInteger(scZeroExtend);
801 ID.AddPointer(Op);
802 ID.AddPointer(Ty);
803 void *IP = 0;
804 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
805
Dan Gohman01ecca22009-04-27 20:16:15 +0000806 // If the input value is a chrec scev, and we can prove that the value
Chris Lattner53e677a2004-04-02 20:23:17 +0000807 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000808 // operands (often constants). This allows analysis of something like
Chris Lattner53e677a2004-04-02 20:23:17 +0000809 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000810 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000811 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000812 const SCEV *Start = AR->getStart();
813 const SCEV *Step = AR->getStepRecurrence(*this);
814 unsigned BitWidth = getTypeSizeInBits(AR->getType());
815 const Loop *L = AR->getLoop();
816
Dan Gohmaneb490a72009-07-25 01:22:26 +0000817 // If we have special knowledge that this addrec won't overflow,
818 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000819 if (AR->hasNoUnsignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000820 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
821 getZeroExtendExpr(Step, Ty),
822 L);
823
Dan Gohman01ecca22009-04-27 20:16:15 +0000824 // Check whether the backedge-taken count is SCEVCouldNotCompute.
825 // Note that this serves two purposes: It filters out loops that are
826 // simply not analyzable, and it covers the case where this code is
827 // being called from within backedge-taken count analysis, such that
828 // attempting to ask for the backedge-taken count would likely result
829 // in infinite recursion. In the later case, the analysis code will
830 // cope with a conservative value, and it will take care to purge
831 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000832 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000833 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000834 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000835 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000836
837 // Check whether the backedge-taken count can be losslessly casted to
838 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000839 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000840 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000841 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000842 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
843 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000844 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000845 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000846 const SCEV *ZMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000847 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000848 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000849 const SCEV *Add = getAddExpr(Start, ZMul);
850 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000851 getAddExpr(getZeroExtendExpr(Start, WideTy),
852 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
853 getZeroExtendExpr(Step, WideTy)));
854 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000855 // Return the expression with the addrec on the outside.
856 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
857 getZeroExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000858 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000859
860 // Similar to above, only this time treat the step value as signed.
861 // This covers loops that count down.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000862 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000863 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000864 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohmanac70cea2009-04-29 22:28:28 +0000865 Add = getAddExpr(Start, SMul);
Dan Gohman5183cae2009-05-18 15:58:39 +0000866 OperandExtendedAdd =
867 getAddExpr(getZeroExtendExpr(Start, WideTy),
868 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
869 getSignExtendExpr(Step, WideTy)));
870 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000871 // Return the expression with the addrec on the outside.
872 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
873 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000874 L);
875 }
876
877 // If the backedge is guarded by a comparison with the pre-inc value
878 // the addrec is safe. Also, if the entry is guarded by a comparison
879 // with the start value and the backedge is guarded by a comparison
880 // with the post-inc value, the addrec is safe.
881 if (isKnownPositive(Step)) {
882 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
883 getUnsignedRange(Step).getUnsignedMax());
884 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
885 (isLoopGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
886 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
887 AR->getPostIncExpr(*this), N)))
888 // Return the expression with the addrec on the outside.
889 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
890 getZeroExtendExpr(Step, Ty),
891 L);
892 } else if (isKnownNegative(Step)) {
893 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
894 getSignedRange(Step).getSignedMin());
895 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) &&
896 (isLoopGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) ||
897 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
898 AR->getPostIncExpr(*this), N)))
899 // Return the expression with the addrec on the outside.
900 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
901 getSignExtendExpr(Step, Ty),
902 L);
Dan Gohman01ecca22009-04-27 20:16:15 +0000903 }
904 }
905 }
Chris Lattner53e677a2004-04-02 20:23:17 +0000906
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000907 // The cast wasn't folded; create an explicit cast node.
908 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +0000909 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
910 SCEV *S = SCEVAllocator.Allocate<SCEVZeroExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +0000911 new (S) SCEVZeroExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +0000912 UniqueSCEVs.InsertNode(S, IP);
913 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +0000914}
915
Dan Gohman0bba49c2009-07-07 17:06:11 +0000916const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Dan Gohmanf5074ec2009-07-13 22:05:32 +0000917 const Type *Ty) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000918 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000919 "This is not an extending conversion!");
Dan Gohman10b94792009-05-01 16:44:18 +0000920 assert(isSCEVable(Ty) &&
921 "This is not a conversion to a SCEVable type!");
922 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanfb17fd22009-04-21 00:55:22 +0000923
Dan Gohmanc39f44b2009-06-30 20:13:32 +0000924 // Fold if the operand is constant.
Dan Gohman622ed672009-05-04 22:02:23 +0000925 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +0000926 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +0000927 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
928 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohmanb8be8b72009-06-24 00:38:39 +0000929 return getConstant(cast<ConstantInt>(C));
Dan Gohman2d1be872009-04-16 03:18:22 +0000930 }
Dan Gohmand19534a2007-06-15 14:38:12 +0000931
Dan Gohman20900ca2009-04-22 16:20:48 +0000932 // sext(sext(x)) --> sext(x)
Dan Gohman622ed672009-05-04 22:02:23 +0000933 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman20900ca2009-04-22 16:20:48 +0000934 return getSignExtendExpr(SS->getOperand(), Ty);
935
Dan Gohman69fbc7f2009-07-13 20:55:53 +0000936 // Before doing any expensive analysis, check to see if we've already
937 // computed a SCEV for this Op and Ty.
938 FoldingSetNodeID ID;
939 ID.AddInteger(scSignExtend);
940 ID.AddPointer(Op);
941 ID.AddPointer(Ty);
942 void *IP = 0;
943 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
944
Dan Gohman01ecca22009-04-27 20:16:15 +0000945 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmand19534a2007-06-15 14:38:12 +0000946 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman01ecca22009-04-27 20:16:15 +0000947 // operands (often constants). This allows analysis of something like
Dan Gohmand19534a2007-06-15 14:38:12 +0000948 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohman622ed672009-05-04 22:02:23 +0000949 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman01ecca22009-04-27 20:16:15 +0000950 if (AR->isAffine()) {
Dan Gohman85b05a22009-07-13 21:35:55 +0000951 const SCEV *Start = AR->getStart();
952 const SCEV *Step = AR->getStepRecurrence(*this);
953 unsigned BitWidth = getTypeSizeInBits(AR->getType());
954 const Loop *L = AR->getLoop();
955
Dan Gohmaneb490a72009-07-25 01:22:26 +0000956 // If we have special knowledge that this addrec won't overflow,
957 // we don't need to do any further analysis.
Dan Gohman5078f842009-08-20 17:11:38 +0000958 if (AR->hasNoSignedWrap())
Dan Gohmaneb490a72009-07-25 01:22:26 +0000959 return getAddRecExpr(getSignExtendExpr(Start, Ty),
960 getSignExtendExpr(Step, Ty),
961 L);
962
Dan Gohman01ecca22009-04-27 20:16:15 +0000963 // Check whether the backedge-taken count is SCEVCouldNotCompute.
964 // Note that this serves two purposes: It filters out loops that are
965 // simply not analyzable, and it covers the case where this code is
966 // being called from within backedge-taken count analysis, such that
967 // attempting to ask for the backedge-taken count would likely result
968 // in infinite recursion. In the later case, the analysis code will
969 // cope with a conservative value, and it will take care to purge
970 // that value once it has finished.
Dan Gohman85b05a22009-07-13 21:35:55 +0000971 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohmana1af7572009-04-30 20:47:05 +0000972 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohmanf0aa4852009-04-29 01:54:20 +0000973 // Manually compute the final value for AR, checking for
Dan Gohmanac70cea2009-04-29 22:28:28 +0000974 // overflow.
Dan Gohman01ecca22009-04-27 20:16:15 +0000975
976 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohmanac70cea2009-04-29 22:28:28 +0000977 // the addrec's type. The count is always unsigned.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000978 const SCEV *CastedMaxBECount =
Dan Gohmana1af7572009-04-30 20:47:05 +0000979 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +0000980 const SCEV *RecastedMaxBECount =
Dan Gohman5183cae2009-05-18 15:58:39 +0000981 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
982 if (MaxBECount == RecastedMaxBECount) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000983 const Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohmana1af7572009-04-30 20:47:05 +0000984 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman0bba49c2009-07-07 17:06:11 +0000985 const SCEV *SMul =
Dan Gohmana1af7572009-04-30 20:47:05 +0000986 getMulExpr(CastedMaxBECount,
Dan Gohman01ecca22009-04-27 20:16:15 +0000987 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman0bba49c2009-07-07 17:06:11 +0000988 const SCEV *Add = getAddExpr(Start, SMul);
989 const SCEV *OperandExtendedAdd =
Dan Gohman5183cae2009-05-18 15:58:39 +0000990 getAddExpr(getSignExtendExpr(Start, WideTy),
991 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
992 getSignExtendExpr(Step, WideTy)));
993 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohmanac70cea2009-04-29 22:28:28 +0000994 // Return the expression with the addrec on the outside.
995 return getAddRecExpr(getSignExtendExpr(Start, Ty),
996 getSignExtendExpr(Step, Ty),
Dan Gohman85b05a22009-07-13 21:35:55 +0000997 L);
Dan Gohman850f7912009-07-16 17:34:36 +0000998
999 // Similar to above, only this time treat the step value as unsigned.
1000 // This covers loops that count up with an unsigned step.
1001 const SCEV *UMul =
1002 getMulExpr(CastedMaxBECount,
1003 getTruncateOrZeroExtend(Step, Start->getType()));
1004 Add = getAddExpr(Start, UMul);
1005 OperandExtendedAdd =
Dan Gohman19378d62009-07-25 16:03:30 +00001006 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohman850f7912009-07-16 17:34:36 +00001007 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
1008 getZeroExtendExpr(Step, WideTy)));
Dan Gohman19378d62009-07-25 16:03:30 +00001009 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman850f7912009-07-16 17:34:36 +00001010 // Return the expression with the addrec on the outside.
1011 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1012 getZeroExtendExpr(Step, Ty),
1013 L);
Dan Gohman85b05a22009-07-13 21:35:55 +00001014 }
1015
1016 // If the backedge is guarded by a comparison with the pre-inc value
1017 // the addrec is safe. Also, if the entry is guarded by a comparison
1018 // with the start value and the backedge is guarded by a comparison
1019 // with the post-inc value, the addrec is safe.
1020 if (isKnownPositive(Step)) {
1021 const SCEV *N = getConstant(APInt::getSignedMinValue(BitWidth) -
1022 getSignedRange(Step).getSignedMax());
1023 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT, AR, N) ||
1024 (isLoopGuardedByCond(L, ICmpInst::ICMP_SLT, Start, N) &&
1025 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SLT,
1026 AR->getPostIncExpr(*this), N)))
1027 // Return the expression with the addrec on the outside.
1028 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1029 getSignExtendExpr(Step, Ty),
1030 L);
1031 } else if (isKnownNegative(Step)) {
1032 const SCEV *N = getConstant(APInt::getSignedMaxValue(BitWidth) -
1033 getSignedRange(Step).getSignedMin());
1034 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT, AR, N) ||
1035 (isLoopGuardedByCond(L, ICmpInst::ICMP_SGT, Start, N) &&
1036 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_SGT,
1037 AR->getPostIncExpr(*this), N)))
1038 // Return the expression with the addrec on the outside.
1039 return getAddRecExpr(getSignExtendExpr(Start, Ty),
1040 getSignExtendExpr(Step, Ty),
1041 L);
Dan Gohman01ecca22009-04-27 20:16:15 +00001042 }
1043 }
1044 }
Dan Gohmand19534a2007-06-15 14:38:12 +00001045
Dan Gohman69fbc7f2009-07-13 20:55:53 +00001046 // The cast wasn't folded; create an explicit cast node.
1047 // Recompute the insert position, as it may have been invalidated.
Dan Gohman1c343752009-06-27 21:21:31 +00001048 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1049 SCEV *S = SCEVAllocator.Allocate<SCEVSignExtendExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001050 new (S) SCEVSignExtendExpr(ID, Op, Ty);
Dan Gohman1c343752009-06-27 21:21:31 +00001051 UniqueSCEVs.InsertNode(S, IP);
1052 return S;
Dan Gohmand19534a2007-06-15 14:38:12 +00001053}
1054
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001055/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1056/// unspecified bits out to the given type.
1057///
Dan Gohman0bba49c2009-07-07 17:06:11 +00001058const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Dan Gohmanc40f17b2009-08-18 16:46:41 +00001059 const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001060 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1061 "This is not an extending conversion!");
1062 assert(isSCEVable(Ty) &&
1063 "This is not a conversion to a SCEVable type!");
1064 Ty = getEffectiveSCEVType(Ty);
1065
1066 // Sign-extend negative constants.
1067 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1068 if (SC->getValue()->getValue().isNegative())
1069 return getSignExtendExpr(Op, Ty);
1070
1071 // Peel off a truncate cast.
1072 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001073 const SCEV *NewOp = T->getOperand();
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001074 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1075 return getAnyExtendExpr(NewOp, Ty);
1076 return getTruncateOrNoop(NewOp, Ty);
1077 }
1078
1079 // Next try a zext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001080 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001081 if (!isa<SCEVZeroExtendExpr>(ZExt))
1082 return ZExt;
1083
1084 // Next try a sext cast. If the cast is folded, use it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001085 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00001086 if (!isa<SCEVSignExtendExpr>(SExt))
1087 return SExt;
1088
1089 // If the expression is obviously signed, use the sext cast value.
1090 if (isa<SCEVSMaxExpr>(Op))
1091 return SExt;
1092
1093 // Absent any other information, use the zext cast value.
1094 return ZExt;
1095}
1096
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001097/// CollectAddOperandsWithScales - Process the given Ops list, which is
1098/// a list of operands to be added under the given scale, update the given
1099/// map. This is a helper function for getAddRecExpr. As an example of
1100/// what it does, given a sequence of operands that would form an add
1101/// expression like this:
1102///
1103/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
1104///
1105/// where A and B are constants, update the map with these values:
1106///
1107/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1108///
1109/// and add 13 + A*B*29 to AccumulatedConstant.
1110/// This will allow getAddRecExpr to produce this:
1111///
1112/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1113///
1114/// This form often exposes folding opportunities that are hidden in
1115/// the original operand list.
1116///
1117/// Return true iff it appears that any interesting folding opportunities
1118/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1119/// the common case where no interesting opportunities are present, and
1120/// is also used as a check to avoid infinite recursion.
1121///
1122static bool
Dan Gohman0bba49c2009-07-07 17:06:11 +00001123CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
1124 SmallVector<const SCEV *, 8> &NewOps,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001125 APInt &AccumulatedConstant,
Dan Gohman0bba49c2009-07-07 17:06:11 +00001126 const SmallVectorImpl<const SCEV *> &Ops,
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001127 const APInt &Scale,
1128 ScalarEvolution &SE) {
1129 bool Interesting = false;
1130
1131 // Iterate over the add operands.
1132 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1133 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1134 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1135 APInt NewScale =
1136 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1137 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1138 // A multiplication of a constant with another add; recurse.
1139 Interesting |=
1140 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1141 cast<SCEVAddExpr>(Mul->getOperand(1))
1142 ->getOperands(),
1143 NewScale, SE);
1144 } else {
1145 // A multiplication of a constant with some other value. Update
1146 // the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001147 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1148 const SCEV *Key = SE.getMulExpr(MulOps);
1149 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001150 M.insert(std::make_pair(Key, NewScale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001151 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001152 NewOps.push_back(Pair.first->first);
1153 } else {
1154 Pair.first->second += NewScale;
1155 // The map already had an entry for this value, which may indicate
1156 // a folding opportunity.
1157 Interesting = true;
1158 }
1159 }
1160 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1161 // Pull a buried constant out to the outside.
1162 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1163 Interesting = true;
1164 AccumulatedConstant += Scale * C->getValue()->getValue();
1165 } else {
1166 // An ordinary operand. Update the map.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001167 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohman23737e02009-06-29 18:25:52 +00001168 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001169 if (Pair.second) {
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001170 NewOps.push_back(Pair.first->first);
1171 } else {
1172 Pair.first->second += Scale;
1173 // The map already had an entry for this value, which may indicate
1174 // a folding opportunity.
1175 Interesting = true;
1176 }
1177 }
1178 }
1179
1180 return Interesting;
1181}
1182
1183namespace {
1184 struct APIntCompare {
1185 bool operator()(const APInt &LHS, const APInt &RHS) const {
1186 return LHS.ult(RHS);
1187 }
1188 };
1189}
1190
Dan Gohman6c0866c2009-05-24 23:45:28 +00001191/// getAddExpr - Get a canonical add expression, or something simpler if
1192/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001193const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1194 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001195 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +00001196 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001197#ifndef NDEBUG
1198 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1199 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1200 getEffectiveSCEVType(Ops[0]->getType()) &&
1201 "SCEVAddExpr operand types don't match!");
1202#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001203
1204 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001205 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001206
1207 // If there are any constants, fold them together.
1208 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001209 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001210 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +00001211 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001212 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001213 // We found two constants, fold them together!
Dan Gohmana82752c2009-06-14 22:47:23 +00001214 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1215 RHSC->getValue()->getValue());
Dan Gohman7f7c4362009-06-14 22:53:57 +00001216 if (Ops.size() == 2) return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00001217 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky3e630762008-02-20 06:48:22 +00001218 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001219 }
1220
1221 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +00001222 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001223 Ops.erase(Ops.begin());
1224 --Idx;
1225 }
1226 }
1227
Chris Lattner627018b2004-04-07 16:16:11 +00001228 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001229
Chris Lattner53e677a2004-04-02 20:23:17 +00001230 // Okay, check to see if the same value occurs in the operand list twice. If
1231 // so, merge them together into an multiply expression. Since we sorted the
1232 // list, these values are required to be adjacent.
1233 const Type *Ty = Ops[0]->getType();
1234 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1235 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1236 // Found a match, merge the two values into a multiply, and add any
1237 // remaining values to the result.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001238 const SCEV *Two = getIntegerSCEV(2, Ty);
1239 const SCEV *Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +00001240 if (Ops.size() == 2)
1241 return Mul;
1242 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1243 Ops.push_back(Mul);
Dan Gohman3645b012009-10-09 00:10:36 +00001244 return getAddExpr(Ops, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001245 }
1246
Dan Gohman728c7f32009-05-08 21:03:19 +00001247 // Check for truncates. If all the operands are truncated from the same
1248 // type, see if factoring out the truncate would permit the result to be
1249 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1250 // if the contents of the resulting outer trunc fold to something simple.
1251 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1252 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1253 const Type *DstType = Trunc->getType();
1254 const Type *SrcType = Trunc->getOperand()->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00001255 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001256 bool Ok = true;
1257 // Check all the operands to see if they can be represented in the
1258 // source type of the truncate.
1259 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1260 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1261 if (T->getOperand()->getType() != SrcType) {
1262 Ok = false;
1263 break;
1264 }
1265 LargeOps.push_back(T->getOperand());
1266 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1267 // This could be either sign or zero extension, but sign extension
1268 // is much more likely to be foldable here.
1269 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1270 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001271 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman728c7f32009-05-08 21:03:19 +00001272 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1273 if (const SCEVTruncateExpr *T =
1274 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1275 if (T->getOperand()->getType() != SrcType) {
1276 Ok = false;
1277 break;
1278 }
1279 LargeMulOps.push_back(T->getOperand());
1280 } else if (const SCEVConstant *C =
1281 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1282 // This could be either sign or zero extension, but sign extension
1283 // is much more likely to be foldable here.
1284 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1285 } else {
1286 Ok = false;
1287 break;
1288 }
1289 }
1290 if (Ok)
1291 LargeOps.push_back(getMulExpr(LargeMulOps));
1292 } else {
1293 Ok = false;
1294 break;
1295 }
1296 }
1297 if (Ok) {
1298 // Evaluate the expression in the larger type.
Dan Gohman3645b012009-10-09 00:10:36 +00001299 const SCEV *Fold = getAddExpr(LargeOps, HasNUW, HasNSW);
Dan Gohman728c7f32009-05-08 21:03:19 +00001300 // If it folds to something simple, use it. Otherwise, don't.
1301 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1302 return getTruncateExpr(Fold, DstType);
1303 }
1304 }
1305
1306 // Skip past any other cast SCEVs.
Dan Gohmanf50cd742007-06-18 19:30:09 +00001307 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1308 ++Idx;
1309
1310 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +00001311 if (Idx < Ops.size()) {
1312 bool DeletedAdd = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001313 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001314 // If we have an add, expand the add operands onto the end of the operands
1315 // list.
1316 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1317 Ops.erase(Ops.begin()+Idx);
1318 DeletedAdd = true;
1319 }
1320
1321 // If we deleted at least one add, we added operands to the end of the list,
1322 // and they are not necessarily sorted. Recurse to resort and resimplify
1323 // any operands we just aquired.
1324 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +00001325 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001326 }
1327
1328 // Skip over the add expression until we get to a multiply.
1329 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1330 ++Idx;
1331
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001332 // Check to see if there are any folding opportunities present with
1333 // operands multiplied by constant values.
1334 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1335 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohman0bba49c2009-07-07 17:06:11 +00001336 DenseMap<const SCEV *, APInt> M;
1337 SmallVector<const SCEV *, 8> NewOps;
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001338 APInt AccumulatedConstant(BitWidth, 0);
1339 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1340 Ops, APInt(BitWidth, 1), *this)) {
1341 // Some interesting folding opportunity is present, so its worthwhile to
1342 // re-generate the operands list. Group the operands by constant scale,
1343 // to avoid multiplying by the same constant scale multiple times.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001344 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
1345 for (SmallVector<const SCEV *, 8>::iterator I = NewOps.begin(),
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001346 E = NewOps.end(); I != E; ++I)
1347 MulOpLists[M.find(*I)->second].push_back(*I);
1348 // Re-generate the operands list.
1349 Ops.clear();
1350 if (AccumulatedConstant != 0)
1351 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman64a845e2009-06-24 04:48:43 +00001352 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1353 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001354 if (I->first != 0)
Dan Gohman64a845e2009-06-24 04:48:43 +00001355 Ops.push_back(getMulExpr(getConstant(I->first),
1356 getAddExpr(I->second)));
Dan Gohmanbd59d7b2009-06-14 22:58:51 +00001357 if (Ops.empty())
1358 return getIntegerSCEV(0, Ty);
1359 if (Ops.size() == 1)
1360 return Ops[0];
1361 return getAddExpr(Ops);
1362 }
1363 }
1364
Chris Lattner53e677a2004-04-02 20:23:17 +00001365 // If we are adding something to a multiply expression, make sure the
1366 // something is not already an operand of the multiply. If so, merge it into
1367 // the multiply.
1368 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001369 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001370 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001371 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Chris Lattner53e677a2004-04-02 20:23:17 +00001372 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohmana82752c2009-06-14 22:47:23 +00001373 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001374 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001375 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001376 if (Mul->getNumOperands() != 2) {
1377 // If the multiply has more than two operands, we must get the
1378 // Y*Z term.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001379 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(), Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001380 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001381 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001382 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001383 const SCEV *One = getIntegerSCEV(1, Ty);
1384 const SCEV *AddOne = getAddExpr(InnerMul, One);
1385 const SCEV *OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001386 if (Ops.size() == 2) return OuterMul;
1387 if (AddOp < Idx) {
1388 Ops.erase(Ops.begin()+AddOp);
1389 Ops.erase(Ops.begin()+Idx-1);
1390 } else {
1391 Ops.erase(Ops.begin()+Idx);
1392 Ops.erase(Ops.begin()+AddOp-1);
1393 }
1394 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001395 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001396 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001397
Chris Lattner53e677a2004-04-02 20:23:17 +00001398 // Check this multiply against other multiplies being added together.
1399 for (unsigned OtherMulIdx = Idx+1;
1400 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1401 ++OtherMulIdx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001402 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001403 // If MulOp occurs in OtherMul, we can fold the two multiplies
1404 // together.
1405 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1406 OMulOp != e; ++OMulOp)
1407 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1408 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohman0bba49c2009-07-07 17:06:11 +00001409 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001410 if (Mul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001411 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1412 Mul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001413 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001414 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001415 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001416 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00001417 if (OtherMul->getNumOperands() != 2) {
Dan Gohman64a845e2009-06-24 04:48:43 +00001418 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1419 OtherMul->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001420 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +00001421 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001422 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001423 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1424 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +00001425 if (Ops.size() == 2) return OuterMul;
1426 Ops.erase(Ops.begin()+Idx);
1427 Ops.erase(Ops.begin()+OtherMulIdx-1);
1428 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +00001429 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001430 }
1431 }
1432 }
1433 }
1434
1435 // If there are any add recurrences in the operands list, see if any other
1436 // added values are loop invariant. If so, we can fold them into the
1437 // recurrence.
1438 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1439 ++Idx;
1440
1441 // Scan over all recurrences, trying to fold loop invariants into them.
1442 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1443 // Scan all of the other operands to this add and add them to the vector if
1444 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001445 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001446 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001447 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1448 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1449 LIOps.push_back(Ops[i]);
1450 Ops.erase(Ops.begin()+i);
1451 --i; --e;
1452 }
1453
1454 // If we found some loop invariants, fold them into the recurrence.
1455 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001456 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001457 LIOps.push_back(AddRec->getStart());
1458
Dan Gohman0bba49c2009-07-07 17:06:11 +00001459 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001460 AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001461 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +00001462
Dan Gohmand281ed22009-12-18 02:09:29 +00001463 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
1464 AddRec->hasNoUnsignedWrap() && HasNUW,
1465 AddRec->hasNoSignedWrap() && HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001466 // If all of the other operands were loop invariant, we are done.
1467 if (Ops.size() == 1) return NewRec;
1468
1469 // Otherwise, add the folded AddRec by the non-liv parts.
1470 for (unsigned i = 0;; ++i)
1471 if (Ops[i] == AddRec) {
1472 Ops[i] = NewRec;
1473 break;
1474 }
Dan Gohman246b2562007-10-22 18:31:58 +00001475 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001476 }
1477
1478 // Okay, if there weren't any loop invariants to be folded, check to see if
1479 // there are multiple AddRec's with the same loop induction variable being
1480 // added together. If so, we can fold them.
1481 for (unsigned OtherIdx = Idx+1;
1482 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1483 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001484 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001485 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1486 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman64a845e2009-06-24 04:48:43 +00001487 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1488 AddRec->op_end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001489 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1490 if (i >= NewOps.size()) {
1491 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1492 OtherAddRec->op_end());
1493 break;
1494 }
Dan Gohman246b2562007-10-22 18:31:58 +00001495 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +00001496 }
Dan Gohman0bba49c2009-07-07 17:06:11 +00001497 const SCEV *NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001498
1499 if (Ops.size() == 2) return NewAddRec;
1500
1501 Ops.erase(Ops.begin()+Idx);
1502 Ops.erase(Ops.begin()+OtherIdx-1);
1503 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001504 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001505 }
1506 }
1507
1508 // Otherwise couldn't fold anything into this recurrence. Move onto the
1509 // next one.
1510 }
1511
1512 // Okay, it looks like we really DO need an add expr. Check to see if we
1513 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001514 FoldingSetNodeID ID;
1515 ID.AddInteger(scAddExpr);
1516 ID.AddInteger(Ops.size());
1517 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1518 ID.AddPointer(Ops[i]);
1519 void *IP = 0;
1520 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman3645b012009-10-09 00:10:36 +00001521 SCEVAddExpr *S = SCEVAllocator.Allocate<SCEVAddExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001522 new (S) SCEVAddExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001523 UniqueSCEVs.InsertNode(S, IP);
Dan Gohman3645b012009-10-09 00:10:36 +00001524 if (HasNUW) S->setHasNoUnsignedWrap(true);
1525 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001526 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001527}
1528
1529
Dan Gohman6c0866c2009-05-24 23:45:28 +00001530/// getMulExpr - Get a canonical multiply expression, or something simpler if
1531/// possible.
Dan Gohman3645b012009-10-09 00:10:36 +00001532const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1533 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001534 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmanf78a9782009-05-18 15:44:58 +00001535#ifndef NDEBUG
1536 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1537 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1538 getEffectiveSCEVType(Ops[0]->getType()) &&
1539 "SCEVMulExpr operand types don't match!");
1540#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001541
1542 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001543 GroupByComplexity(Ops, LI);
Chris Lattner53e677a2004-04-02 20:23:17 +00001544
1545 // If there are any constants, fold them together.
1546 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001547 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001548
1549 // C1*(C2+V) -> C1*C2 + C1*V
1550 if (Ops.size() == 2)
Dan Gohman622ed672009-05-04 22:02:23 +00001551 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattner53e677a2004-04-02 20:23:17 +00001552 if (Add->getNumOperands() == 2 &&
1553 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +00001554 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1555 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001556
1557
1558 ++Idx;
Dan Gohman622ed672009-05-04 22:02:23 +00001559 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001560 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001561 ConstantInt *Fold = ConstantInt::get(getContext(),
1562 LHSC->getValue()->getValue() *
Nick Lewycky3e630762008-02-20 06:48:22 +00001563 RHSC->getValue()->getValue());
1564 Ops[0] = getConstant(Fold);
1565 Ops.erase(Ops.begin()+1); // Erase the folded element
1566 if (Ops.size() == 1) return Ops[0];
1567 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001568 }
1569
1570 // If we are left with a constant one being multiplied, strip it off.
1571 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1572 Ops.erase(Ops.begin());
1573 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001574 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001575 // If we have a multiply of zero, it will always be zero.
1576 return Ops[0];
1577 }
1578 }
1579
1580 // Skip over the add expression until we get to a multiply.
1581 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1582 ++Idx;
1583
1584 if (Ops.size() == 1)
1585 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001586
Chris Lattner53e677a2004-04-02 20:23:17 +00001587 // If there are mul operands inline them all into this expression.
1588 if (Idx < Ops.size()) {
1589 bool DeletedMul = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001590 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001591 // If we have an mul, expand the mul operands onto the end of the operands
1592 // list.
1593 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1594 Ops.erase(Ops.begin()+Idx);
1595 DeletedMul = true;
1596 }
1597
1598 // If we deleted at least one mul, we added operands to the end of the list,
1599 // and they are not necessarily sorted. Recurse to resort and resimplify
1600 // any operands we just aquired.
1601 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001602 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001603 }
1604
1605 // If there are any add recurrences in the operands list, see if any other
1606 // added values are loop invariant. If so, we can fold them into the
1607 // recurrence.
1608 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1609 ++Idx;
1610
1611 // Scan over all recurrences, trying to fold loop invariants into them.
1612 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1613 // Scan all of the other operands to this mul and add them to the vector if
1614 // they are loop invariant w.r.t. the recurrence.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001615 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman35738ac2009-05-04 22:30:44 +00001616 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001617 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1618 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1619 LIOps.push_back(Ops[i]);
1620 Ops.erase(Ops.begin()+i);
1621 --i; --e;
1622 }
1623
1624 // If we found some loop invariants, fold them into the recurrence.
1625 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001626 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohman0bba49c2009-07-07 17:06:11 +00001627 SmallVector<const SCEV *, 4> NewOps;
Chris Lattner53e677a2004-04-02 20:23:17 +00001628 NewOps.reserve(AddRec->getNumOperands());
1629 if (LIOps.size() == 1) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001630 const SCEV *Scale = LIOps[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001631 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001632 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001633 } else {
1634 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001635 SmallVector<const SCEV *, 4> MulOps(LIOps.begin(), LIOps.end());
Chris Lattner53e677a2004-04-02 20:23:17 +00001636 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001637 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001638 }
1639 }
1640
Dan Gohmand281ed22009-12-18 02:09:29 +00001641 const SCEV *NewRec = getAddRecExpr(NewOps, AddRec->getLoop(),
1642 AddRec->hasNoUnsignedWrap() && HasNUW,
1643 AddRec->hasNoSignedWrap() && HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001644
1645 // If all of the other operands were loop invariant, we are done.
1646 if (Ops.size() == 1) return NewRec;
1647
1648 // Otherwise, multiply the folded AddRec by the non-liv parts.
1649 for (unsigned i = 0;; ++i)
1650 if (Ops[i] == AddRec) {
1651 Ops[i] = NewRec;
1652 break;
1653 }
Dan Gohman246b2562007-10-22 18:31:58 +00001654 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001655 }
1656
1657 // Okay, if there weren't any loop invariants to be folded, check to see if
1658 // there are multiple AddRec's with the same loop induction variable being
1659 // multiplied together. If so, we can fold them.
1660 for (unsigned OtherIdx = Idx+1;
1661 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1662 if (OtherIdx != Idx) {
Dan Gohman35738ac2009-05-04 22:30:44 +00001663 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001664 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1665 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohman35738ac2009-05-04 22:30:44 +00001666 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman0bba49c2009-07-07 17:06:11 +00001667 const SCEV *NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001668 G->getStart());
Dan Gohman0bba49c2009-07-07 17:06:11 +00001669 const SCEV *B = F->getStepRecurrence(*this);
1670 const SCEV *D = G->getStepRecurrence(*this);
1671 const SCEV *NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman246b2562007-10-22 18:31:58 +00001672 getMulExpr(G, B),
1673 getMulExpr(B, D));
Dan Gohman0bba49c2009-07-07 17:06:11 +00001674 const SCEV *NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman246b2562007-10-22 18:31:58 +00001675 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001676 if (Ops.size() == 2) return NewAddRec;
1677
1678 Ops.erase(Ops.begin()+Idx);
1679 Ops.erase(Ops.begin()+OtherIdx-1);
1680 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001681 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001682 }
1683 }
1684
1685 // Otherwise couldn't fold anything into this recurrence. Move onto the
1686 // next one.
1687 }
1688
1689 // Okay, it looks like we really DO need an mul expr. Check to see if we
1690 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001691 FoldingSetNodeID ID;
1692 ID.AddInteger(scMulExpr);
1693 ID.AddInteger(Ops.size());
1694 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1695 ID.AddPointer(Ops[i]);
1696 void *IP = 0;
1697 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman3645b012009-10-09 00:10:36 +00001698 SCEVMulExpr *S = SCEVAllocator.Allocate<SCEVMulExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001699 new (S) SCEVMulExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001700 UniqueSCEVs.InsertNode(S, IP);
Dan Gohman3645b012009-10-09 00:10:36 +00001701 if (HasNUW) S->setHasNoUnsignedWrap(true);
1702 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001703 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001704}
1705
Andreas Bolka8a11c982009-08-07 22:55:26 +00001706/// getUDivExpr - Get a canonical unsigned division expression, or something
1707/// simpler if possible.
Dan Gohman9311ef62009-06-24 14:49:00 +00001708const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1709 const SCEV *RHS) {
Dan Gohmanf78a9782009-05-18 15:44:58 +00001710 assert(getEffectiveSCEVType(LHS->getType()) ==
1711 getEffectiveSCEVType(RHS->getType()) &&
1712 "SCEVUDivExpr operand types don't match!");
1713
Dan Gohman622ed672009-05-04 22:02:23 +00001714 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001715 if (RHSC->getValue()->equalsInt(1))
Dan Gohman4c0d5d52009-08-20 16:42:55 +00001716 return LHS; // X udiv 1 --> x
Dan Gohman185cf032009-05-08 20:18:49 +00001717 if (RHSC->isZero())
1718 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Chris Lattner53e677a2004-04-02 20:23:17 +00001719
Dan Gohman185cf032009-05-08 20:18:49 +00001720 // Determine if the division can be folded into the operands of
1721 // its operands.
1722 // TODO: Generalize this to non-constants by using known-bits information.
1723 const Type *Ty = LHS->getType();
1724 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1725 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1726 // For non-power-of-two values, effectively round the value up to the
1727 // nearest power of two.
1728 if (!RHSC->getValue()->getValue().isPowerOf2())
1729 ++MaxShiftAmt;
1730 const IntegerType *ExtTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00001731 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohman185cf032009-05-08 20:18:49 +00001732 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1733 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1734 if (const SCEVConstant *Step =
1735 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1736 if (!Step->getValue()->getValue()
1737 .urem(RHSC->getValue()->getValue()) &&
Dan Gohmanb0285932009-05-08 23:11:16 +00001738 getZeroExtendExpr(AR, ExtTy) ==
1739 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1740 getZeroExtendExpr(Step, ExtTy),
1741 AR->getLoop())) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001742 SmallVector<const SCEV *, 4> Operands;
Dan Gohman185cf032009-05-08 20:18:49 +00001743 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1744 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1745 return getAddRecExpr(Operands, AR->getLoop());
1746 }
1747 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohmanb0285932009-05-08 23:11:16 +00001748 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001749 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001750 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1751 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1752 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohman185cf032009-05-08 20:18:49 +00001753 // Find an operand that's safely divisible.
1754 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001755 const SCEV *Op = M->getOperand(i);
1756 const SCEV *Div = getUDivExpr(Op, RHSC);
Dan Gohman185cf032009-05-08 20:18:49 +00001757 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001758 const SmallVectorImpl<const SCEV *> &MOperands = M->getOperands();
1759 Operands = SmallVector<const SCEV *, 4>(MOperands.begin(),
Dan Gohmana82752c2009-06-14 22:47:23 +00001760 MOperands.end());
Dan Gohman185cf032009-05-08 20:18:49 +00001761 Operands[i] = Div;
1762 return getMulExpr(Operands);
1763 }
1764 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001765 }
Dan Gohman185cf032009-05-08 20:18:49 +00001766 // (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 +00001767 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001768 SmallVector<const SCEV *, 4> Operands;
Dan Gohmanb0285932009-05-08 23:11:16 +00001769 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1770 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1771 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1772 Operands.clear();
Dan Gohman185cf032009-05-08 20:18:49 +00001773 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001774 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohman185cf032009-05-08 20:18:49 +00001775 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1776 break;
1777 Operands.push_back(Op);
1778 }
1779 if (Operands.size() == A->getNumOperands())
1780 return getAddExpr(Operands);
1781 }
Dan Gohmanb0285932009-05-08 23:11:16 +00001782 }
Dan Gohman185cf032009-05-08 20:18:49 +00001783
1784 // Fold if both operands are constant.
Dan Gohman622ed672009-05-04 22:02:23 +00001785 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001786 Constant *LHSCV = LHSC->getValue();
1787 Constant *RHSCV = RHSC->getValue();
Owen Andersonbaf3c402009-07-29 18:55:55 +00001788 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
Dan Gohmanb8be8b72009-06-24 00:38:39 +00001789 RHSCV)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001790 }
1791 }
1792
Dan Gohman1c343752009-06-27 21:21:31 +00001793 FoldingSetNodeID ID;
1794 ID.AddInteger(scUDivExpr);
1795 ID.AddPointer(LHS);
1796 ID.AddPointer(RHS);
1797 void *IP = 0;
1798 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1799 SCEV *S = SCEVAllocator.Allocate<SCEVUDivExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001800 new (S) SCEVUDivExpr(ID, LHS, RHS);
Dan Gohman1c343752009-06-27 21:21:31 +00001801 UniqueSCEVs.InsertNode(S, IP);
1802 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001803}
1804
1805
Dan Gohman6c0866c2009-05-24 23:45:28 +00001806/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1807/// Simplify the expression as much as possible.
Dan Gohman0bba49c2009-07-07 17:06:11 +00001808const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start,
Dan Gohman3645b012009-10-09 00:10:36 +00001809 const SCEV *Step, const Loop *L,
1810 bool HasNUW, bool HasNSW) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001811 SmallVector<const SCEV *, 4> Operands;
Chris Lattner53e677a2004-04-02 20:23:17 +00001812 Operands.push_back(Start);
Dan Gohman622ed672009-05-04 22:02:23 +00001813 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattner53e677a2004-04-02 20:23:17 +00001814 if (StepChrec->getLoop() == L) {
1815 Operands.insert(Operands.end(), StepChrec->op_begin(),
1816 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001817 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001818 }
1819
1820 Operands.push_back(Step);
Dan Gohman3645b012009-10-09 00:10:36 +00001821 return getAddRecExpr(Operands, L, HasNUW, HasNSW);
Chris Lattner53e677a2004-04-02 20:23:17 +00001822}
1823
Dan Gohman6c0866c2009-05-24 23:45:28 +00001824/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1825/// Simplify the expression as much as possible.
Dan Gohman64a845e2009-06-24 04:48:43 +00001826const SCEV *
Dan Gohman0bba49c2009-07-07 17:06:11 +00001827ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Dan Gohman3645b012009-10-09 00:10:36 +00001828 const Loop *L,
1829 bool HasNUW, bool HasNSW) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001830 if (Operands.size() == 1) return Operands[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001831#ifndef NDEBUG
1832 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1833 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1834 getEffectiveSCEVType(Operands[0]->getType()) &&
1835 "SCEVAddRecExpr operand types don't match!");
1836#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001837
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001838 if (Operands.back()->isZero()) {
1839 Operands.pop_back();
Dan Gohman3645b012009-10-09 00:10:36 +00001840 return getAddRecExpr(Operands, L, HasNUW, HasNSW); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001841 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001842
Dan Gohmand9cc7492008-08-08 18:33:12 +00001843 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohman622ed672009-05-04 22:02:23 +00001844 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman5d984912009-12-18 01:14:11 +00001845 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohmand9cc7492008-08-08 18:33:12 +00001846 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001847 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman5d984912009-12-18 01:14:11 +00001848 NestedAR->op_end());
Dan Gohmand9cc7492008-08-08 18:33:12 +00001849 Operands[0] = NestedAR->getStart();
Dan Gohman9a80b452009-06-26 22:36:20 +00001850 // AddRecs require their operands be loop-invariant with respect to their
1851 // loops. Don't perform this transformation if it would break this
1852 // requirement.
1853 bool AllInvariant = true;
1854 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1855 if (!Operands[i]->isLoopInvariant(L)) {
1856 AllInvariant = false;
1857 break;
1858 }
1859 if (AllInvariant) {
1860 NestedOperands[0] = getAddRecExpr(Operands, L);
1861 AllInvariant = true;
1862 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
1863 if (!NestedOperands[i]->isLoopInvariant(NestedLoop)) {
1864 AllInvariant = false;
1865 break;
1866 }
1867 if (AllInvariant)
1868 // Ok, both add recurrences are valid after the transformation.
Dan Gohman3645b012009-10-09 00:10:36 +00001869 return getAddRecExpr(NestedOperands, NestedLoop, HasNUW, HasNSW);
Dan Gohman9a80b452009-06-26 22:36:20 +00001870 }
1871 // Reset Operands to its original state.
1872 Operands[0] = NestedAR;
Dan Gohmand9cc7492008-08-08 18:33:12 +00001873 }
1874 }
1875
Dan Gohman1c343752009-06-27 21:21:31 +00001876 FoldingSetNodeID ID;
1877 ID.AddInteger(scAddRecExpr);
1878 ID.AddInteger(Operands.size());
1879 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1880 ID.AddPointer(Operands[i]);
1881 ID.AddPointer(L);
1882 void *IP = 0;
1883 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman3645b012009-10-09 00:10:36 +00001884 SCEVAddRecExpr *S = SCEVAllocator.Allocate<SCEVAddRecExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001885 new (S) SCEVAddRecExpr(ID, Operands, L);
Dan Gohman1c343752009-06-27 21:21:31 +00001886 UniqueSCEVs.InsertNode(S, IP);
Dan Gohman3645b012009-10-09 00:10:36 +00001887 if (HasNUW) S->setHasNoUnsignedWrap(true);
1888 if (HasNSW) S->setHasNoSignedWrap(true);
Dan Gohman1c343752009-06-27 21:21:31 +00001889 return S;
Chris Lattner53e677a2004-04-02 20:23:17 +00001890}
1891
Dan Gohman9311ef62009-06-24 14:49:00 +00001892const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1893 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001894 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001895 Ops.push_back(LHS);
1896 Ops.push_back(RHS);
1897 return getSMaxExpr(Ops);
1898}
1899
Dan Gohman0bba49c2009-07-07 17:06:11 +00001900const SCEV *
1901ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001902 assert(!Ops.empty() && "Cannot get empty smax!");
1903 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00001904#ifndef NDEBUG
1905 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1906 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1907 getEffectiveSCEVType(Ops[0]->getType()) &&
1908 "SCEVSMaxExpr operand types don't match!");
1909#endif
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001910
1911 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00001912 GroupByComplexity(Ops, LI);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001913
1914 // If there are any constants, fold them together.
1915 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00001916 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001917 ++Idx;
1918 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00001919 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001920 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00001921 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001922 APIntOps::smax(LHSC->getValue()->getValue(),
1923 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001924 Ops[0] = getConstant(Fold);
1925 Ops.erase(Ops.begin()+1); // Erase the folded element
1926 if (Ops.size() == 1) return Ops[0];
1927 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001928 }
1929
Dan Gohmane5aceed2009-06-24 14:46:22 +00001930 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001931 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1932 Ops.erase(Ops.begin());
1933 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00001934 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1935 // If we have an smax with a constant maximum-int, it will always be
1936 // maximum-int.
1937 return Ops[0];
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001938 }
1939 }
1940
1941 if (Ops.size() == 1) return Ops[0];
1942
1943 // Find the first SMax
1944 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1945 ++Idx;
1946
1947 // Check to see if one of the operands is an SMax. If so, expand its operands
1948 // onto our operand list, and recurse to simplify.
1949 if (Idx < Ops.size()) {
1950 bool DeletedSMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00001951 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001952 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1953 Ops.erase(Ops.begin()+Idx);
1954 DeletedSMax = true;
1955 }
1956
1957 if (DeletedSMax)
1958 return getSMaxExpr(Ops);
1959 }
1960
1961 // Okay, check to see if the same value occurs in the operand list twice. If
1962 // so, delete one. Since we sorted the list, these values are required to
1963 // be adjacent.
1964 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1965 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1966 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1967 --i; --e;
1968 }
1969
1970 if (Ops.size() == 1) return Ops[0];
1971
1972 assert(!Ops.empty() && "Reduced smax down to nothing!");
1973
Nick Lewycky3e630762008-02-20 06:48:22 +00001974 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001975 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00001976 FoldingSetNodeID ID;
1977 ID.AddInteger(scSMaxExpr);
1978 ID.AddInteger(Ops.size());
1979 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1980 ID.AddPointer(Ops[i]);
1981 void *IP = 0;
1982 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1983 SCEV *S = SCEVAllocator.Allocate<SCEVSMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00001984 new (S) SCEVSMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00001985 UniqueSCEVs.InsertNode(S, IP);
1986 return S;
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001987}
1988
Dan Gohman9311ef62009-06-24 14:49:00 +00001989const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1990 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00001991 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky3e630762008-02-20 06:48:22 +00001992 Ops.push_back(LHS);
1993 Ops.push_back(RHS);
1994 return getUMaxExpr(Ops);
1995}
1996
Dan Gohman0bba49c2009-07-07 17:06:11 +00001997const SCEV *
1998ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky3e630762008-02-20 06:48:22 +00001999 assert(!Ops.empty() && "Cannot get empty umax!");
2000 if (Ops.size() == 1) return Ops[0];
Dan Gohmanf78a9782009-05-18 15:44:58 +00002001#ifndef NDEBUG
2002 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
2003 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
2004 getEffectiveSCEVType(Ops[0]->getType()) &&
2005 "SCEVUMaxExpr operand types don't match!");
2006#endif
Nick Lewycky3e630762008-02-20 06:48:22 +00002007
2008 // Sort by complexity, this groups all similar expression types together.
Dan Gohman72861302009-05-07 14:39:04 +00002009 GroupByComplexity(Ops, LI);
Nick Lewycky3e630762008-02-20 06:48:22 +00002010
2011 // If there are any constants, fold them together.
2012 unsigned Idx = 0;
Dan Gohman622ed672009-05-04 22:02:23 +00002013 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002014 ++Idx;
2015 assert(Idx < Ops.size());
Dan Gohman622ed672009-05-04 22:02:23 +00002016 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002017 // We found two constants, fold them together!
Owen Andersoneed707b2009-07-24 23:12:02 +00002018 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky3e630762008-02-20 06:48:22 +00002019 APIntOps::umax(LHSC->getValue()->getValue(),
2020 RHSC->getValue()->getValue()));
2021 Ops[0] = getConstant(Fold);
2022 Ops.erase(Ops.begin()+1); // Erase the folded element
2023 if (Ops.size() == 1) return Ops[0];
2024 LHSC = cast<SCEVConstant>(Ops[0]);
2025 }
2026
Dan Gohmane5aceed2009-06-24 14:46:22 +00002027 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky3e630762008-02-20 06:48:22 +00002028 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2029 Ops.erase(Ops.begin());
2030 --Idx;
Dan Gohmane5aceed2009-06-24 14:46:22 +00002031 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2032 // If we have an umax with a constant maximum-int, it will always be
2033 // maximum-int.
2034 return Ops[0];
Nick Lewycky3e630762008-02-20 06:48:22 +00002035 }
2036 }
2037
2038 if (Ops.size() == 1) return Ops[0];
2039
2040 // Find the first UMax
2041 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2042 ++Idx;
2043
2044 // Check to see if one of the operands is a UMax. If so, expand its operands
2045 // onto our operand list, and recurse to simplify.
2046 if (Idx < Ops.size()) {
2047 bool DeletedUMax = false;
Dan Gohman622ed672009-05-04 22:02:23 +00002048 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002049 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
2050 Ops.erase(Ops.begin()+Idx);
2051 DeletedUMax = true;
2052 }
2053
2054 if (DeletedUMax)
2055 return getUMaxExpr(Ops);
2056 }
2057
2058 // Okay, check to see if the same value occurs in the operand list twice. If
2059 // so, delete one. Since we sorted the list, these values are required to
2060 // be adjacent.
2061 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
2062 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
2063 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2064 --i; --e;
2065 }
2066
2067 if (Ops.size() == 1) return Ops[0];
2068
2069 assert(!Ops.empty() && "Reduced umax down to nothing!");
2070
2071 // Okay, it looks like we really DO need a umax expr. Check to see if we
2072 // already have one, otherwise create a new one.
Dan Gohman1c343752009-06-27 21:21:31 +00002073 FoldingSetNodeID ID;
2074 ID.AddInteger(scUMaxExpr);
2075 ID.AddInteger(Ops.size());
2076 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2077 ID.AddPointer(Ops[i]);
2078 void *IP = 0;
2079 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2080 SCEV *S = SCEVAllocator.Allocate<SCEVUMaxExpr>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002081 new (S) SCEVUMaxExpr(ID, Ops);
Dan Gohman1c343752009-06-27 21:21:31 +00002082 UniqueSCEVs.InsertNode(S, IP);
2083 return S;
Nick Lewycky3e630762008-02-20 06:48:22 +00002084}
2085
Dan Gohman9311ef62009-06-24 14:49:00 +00002086const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2087 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002088 // ~smax(~x, ~y) == smin(x, y).
2089 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2090}
2091
Dan Gohman9311ef62009-06-24 14:49:00 +00002092const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2093 const SCEV *RHS) {
Dan Gohmanf9a9a992009-06-22 03:18:45 +00002094 // ~umax(~x, ~y) == umin(x, y)
2095 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2096}
2097
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002098const SCEV *ScalarEvolution::getFieldOffsetExpr(const StructType *STy,
2099 unsigned FieldNo) {
2100 // If we have TargetData we can determine the constant offset.
2101 if (TD) {
2102 const Type *IntPtrTy = TD->getIntPtrType(getContext());
2103 const StructLayout &SL = *TD->getStructLayout(STy);
2104 uint64_t Offset = SL.getElementOffset(FieldNo);
2105 return getIntegerSCEV(Offset, IntPtrTy);
2106 }
2107
2108 // Field 0 is always at offset 0.
2109 if (FieldNo == 0) {
2110 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2111 return getIntegerSCEV(0, Ty);
2112 }
2113
2114 // Okay, it looks like we really DO need an offsetof expr. Check to see if we
2115 // already have one, otherwise create a new one.
2116 FoldingSetNodeID ID;
2117 ID.AddInteger(scFieldOffset);
2118 ID.AddPointer(STy);
2119 ID.AddInteger(FieldNo);
2120 void *IP = 0;
2121 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2122 SCEV *S = SCEVAllocator.Allocate<SCEVFieldOffsetExpr>();
2123 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
2124 new (S) SCEVFieldOffsetExpr(ID, Ty, STy, FieldNo);
2125 UniqueSCEVs.InsertNode(S, IP);
2126 return S;
2127}
2128
2129const SCEV *ScalarEvolution::getAllocSizeExpr(const Type *AllocTy) {
2130 // If we have TargetData we can determine the constant size.
2131 if (TD && AllocTy->isSized()) {
2132 const Type *IntPtrTy = TD->getIntPtrType(getContext());
2133 return getIntegerSCEV(TD->getTypeAllocSize(AllocTy), IntPtrTy);
2134 }
2135
2136 // Expand an array size into the element size times the number
2137 // of elements.
2138 if (const ArrayType *ATy = dyn_cast<ArrayType>(AllocTy)) {
2139 const SCEV *E = getAllocSizeExpr(ATy->getElementType());
2140 return getMulExpr(
2141 E, getConstant(ConstantInt::get(cast<IntegerType>(E->getType()),
2142 ATy->getNumElements())));
2143 }
2144
2145 // Expand a vector size into the element size times the number
2146 // of elements.
2147 if (const VectorType *VTy = dyn_cast<VectorType>(AllocTy)) {
2148 const SCEV *E = getAllocSizeExpr(VTy->getElementType());
2149 return getMulExpr(
2150 E, getConstant(ConstantInt::get(cast<IntegerType>(E->getType()),
2151 VTy->getNumElements())));
2152 }
2153
2154 // Okay, it looks like we really DO need a sizeof expr. Check to see if we
2155 // already have one, otherwise create a new one.
2156 FoldingSetNodeID ID;
2157 ID.AddInteger(scAllocSize);
2158 ID.AddPointer(AllocTy);
2159 void *IP = 0;
2160 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2161 SCEV *S = SCEVAllocator.Allocate<SCEVAllocSizeExpr>();
2162 const Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
2163 new (S) SCEVAllocSizeExpr(ID, Ty, AllocTy);
2164 UniqueSCEVs.InsertNode(S, IP);
2165 return S;
2166}
2167
Dan Gohman0bba49c2009-07-07 17:06:11 +00002168const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002169 // Don't attempt to do anything other than create a SCEVUnknown object
2170 // here. createSCEV only calls getUnknown after checking for all other
2171 // interesting possibilities, and any other code that calls getUnknown
2172 // is doing so in order to hide a value from SCEV canonicalization.
2173
Dan Gohman1c343752009-06-27 21:21:31 +00002174 FoldingSetNodeID ID;
2175 ID.AddInteger(scUnknown);
2176 ID.AddPointer(V);
2177 void *IP = 0;
2178 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
2179 SCEV *S = SCEVAllocator.Allocate<SCEVUnknown>();
Dan Gohmanc050fd92009-07-13 20:50:19 +00002180 new (S) SCEVUnknown(ID, V);
Dan Gohman1c343752009-06-27 21:21:31 +00002181 UniqueSCEVs.InsertNode(S, IP);
2182 return S;
Chris Lattner0a7f98c2004-04-15 15:07:24 +00002183}
2184
Chris Lattner53e677a2004-04-02 20:23:17 +00002185//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00002186// Basic SCEV Analysis and PHI Idiom Recognition Code
2187//
2188
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002189/// isSCEVable - Test if values of the given type are analyzable within
2190/// the SCEV framework. This primarily includes integer types, and it
2191/// can optionally include pointer types if the ScalarEvolution class
2192/// has access to target-specific information.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002193bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002194 // Integers and pointers are always SCEVable.
2195 return Ty->isInteger() || isa<PointerType>(Ty);
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002196}
2197
2198/// getTypeSizeInBits - Return the size in bits of the specified type,
2199/// for which isSCEVable must return true.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002200uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002201 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2202
2203 // If we have a TargetData, use it!
2204 if (TD)
2205 return TD->getTypeSizeInBits(Ty);
2206
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002207 // Integer types have fixed sizes.
2208 if (Ty->isInteger())
2209 return Ty->getPrimitiveSizeInBits();
2210
2211 // The only other support type is pointer. Without TargetData, conservatively
2212 // assume pointers are 64-bit.
2213 assert(isa<PointerType>(Ty) && "isSCEVable permitted a non-SCEVable type!");
2214 return 64;
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002215}
2216
2217/// getEffectiveSCEVType - Return a type with the same bitwidth as
2218/// the given type and which represents how SCEV will treat the given
2219/// type, for which isSCEVable must return true. For pointer types,
2220/// this is the pointer-sized integer type.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002221const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002222 assert(isSCEVable(Ty) && "Type is not SCEVable!");
2223
2224 if (Ty->isInteger())
2225 return Ty;
2226
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002227 // The only other support type is pointer.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002228 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002229 if (TD) return TD->getIntPtrType(getContext());
2230
2231 // Without TargetData, conservatively assume pointers are 64-bit.
2232 return Type::getInt64Ty(getContext());
Dan Gohman2d1be872009-04-16 03:18:22 +00002233}
Chris Lattner53e677a2004-04-02 20:23:17 +00002234
Dan Gohman0bba49c2009-07-07 17:06:11 +00002235const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohman1c343752009-06-27 21:21:31 +00002236 return &CouldNotCompute;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00002237}
2238
Chris Lattner53e677a2004-04-02 20:23:17 +00002239/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
2240/// expression and create a new one.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002241const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002242 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002243
Dan Gohman0bba49c2009-07-07 17:06:11 +00002244 std::map<SCEVCallbackVH, const SCEV *>::iterator I = Scalars.find(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002245 if (I != Scalars.end()) return I->second;
Dan Gohman0bba49c2009-07-07 17:06:11 +00002246 const SCEV *S = createSCEV(V);
Dan Gohman35738ac2009-05-04 22:30:44 +00002247 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattner53e677a2004-04-02 20:23:17 +00002248 return S;
2249}
2250
Dan Gohman6bbcba12009-06-24 00:54:57 +00002251/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman2d1be872009-04-16 03:18:22 +00002252/// specified signed integer value and return a SCEV for the constant.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002253const SCEV *ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman6bbcba12009-06-24 00:54:57 +00002254 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Owen Andersoneed707b2009-07-24 23:12:02 +00002255 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman2d1be872009-04-16 03:18:22 +00002256}
2257
2258/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
2259///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002260const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002261 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson0a5372e2009-07-13 04:09:18 +00002262 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002263 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002264
2265 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002266 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002267 return getMulExpr(V,
Owen Andersona7235ea2009-07-31 20:28:14 +00002268 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman2d1be872009-04-16 03:18:22 +00002269}
2270
2271/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohman0bba49c2009-07-07 17:06:11 +00002272const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohman622ed672009-05-04 22:02:23 +00002273 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson73c6b712009-07-13 20:58:05 +00002274 return getConstant(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002275 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman2d1be872009-04-16 03:18:22 +00002276
2277 const Type *Ty = V->getType();
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002278 Ty = getEffectiveSCEVType(Ty);
Owen Anderson73c6b712009-07-13 20:58:05 +00002279 const SCEV *AllOnes =
Owen Andersona7235ea2009-07-31 20:28:14 +00002280 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman2d1be872009-04-16 03:18:22 +00002281 return getMinusSCEV(AllOnes, V);
2282}
2283
2284/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
2285///
Dan Gohman9311ef62009-06-24 14:49:00 +00002286const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
2287 const SCEV *RHS) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002288 // X - Y --> X + -Y
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002289 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman2d1be872009-04-16 03:18:22 +00002290}
2291
2292/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
2293/// input value to the specified type. If the type must be extended, it is zero
2294/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002295const SCEV *
2296ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002297 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002298 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002299 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2300 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002301 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002302 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002303 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002304 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002305 return getTruncateExpr(V, Ty);
2306 return getZeroExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002307}
2308
2309/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2310/// input value to the specified type. If the type must be extended, it is sign
2311/// extended.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002312const SCEV *
2313ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Nick Lewycky5cd28fa2009-04-23 05:15:08 +00002314 const Type *Ty) {
Dan Gohman2d1be872009-04-16 03:18:22 +00002315 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002316 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2317 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2d1be872009-04-16 03:18:22 +00002318 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002319 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman2d1be872009-04-16 03:18:22 +00002320 return V; // No conversion
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002321 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002322 return getTruncateExpr(V, Ty);
2323 return getSignExtendExpr(V, Ty);
Dan Gohman2d1be872009-04-16 03:18:22 +00002324}
2325
Dan Gohman467c4302009-05-13 03:46:30 +00002326/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2327/// input value to the specified type. If the type must be extended, it is zero
2328/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002329const SCEV *
2330ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002331 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002332 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2333 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002334 "Cannot noop or zero extend with non-integer arguments!");
2335 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2336 "getNoopOrZeroExtend cannot truncate!");
2337 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2338 return V; // No conversion
2339 return getZeroExtendExpr(V, Ty);
2340}
2341
2342/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2343/// input value to the specified type. If the type must be extended, it is sign
2344/// extended. The conversion must not be narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002345const SCEV *
2346ScalarEvolution::getNoopOrSignExtend(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002347 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002348 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2349 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002350 "Cannot noop or sign extend with non-integer arguments!");
2351 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2352 "getNoopOrSignExtend cannot truncate!");
2353 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2354 return V; // No conversion
2355 return getSignExtendExpr(V, Ty);
2356}
2357
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002358/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2359/// the input value to the specified type. If the type must be extended,
2360/// it is extended with unspecified bits. The conversion must not be
2361/// narrowing.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002362const SCEV *
2363ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, const Type *Ty) {
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002364 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002365 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2366 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman2ce84c8d2009-06-13 15:56:47 +00002367 "Cannot noop or any extend with non-integer arguments!");
2368 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2369 "getNoopOrAnyExtend cannot truncate!");
2370 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2371 return V; // No conversion
2372 return getAnyExtendExpr(V, Ty);
2373}
2374
Dan Gohman467c4302009-05-13 03:46:30 +00002375/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2376/// input value to the specified type. The conversion must not be widening.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002377const SCEV *
2378ScalarEvolution::getTruncateOrNoop(const SCEV *V, const Type *Ty) {
Dan Gohman467c4302009-05-13 03:46:30 +00002379 const Type *SrcTy = V->getType();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002380 assert((SrcTy->isInteger() || isa<PointerType>(SrcTy)) &&
2381 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohman467c4302009-05-13 03:46:30 +00002382 "Cannot truncate or noop with non-integer arguments!");
2383 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2384 "getTruncateOrNoop cannot extend!");
2385 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2386 return V; // No conversion
2387 return getTruncateExpr(V, Ty);
2388}
2389
Dan Gohmana334aa72009-06-22 00:31:57 +00002390/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2391/// the types using zero-extension, and then perform a umax operation
2392/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002393const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2394 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002395 const SCEV *PromotedLHS = LHS;
2396 const SCEV *PromotedRHS = RHS;
Dan Gohmana334aa72009-06-22 00:31:57 +00002397
2398 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2399 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2400 else
2401 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2402
2403 return getUMaxExpr(PromotedLHS, PromotedRHS);
2404}
2405
Dan Gohmanc9759e82009-06-22 15:03:27 +00002406/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2407/// the types using zero-extension, and then perform a umin operation
2408/// with them.
Dan Gohman9311ef62009-06-24 14:49:00 +00002409const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2410 const SCEV *RHS) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002411 const SCEV *PromotedLHS = LHS;
2412 const SCEV *PromotedRHS = RHS;
Dan Gohmanc9759e82009-06-22 15:03:27 +00002413
2414 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2415 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2416 else
2417 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2418
2419 return getUMinExpr(PromotedLHS, PromotedRHS);
2420}
2421
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002422/// PushDefUseChildren - Push users of the given Instruction
2423/// onto the given Worklist.
2424static void
2425PushDefUseChildren(Instruction *I,
2426 SmallVectorImpl<Instruction *> &Worklist) {
2427 // Push the def-use children onto the Worklist stack.
2428 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2429 UI != UE; ++UI)
2430 Worklist.push_back(cast<Instruction>(UI));
2431}
2432
2433/// ForgetSymbolicValue - This looks up computed SCEV values for all
2434/// instructions that depend on the given instruction and removes them from
2435/// the Scalars map if they reference SymName. This is used during PHI
2436/// resolution.
Dan Gohman64a845e2009-06-24 04:48:43 +00002437void
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002438ScalarEvolution::ForgetSymbolicName(Instruction *I, const SCEV *SymName) {
2439 SmallVector<Instruction *, 16> Worklist;
2440 PushDefUseChildren(I, Worklist);
Chris Lattner53e677a2004-04-02 20:23:17 +00002441
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002442 SmallPtrSet<Instruction *, 8> Visited;
2443 Visited.insert(I);
2444 while (!Worklist.empty()) {
2445 Instruction *I = Worklist.pop_back_val();
2446 if (!Visited.insert(I)) continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002447
Dan Gohman5d984912009-12-18 01:14:11 +00002448 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002449 Scalars.find(static_cast<Value *>(I));
2450 if (It != Scalars.end()) {
2451 // Short-circuit the def-use traversal if the symbolic name
2452 // ceases to appear in expressions.
2453 if (!It->second->hasOperand(SymName))
2454 continue;
Chris Lattner4dc534c2005-02-13 04:37:18 +00002455
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002456 // SCEVUnknown for a PHI either means that it has an unrecognized
2457 // structure, or it's a PHI that's in the progress of being computed
2458 // by createNodeForPHI. In the former case, additional loop trip
2459 // count information isn't going to change anything. In the later
2460 // case, createNodeForPHI will perform the necessary updates on its
2461 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00002462 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
2463 ValuesAtScopes.erase(It->second);
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002464 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00002465 }
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002466 }
2467
2468 PushDefUseChildren(I, Worklist);
2469 }
Chris Lattner4dc534c2005-02-13 04:37:18 +00002470}
Chris Lattner53e677a2004-04-02 20:23:17 +00002471
2472/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2473/// a loop header, making it a potential recurrence, or it doesn't.
2474///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002475const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002476 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002477 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002478 if (L->getHeader() == PN->getParent()) {
2479 // If it lives in the loop header, it has two incoming values, one
2480 // from outside the loop, and one from inside.
2481 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2482 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002483
Chris Lattner53e677a2004-04-02 20:23:17 +00002484 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002485 const SCEV *SymbolicName = getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002486 assert(Scalars.find(PN) == Scalars.end() &&
2487 "PHI node already processed?");
Dan Gohman35738ac2009-05-04 22:30:44 +00002488 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattner53e677a2004-04-02 20:23:17 +00002489
2490 // Using this symbolic name for the PHI, analyze the value coming around
2491 // the back-edge.
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002492 Value *BEValueV = PN->getIncomingValue(BackEdge);
2493 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002494
2495 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2496 // has a special value for the first iteration of the loop.
2497
2498 // If the value coming around the backedge is an add with the symbolic
2499 // value we just inserted, then we found a simple induction variable!
Dan Gohman622ed672009-05-04 22:02:23 +00002500 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002501 // If there is a single occurrence of the symbolic value, replace it
2502 // with a recurrence.
2503 unsigned FoundIndex = Add->getNumOperands();
2504 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2505 if (Add->getOperand(i) == SymbolicName)
2506 if (FoundIndex == e) {
2507 FoundIndex = i;
2508 break;
2509 }
2510
2511 if (FoundIndex != Add->getNumOperands()) {
2512 // Create an add with everything but the specified operand.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002513 SmallVector<const SCEV *, 8> Ops;
Chris Lattner53e677a2004-04-02 20:23:17 +00002514 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2515 if (i != FoundIndex)
2516 Ops.push_back(Add->getOperand(i));
Dan Gohman0bba49c2009-07-07 17:06:11 +00002517 const SCEV *Accum = getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00002518
2519 // This is not a valid addrec if the step amount is varying each
2520 // loop iteration, but is not itself an addrec in this loop.
2521 if (Accum->isLoopInvariant(L) ||
2522 (isa<SCEVAddRecExpr>(Accum) &&
2523 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman64a845e2009-06-24 04:48:43 +00002524 const SCEV *StartVal =
2525 getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmaneb490a72009-07-25 01:22:26 +00002526 const SCEVAddRecExpr *PHISCEV =
2527 cast<SCEVAddRecExpr>(getAddRecExpr(StartVal, Accum, L));
2528
2529 // If the increment doesn't overflow, then neither the addrec nor the
2530 // post-increment will overflow.
2531 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV))
2532 if (OBO->getOperand(0) == PN &&
2533 getSCEV(OBO->getOperand(1)) ==
2534 PHISCEV->getStepRecurrence(*this)) {
2535 const SCEVAddRecExpr *PostInc = PHISCEV->getPostIncExpr(*this);
Dan Gohman5078f842009-08-20 17:11:38 +00002536 if (OBO->hasNoUnsignedWrap()) {
Dan Gohmaneb490a72009-07-25 01:22:26 +00002537 const_cast<SCEVAddRecExpr *>(PHISCEV)
Dan Gohman5078f842009-08-20 17:11:38 +00002538 ->setHasNoUnsignedWrap(true);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002539 const_cast<SCEVAddRecExpr *>(PostInc)
Dan Gohman5078f842009-08-20 17:11:38 +00002540 ->setHasNoUnsignedWrap(true);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002541 }
Dan Gohman5078f842009-08-20 17:11:38 +00002542 if (OBO->hasNoSignedWrap()) {
Dan Gohmaneb490a72009-07-25 01:22:26 +00002543 const_cast<SCEVAddRecExpr *>(PHISCEV)
Dan Gohman5078f842009-08-20 17:11:38 +00002544 ->setHasNoSignedWrap(true);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002545 const_cast<SCEVAddRecExpr *>(PostInc)
Dan Gohman5078f842009-08-20 17:11:38 +00002546 ->setHasNoSignedWrap(true);
Dan Gohmaneb490a72009-07-25 01:22:26 +00002547 }
2548 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002549
2550 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002551 // to be symbolic. We now need to go back and purge all of the
2552 // entries for the scalars that use the symbolic expression.
2553 ForgetSymbolicName(PN, SymbolicName);
2554 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner53e677a2004-04-02 20:23:17 +00002555 return PHISCEV;
2556 }
2557 }
Dan Gohman622ed672009-05-04 22:02:23 +00002558 } else if (const SCEVAddRecExpr *AddRec =
2559 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattner97156e72006-04-26 18:34:07 +00002560 // Otherwise, this could be a loop like this:
2561 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2562 // In this case, j = {1,+,1} and BEValue is j.
2563 // Because the other in-value of i (0) fits the evolution of BEValue
2564 // i really is an addrec evolution.
2565 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002566 const SCEV *StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Chris Lattner97156e72006-04-26 18:34:07 +00002567
2568 // If StartVal = j.start - j.stride, we can use StartVal as the
2569 // initial step of the addrec evolution.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002570 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman246b2562007-10-22 18:31:58 +00002571 AddRec->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00002572 const SCEV *PHISCEV =
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002573 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00002574
2575 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohmanfef8bb22009-07-25 01:13:03 +00002576 // to be symbolic. We now need to go back and purge all of the
2577 // entries for the scalars that use the symbolic expression.
2578 ForgetSymbolicName(PN, SymbolicName);
2579 Scalars[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattner97156e72006-04-26 18:34:07 +00002580 return PHISCEV;
2581 }
2582 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002583 }
2584
2585 return SymbolicName;
2586 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002587
Dan Gohmana653fc52009-07-14 14:06:25 +00002588 // It's tempting to recognize PHIs with a unique incoming value, however
2589 // this leads passes like indvars to break LCSSA form. Fortunately, such
2590 // PHIs are rare, as instcombine zaps them.
2591
Chris Lattner53e677a2004-04-02 20:23:17 +00002592 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002593 return getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00002594}
2595
Dan Gohman26466c02009-05-08 20:26:55 +00002596/// createNodeForGEP - Expand GEP instructions into add and multiply
2597/// operations. This allows them to be analyzed by regular SCEV code.
2598///
Dan Gohmand281ed22009-12-18 02:09:29 +00002599const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman26466c02009-05-08 20:26:55 +00002600
Dan Gohmand281ed22009-12-18 02:09:29 +00002601 bool InBounds = GEP->isInBounds();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002602 const Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohmane810b0d2009-05-08 20:36:47 +00002603 Value *Base = GEP->getOperand(0);
Dan Gohmanc63a6272009-05-09 00:14:52 +00002604 // Don't attempt to analyze GEPs over unsized objects.
2605 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2606 return getUnknown(GEP);
Dan Gohman0bba49c2009-07-07 17:06:11 +00002607 const SCEV *TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmane810b0d2009-05-08 20:36:47 +00002608 gep_type_iterator GTI = gep_type_begin(GEP);
2609 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2610 E = GEP->op_end();
Dan Gohman26466c02009-05-08 20:26:55 +00002611 I != E; ++I) {
2612 Value *Index = *I;
2613 // Compute the (potentially symbolic) offset in bytes for this index.
2614 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2615 // For a struct, add the member offset.
Dan Gohman26466c02009-05-08 20:26:55 +00002616 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Dan Gohmanc40f17b2009-08-18 16:46:41 +00002617 TotalOffset = getAddExpr(TotalOffset,
Dan Gohmand281ed22009-12-18 02:09:29 +00002618 getFieldOffsetExpr(STy, FieldNo),
2619 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002620 } else {
2621 // For an array, add the element offset, explicitly scaled.
Dan Gohman0bba49c2009-07-07 17:06:11 +00002622 const SCEV *LocalOffset = getSCEV(Index);
Dan Gohman26466c02009-05-08 20:26:55 +00002623 if (!isa<PointerType>(LocalOffset->getType()))
2624 // Getelementptr indicies are signed.
Dan Gohman85b05a22009-07-13 21:35:55 +00002625 LocalOffset = getTruncateOrSignExtend(LocalOffset, IntPtrTy);
Dan Gohmand281ed22009-12-18 02:09:29 +00002626 // Lower "inbounds" GEPs to NSW arithmetic.
Dan Gohmand281ed22009-12-18 02:09:29 +00002627 LocalOffset = getMulExpr(LocalOffset, getAllocSizeExpr(*GTI),
2628 /*HasNUW=*/false, /*HasNSW=*/InBounds);
2629 TotalOffset = getAddExpr(TotalOffset, LocalOffset,
2630 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002631 }
2632 }
Dan Gohmand281ed22009-12-18 02:09:29 +00002633 return getAddExpr(getSCEV(Base), TotalOffset,
2634 /*HasNUW=*/false, /*HasNSW=*/InBounds);
Dan Gohman26466c02009-05-08 20:26:55 +00002635}
2636
Nick Lewycky83bb0052007-11-22 07:59:40 +00002637/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2638/// guaranteed to end in (at every loop iteration). It is, at the same time,
2639/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2640/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002641uint32_t
Dan Gohman0bba49c2009-07-07 17:06:11 +00002642ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohman622ed672009-05-04 22:02:23 +00002643 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00002644 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00002645
Dan Gohman622ed672009-05-04 22:02:23 +00002646 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman2c364ad2009-06-19 23:29:04 +00002647 return std::min(GetMinTrailingZeros(T->getOperand()),
2648 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002649
Dan Gohman622ed672009-05-04 22:02:23 +00002650 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002651 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2652 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2653 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002654 }
2655
Dan Gohman622ed672009-05-04 22:02:23 +00002656 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002657 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2658 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2659 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky83bb0052007-11-22 07:59:40 +00002660 }
2661
Dan Gohman622ed672009-05-04 22:02:23 +00002662 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002663 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002664 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002665 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002666 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002667 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002668 }
2669
Dan Gohman622ed672009-05-04 22:02:23 +00002670 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002671 // The result is the sum of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002672 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2673 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky83bb0052007-11-22 07:59:40 +00002674 for (unsigned i = 1, e = M->getNumOperands();
2675 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002676 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky83bb0052007-11-22 07:59:40 +00002677 BitWidth);
2678 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002679 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002680
Dan Gohman622ed672009-05-04 22:02:23 +00002681 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00002682 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002683 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002684 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002685 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky83bb0052007-11-22 07:59:40 +00002686 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00002687 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00002688
Dan Gohman622ed672009-05-04 22:02:23 +00002689 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002690 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002691 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002692 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002693 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002694 return MinOpRes;
2695 }
2696
Dan Gohman622ed672009-05-04 22:02:23 +00002697 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky3e630762008-02-20 06:48:22 +00002698 // The result is the min of all operands results.
Dan Gohman2c364ad2009-06-19 23:29:04 +00002699 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky3e630762008-02-20 06:48:22 +00002700 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman2c364ad2009-06-19 23:29:04 +00002701 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky3e630762008-02-20 06:48:22 +00002702 return MinOpRes;
2703 }
2704
Dan Gohman2c364ad2009-06-19 23:29:04 +00002705 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2706 // For a SCEVUnknown, ask ValueTracking.
2707 unsigned BitWidth = getTypeSizeInBits(U->getType());
2708 APInt Mask = APInt::getAllOnesValue(BitWidth);
2709 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2710 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2711 return Zeros.countTrailingOnes();
2712 }
2713
2714 // SCEVUDivExpr
Nick Lewycky83bb0052007-11-22 07:59:40 +00002715 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00002716}
Chris Lattner53e677a2004-04-02 20:23:17 +00002717
Dan Gohman85b05a22009-07-13 21:35:55 +00002718/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
2719///
2720ConstantRange
2721ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002722
2723 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohman85b05a22009-07-13 21:35:55 +00002724 return ConstantRange(C->getValue()->getValue());
Dan Gohman2c364ad2009-06-19 23:29:04 +00002725
Dan Gohman85b05a22009-07-13 21:35:55 +00002726 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2727 ConstantRange X = getUnsignedRange(Add->getOperand(0));
2728 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2729 X = X.add(getUnsignedRange(Add->getOperand(i)));
2730 return X;
2731 }
2732
2733 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2734 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
2735 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2736 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
2737 return X;
2738 }
2739
2740 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2741 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
2742 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2743 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
2744 return X;
2745 }
2746
2747 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2748 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
2749 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2750 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
2751 return X;
2752 }
2753
2754 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2755 ConstantRange X = getUnsignedRange(UDiv->getLHS());
2756 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
2757 return X.udiv(Y);
2758 }
2759
2760 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2761 ConstantRange X = getUnsignedRange(ZExt->getOperand());
2762 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2763 }
2764
2765 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2766 ConstantRange X = getUnsignedRange(SExt->getOperand());
2767 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2768 }
2769
2770 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2771 ConstantRange X = getUnsignedRange(Trunc->getOperand());
2772 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2773 }
2774
2775 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2776
2777 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2778 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2779 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2780 if (!Trip) return FullSet;
2781
2782 // TODO: non-affine addrec
2783 if (AddRec->isAffine()) {
2784 const Type *Ty = AddRec->getType();
2785 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2786 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2787 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2788
2789 const SCEV *Start = AddRec->getStart();
Dan Gohmana16b5762009-07-21 00:42:47 +00002790 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohman85b05a22009-07-13 21:35:55 +00002791 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2792
2793 // Check for overflow.
Dan Gohmana16b5762009-07-21 00:42:47 +00002794 // TODO: This is very conservative.
2795 if (!(Step->isOne() &&
2796 isKnownPredicate(ICmpInst::ICMP_ULT, Start, End)) &&
2797 !(Step->isAllOnesValue() &&
2798 isKnownPredicate(ICmpInst::ICMP_UGT, Start, End)))
Dan Gohman85b05a22009-07-13 21:35:55 +00002799 return FullSet;
2800
2801 ConstantRange StartRange = getUnsignedRange(Start);
2802 ConstantRange EndRange = getUnsignedRange(End);
2803 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
2804 EndRange.getUnsignedMin());
2805 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
2806 EndRange.getUnsignedMax());
2807 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohman0d5bae42009-07-20 22:41:51 +00002808 return FullSet;
Dan Gohman85b05a22009-07-13 21:35:55 +00002809 return ConstantRange(Min, Max+1);
2810 }
2811 }
Dan Gohman2c364ad2009-06-19 23:29:04 +00002812 }
2813
2814 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2815 // For a SCEVUnknown, ask ValueTracking.
2816 unsigned BitWidth = getTypeSizeInBits(U->getType());
2817 APInt Mask = APInt::getAllOnesValue(BitWidth);
2818 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2819 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
Dan Gohman746f3b12009-07-20 22:34:18 +00002820 if (Ones == ~Zeros + 1)
2821 return FullSet;
2822 return ConstantRange(Ones, ~Zeros + 1);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002823 }
2824
Dan Gohman85b05a22009-07-13 21:35:55 +00002825 return FullSet;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002826}
2827
Dan Gohman85b05a22009-07-13 21:35:55 +00002828/// getSignedRange - Determine the signed range for a particular SCEV.
2829///
2830ConstantRange
2831ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman2c364ad2009-06-19 23:29:04 +00002832
Dan Gohman85b05a22009-07-13 21:35:55 +00002833 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2834 return ConstantRange(C->getValue()->getValue());
2835
2836 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
2837 ConstantRange X = getSignedRange(Add->getOperand(0));
2838 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
2839 X = X.add(getSignedRange(Add->getOperand(i)));
2840 return X;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002841 }
2842
Dan Gohman85b05a22009-07-13 21:35:55 +00002843 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
2844 ConstantRange X = getSignedRange(Mul->getOperand(0));
2845 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
2846 X = X.multiply(getSignedRange(Mul->getOperand(i)));
2847 return X;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002848 }
2849
Dan Gohman85b05a22009-07-13 21:35:55 +00002850 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
2851 ConstantRange X = getSignedRange(SMax->getOperand(0));
2852 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
2853 X = X.smax(getSignedRange(SMax->getOperand(i)));
2854 return X;
2855 }
Dan Gohman62849c02009-06-24 01:05:09 +00002856
Dan Gohman85b05a22009-07-13 21:35:55 +00002857 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
2858 ConstantRange X = getSignedRange(UMax->getOperand(0));
2859 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
2860 X = X.umax(getSignedRange(UMax->getOperand(i)));
2861 return X;
2862 }
Dan Gohman62849c02009-06-24 01:05:09 +00002863
Dan Gohman85b05a22009-07-13 21:35:55 +00002864 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
2865 ConstantRange X = getSignedRange(UDiv->getLHS());
2866 ConstantRange Y = getSignedRange(UDiv->getRHS());
2867 return X.udiv(Y);
2868 }
Dan Gohman62849c02009-06-24 01:05:09 +00002869
Dan Gohman85b05a22009-07-13 21:35:55 +00002870 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
2871 ConstantRange X = getSignedRange(ZExt->getOperand());
2872 return X.zeroExtend(cast<IntegerType>(ZExt->getType())->getBitWidth());
2873 }
2874
2875 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
2876 ConstantRange X = getSignedRange(SExt->getOperand());
2877 return X.signExtend(cast<IntegerType>(SExt->getType())->getBitWidth());
2878 }
2879
2880 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
2881 ConstantRange X = getSignedRange(Trunc->getOperand());
2882 return X.truncate(cast<IntegerType>(Trunc->getType())->getBitWidth());
2883 }
2884
2885 ConstantRange FullSet(getTypeSizeInBits(S->getType()), true);
2886
2887 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
2888 const SCEV *T = getBackedgeTakenCount(AddRec->getLoop());
2889 const SCEVConstant *Trip = dyn_cast<SCEVConstant>(T);
2890 if (!Trip) return FullSet;
2891
2892 // TODO: non-affine addrec
2893 if (AddRec->isAffine()) {
2894 const Type *Ty = AddRec->getType();
2895 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
2896 if (getTypeSizeInBits(MaxBECount->getType()) <= getTypeSizeInBits(Ty)) {
2897 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
2898
2899 const SCEV *Start = AddRec->getStart();
2900 const SCEV *Step = AddRec->getStepRecurrence(*this);
2901 const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
2902
2903 // Check for overflow.
Dan Gohmana16b5762009-07-21 00:42:47 +00002904 // TODO: This is very conservative.
2905 if (!(Step->isOne() &&
Dan Gohman85b05a22009-07-13 21:35:55 +00002906 isKnownPredicate(ICmpInst::ICMP_SLT, Start, End)) &&
Dan Gohmana16b5762009-07-21 00:42:47 +00002907 !(Step->isAllOnesValue() &&
Dan Gohman85b05a22009-07-13 21:35:55 +00002908 isKnownPredicate(ICmpInst::ICMP_SGT, Start, End)))
2909 return FullSet;
2910
2911 ConstantRange StartRange = getSignedRange(Start);
2912 ConstantRange EndRange = getSignedRange(End);
2913 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
2914 EndRange.getSignedMin());
2915 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
2916 EndRange.getSignedMax());
2917 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmanc268e7c2009-07-21 00:37:45 +00002918 return FullSet;
Dan Gohman85b05a22009-07-13 21:35:55 +00002919 return ConstantRange(Min, Max+1);
Dan Gohman62849c02009-06-24 01:05:09 +00002920 }
Dan Gohman62849c02009-06-24 01:05:09 +00002921 }
Dan Gohman62849c02009-06-24 01:05:09 +00002922 }
2923
Dan Gohman2c364ad2009-06-19 23:29:04 +00002924 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2925 // For a SCEVUnknown, ask ValueTracking.
Dan Gohman85b05a22009-07-13 21:35:55 +00002926 unsigned BitWidth = getTypeSizeInBits(U->getType());
2927 unsigned NS = ComputeNumSignBits(U->getValue(), TD);
2928 if (NS == 1)
2929 return FullSet;
2930 return
2931 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
2932 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1);
Dan Gohman2c364ad2009-06-19 23:29:04 +00002933 }
2934
Dan Gohman85b05a22009-07-13 21:35:55 +00002935 return FullSet;
Dan Gohman2c364ad2009-06-19 23:29:04 +00002936}
2937
Chris Lattner53e677a2004-04-02 20:23:17 +00002938/// createSCEV - We know that there is no SCEV for the specified value.
2939/// Analyze the expression.
2940///
Dan Gohman0bba49c2009-07-07 17:06:11 +00002941const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanaf79fb52009-04-21 01:07:12 +00002942 if (!isSCEVable(V->getType()))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002943 return getUnknown(V);
Dan Gohman2d1be872009-04-16 03:18:22 +00002944
Dan Gohman6c459a22008-06-22 19:56:46 +00002945 unsigned Opcode = Instruction::UserOp1;
2946 if (Instruction *I = dyn_cast<Instruction>(V))
2947 Opcode = I->getOpcode();
2948 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2949 Opcode = CE->getOpcode();
Dan Gohman6bbcba12009-06-24 00:54:57 +00002950 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2951 return getConstant(CI);
2952 else if (isa<ConstantPointerNull>(V))
2953 return getIntegerSCEV(0, V->getType());
2954 else if (isa<UndefValue>(V))
2955 return getIntegerSCEV(0, V->getType());
Dan Gohman26812322009-08-25 17:49:57 +00002956 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
2957 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman6c459a22008-06-22 19:56:46 +00002958 else
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002959 return getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00002960
Dan Gohmanca178902009-07-17 20:47:02 +00002961 Operator *U = cast<Operator>(V);
Dan Gohman6c459a22008-06-22 19:56:46 +00002962 switch (Opcode) {
Dan Gohman7a721952009-10-09 16:35:06 +00002963 case Instruction::Add:
2964 // Don't transfer the NSW and NUW bits from the Add instruction to the
2965 // Add expression, because the Instruction may be guarded by control
2966 // flow and the no-overflow bits may not be valid for the expression in
2967 // any context.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002968 return getAddExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00002969 getSCEV(U->getOperand(1)));
2970 case Instruction::Mul:
2971 // Don't transfer the NSW and NUW bits from the Mul instruction to the
2972 // Mul expression, as with Add.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002973 return getMulExpr(getSCEV(U->getOperand(0)),
Dan Gohman7a721952009-10-09 16:35:06 +00002974 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002975 case Instruction::UDiv:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002976 return getUDivExpr(getSCEV(U->getOperand(0)),
2977 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00002978 case Instruction::Sub:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00002979 return getMinusSCEV(getSCEV(U->getOperand(0)),
2980 getSCEV(U->getOperand(1)));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002981 case Instruction::And:
2982 // For an expression like x&255 that merely masks off the high bits,
2983 // use zext(trunc(x)) as the SCEV expression.
2984 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00002985 if (CI->isNullValue())
2986 return getSCEV(U->getOperand(1));
Dan Gohmand6c32952009-04-27 01:41:10 +00002987 if (CI->isAllOnesValue())
2988 return getSCEV(U->getOperand(0));
Dan Gohman4ee29af2009-04-21 02:26:00 +00002989 const APInt &A = CI->getValue();
Dan Gohman61ffa8e2009-06-16 19:52:01 +00002990
2991 // Instcombine's ShrinkDemandedConstant may strip bits out of
2992 // constants, obscuring what would otherwise be a low-bits mask.
2993 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2994 // knew about to reconstruct a low-bits mask value.
2995 unsigned LZ = A.countLeadingZeros();
2996 unsigned BitWidth = A.getBitWidth();
2997 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2998 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2999 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
3000
3001 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
3002
Dan Gohmanfc3641b2009-06-17 23:54:37 +00003003 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman4ee29af2009-04-21 02:26:00 +00003004 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003005 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003006 IntegerType::get(getContext(), BitWidth - LZ)),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003007 U->getType());
Dan Gohman4ee29af2009-04-21 02:26:00 +00003008 }
3009 break;
Dan Gohman61ffa8e2009-06-16 19:52:01 +00003010
Dan Gohman6c459a22008-06-22 19:56:46 +00003011 case Instruction::Or:
3012 // If the RHS of the Or is a constant, we may have something like:
3013 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
3014 // optimizations will transparently handle this case.
3015 //
3016 // In order for this transformation to be safe, the LHS must be of the
3017 // form X*(2^n) and the Or constant must be less than 2^n.
3018 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003019 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman6c459a22008-06-22 19:56:46 +00003020 const APInt &CIVal = CI->getValue();
Dan Gohman2c364ad2009-06-19 23:29:04 +00003021 if (GetMinTrailingZeros(LHS) >=
Dan Gohman1f96e672009-09-17 18:05:20 +00003022 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
3023 // Build a plain add SCEV.
3024 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
3025 // If the LHS of the add was an addrec and it has no-wrap flags,
3026 // transfer the no-wrap flags, since an or won't introduce a wrap.
3027 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
3028 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
3029 if (OldAR->hasNoUnsignedWrap())
3030 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoUnsignedWrap(true);
3031 if (OldAR->hasNoSignedWrap())
3032 const_cast<SCEVAddRecExpr *>(NewAR)->setHasNoSignedWrap(true);
3033 }
3034 return S;
3035 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003036 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003037 break;
3038 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00003039 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00003040 // If the RHS of the xor is a signbit, then this is just an add.
3041 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00003042 if (CI->getValue().isSignBit())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003043 return getAddExpr(getSCEV(U->getOperand(0)),
3044 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003045
3046 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman0bac95e2009-05-18 16:17:44 +00003047 if (CI->isAllOnesValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003048 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman10978bd2009-05-18 16:29:04 +00003049
3050 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
3051 // This is a variant of the check for xor with -1, and it handles
3052 // the case where instcombine has trimmed non-demanded bits out
3053 // of an xor with -1.
3054 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
3055 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
3056 if (BO->getOpcode() == Instruction::And &&
3057 LCI->getValue() == CI->getValue())
3058 if (const SCEVZeroExtendExpr *Z =
Dan Gohman3034c102009-06-17 01:22:39 +00003059 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohman82052832009-06-18 00:00:20 +00003060 const Type *UTy = U->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00003061 const SCEV *Z0 = Z->getOperand();
Dan Gohman82052832009-06-18 00:00:20 +00003062 const Type *Z0Ty = Z0->getType();
3063 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
3064
3065 // If C is a low-bits mask, the zero extend is zerving to
3066 // mask off the high bits. Complement the operand and
3067 // re-apply the zext.
3068 if (APIntOps::isMask(Z0TySize, CI->getValue()))
3069 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
3070
3071 // If C is a single bit, it may be in the sign-bit position
3072 // before the zero-extend. In this case, represent the xor
3073 // using an add, which is equivalent, and re-apply the zext.
3074 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
3075 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
3076 Trunc.isSignBit())
3077 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
3078 UTy);
Dan Gohman3034c102009-06-17 01:22:39 +00003079 }
Dan Gohman6c459a22008-06-22 19:56:46 +00003080 }
3081 break;
3082
3083 case Instruction::Shl:
3084 // Turn shift left of a constant amount into a multiply.
3085 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3086 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003087 Constant *X = ConstantInt::get(getContext(),
Dan Gohman6c459a22008-06-22 19:56:46 +00003088 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003089 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman6c459a22008-06-22 19:56:46 +00003090 }
3091 break;
3092
Nick Lewycky01eaf802008-07-07 06:15:49 +00003093 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00003094 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00003095 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
3096 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Owen Andersoneed707b2009-07-24 23:12:02 +00003097 Constant *X = ConstantInt::get(getContext(),
Nick Lewycky01eaf802008-07-07 06:15:49 +00003098 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003099 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky01eaf802008-07-07 06:15:49 +00003100 }
3101 break;
3102
Dan Gohman4ee29af2009-04-21 02:26:00 +00003103 case Instruction::AShr:
3104 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
3105 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
3106 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
3107 if (L->getOpcode() == Instruction::Shl &&
3108 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman2c73d5f2009-04-25 17:05:40 +00003109 unsigned BitWidth = getTypeSizeInBits(U->getType());
3110 uint64_t Amt = BitWidth - CI->getZExtValue();
3111 if (Amt == BitWidth)
3112 return getSCEV(L->getOperand(0)); // shift by zero --> noop
3113 if (Amt > BitWidth)
3114 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman4ee29af2009-04-21 02:26:00 +00003115 return
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003116 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Owen Anderson1d0be152009-08-13 21:58:54 +00003117 IntegerType::get(getContext(), Amt)),
Dan Gohman4ee29af2009-04-21 02:26:00 +00003118 U->getType());
3119 }
3120 break;
3121
Dan Gohman6c459a22008-06-22 19:56:46 +00003122 case Instruction::Trunc:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003123 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003124
3125 case Instruction::ZExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003126 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003127
3128 case Instruction::SExt:
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003129 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman6c459a22008-06-22 19:56:46 +00003130
3131 case Instruction::BitCast:
3132 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00003133 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman6c459a22008-06-22 19:56:46 +00003134 return getSCEV(U->getOperand(0));
3135 break;
3136
Dan Gohmanf2411742009-07-20 17:43:30 +00003137 // It's tempting to handle inttoptr and ptrtoint, however this can
3138 // lead to pointer expressions which cannot be expanded to GEPs
3139 // (because they may overflow). For now, the only pointer-typed
3140 // expressions we handle are GEPs and address literals.
Dan Gohman2d1be872009-04-16 03:18:22 +00003141
Dan Gohman26466c02009-05-08 20:26:55 +00003142 case Instruction::GetElementPtr:
Dan Gohmand281ed22009-12-18 02:09:29 +00003143 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman2d1be872009-04-16 03:18:22 +00003144
Dan Gohman6c459a22008-06-22 19:56:46 +00003145 case Instruction::PHI:
3146 return createNodeForPHI(cast<PHINode>(U));
3147
3148 case Instruction::Select:
3149 // This could be a smax or umax that was lowered earlier.
3150 // Try to recover it.
3151 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
3152 Value *LHS = ICI->getOperand(0);
3153 Value *RHS = ICI->getOperand(1);
3154 switch (ICI->getPredicate()) {
3155 case ICmpInst::ICMP_SLT:
3156 case ICmpInst::ICMP_SLE:
3157 std::swap(LHS, RHS);
3158 // fall through
3159 case ICmpInst::ICMP_SGT:
3160 case ICmpInst::ICMP_SGE:
3161 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003162 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003163 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003164 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003165 break;
3166 case ICmpInst::ICMP_ULT:
3167 case ICmpInst::ICMP_ULE:
3168 std::swap(LHS, RHS);
3169 // fall through
3170 case ICmpInst::ICMP_UGT:
3171 case ICmpInst::ICMP_UGE:
3172 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003173 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003174 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmanf9a9a992009-06-22 03:18:45 +00003175 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman6c459a22008-06-22 19:56:46 +00003176 break;
Dan Gohman30fb5122009-06-18 20:21:07 +00003177 case ICmpInst::ICMP_NE:
3178 // n != 0 ? n : 1 -> umax(n, 1)
3179 if (LHS == U->getOperand(1) &&
3180 isa<ConstantInt>(U->getOperand(2)) &&
3181 cast<ConstantInt>(U->getOperand(2))->isOne() &&
3182 isa<ConstantInt>(RHS) &&
3183 cast<ConstantInt>(RHS)->isZero())
3184 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
3185 break;
3186 case ICmpInst::ICMP_EQ:
3187 // n == 0 ? 1 : n -> umax(n, 1)
3188 if (LHS == U->getOperand(2) &&
3189 isa<ConstantInt>(U->getOperand(1)) &&
3190 cast<ConstantInt>(U->getOperand(1))->isOne() &&
3191 isa<ConstantInt>(RHS) &&
3192 cast<ConstantInt>(RHS)->isZero())
3193 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
3194 break;
Dan Gohman6c459a22008-06-22 19:56:46 +00003195 default:
3196 break;
3197 }
3198 }
3199
3200 default: // We cannot analyze this expression.
3201 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003202 }
3203
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003204 return getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003205}
3206
3207
3208
3209//===----------------------------------------------------------------------===//
3210// Iteration Count Computation Code
3211//
3212
Dan Gohman46bdfb02009-02-24 18:55:53 +00003213/// getBackedgeTakenCount - If the specified loop has a predictable
3214/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
3215/// object. The backedge-taken count is the number of times the loop header
3216/// will be branched to from within the loop. This is one less than the
3217/// trip count of the loop, since it doesn't count the first iteration,
3218/// when the header is branched to from outside the loop.
3219///
3220/// Note that it is not valid to call this method on a loop without a
3221/// loop-invariant backedge-taken count (see
3222/// hasLoopInvariantBackedgeTakenCount).
3223///
Dan Gohman0bba49c2009-07-07 17:06:11 +00003224const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003225 return getBackedgeTakenInfo(L).Exact;
3226}
3227
3228/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
3229/// return the least SCEV value that is known never to be less than the
3230/// actual backedge taken count.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003231const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003232 return getBackedgeTakenInfo(L).Max;
3233}
3234
Dan Gohman59ae6b92009-07-08 19:23:34 +00003235/// PushLoopPHIs - Push PHI nodes in the header of the given loop
3236/// onto the given Worklist.
3237static void
3238PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
3239 BasicBlock *Header = L->getHeader();
3240
3241 // Push all Loop-header PHIs onto the Worklist stack.
3242 for (BasicBlock::iterator I = Header->begin();
3243 PHINode *PN = dyn_cast<PHINode>(I); ++I)
3244 Worklist.push_back(PN);
3245}
3246
Dan Gohmana1af7572009-04-30 20:47:05 +00003247const ScalarEvolution::BackedgeTakenInfo &
3248ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohman01ecca22009-04-27 20:16:15 +00003249 // Initially insert a CouldNotCompute for this loop. If the insertion
3250 // succeeds, procede to actually compute a backedge-taken count and
3251 // update the value. The temporary CouldNotCompute value tells SCEV
3252 // code elsewhere that it shouldn't attempt to request a new
3253 // backedge-taken count, which could result in infinite recursion.
Dan Gohman5d984912009-12-18 01:14:11 +00003254 std::pair<std::map<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohman01ecca22009-04-27 20:16:15 +00003255 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
3256 if (Pair.second) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003257 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman1c343752009-06-27 21:21:31 +00003258 if (ItCount.Exact != getCouldNotCompute()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00003259 assert(ItCount.Exact->isLoopInvariant(L) &&
3260 ItCount.Max->isLoopInvariant(L) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00003261 "Computed trip count isn't loop invariant for loop!");
3262 ++NumTripCountsComputed;
Dan Gohman01ecca22009-04-27 20:16:15 +00003263
Dan Gohman01ecca22009-04-27 20:16:15 +00003264 // Update the value in the map.
3265 Pair.first->second = ItCount;
Dan Gohmana334aa72009-06-22 00:31:57 +00003266 } else {
Dan Gohman1c343752009-06-27 21:21:31 +00003267 if (ItCount.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003268 // Update the value in the map.
3269 Pair.first->second = ItCount;
3270 if (isa<PHINode>(L->getHeader()->begin()))
3271 // Only count loops that have phi nodes as not being computable.
3272 ++NumTripCountsNotComputed;
Chris Lattner53e677a2004-04-02 20:23:17 +00003273 }
Dan Gohmana1af7572009-04-30 20:47:05 +00003274
3275 // Now that we know more about the trip count for this loop, forget any
3276 // existing SCEV values for PHI nodes in this loop since they are only
Dan Gohman59ae6b92009-07-08 19:23:34 +00003277 // conservative estimates made without the benefit of trip count
Dan Gohman4c7279a2009-10-31 15:04:55 +00003278 // information. This is similar to the code in forgetLoop, except that
3279 // it handles SCEVUnknown PHI nodes specially.
Dan Gohman59ae6b92009-07-08 19:23:34 +00003280 if (ItCount.hasAnyInfo()) {
3281 SmallVector<Instruction *, 16> Worklist;
3282 PushLoopPHIs(L, Worklist);
3283
3284 SmallPtrSet<Instruction *, 8> Visited;
3285 while (!Worklist.empty()) {
3286 Instruction *I = Worklist.pop_back_val();
3287 if (!Visited.insert(I)) continue;
3288
Dan Gohman5d984912009-12-18 01:14:11 +00003289 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003290 Scalars.find(static_cast<Value *>(I));
3291 if (It != Scalars.end()) {
3292 // SCEVUnknown for a PHI either means that it has an unrecognized
3293 // structure, or it's a PHI that's in the progress of being computed
Dan Gohmanba701882009-07-13 22:04:06 +00003294 // by createNodeForPHI. In the former case, additional loop trip
3295 // count information isn't going to change anything. In the later
3296 // case, createNodeForPHI will perform the necessary updates on its
3297 // own when it gets to that point.
Dan Gohman42214892009-08-31 21:15:23 +00003298 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(It->second)) {
3299 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003300 Scalars.erase(It);
Dan Gohman42214892009-08-31 21:15:23 +00003301 }
Dan Gohman59ae6b92009-07-08 19:23:34 +00003302 if (PHINode *PN = dyn_cast<PHINode>(I))
3303 ConstantEvolutionLoopExitValue.erase(PN);
3304 }
3305
3306 PushDefUseChildren(I, Worklist);
3307 }
3308 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003309 }
Dan Gohman01ecca22009-04-27 20:16:15 +00003310 return Pair.first->second;
Chris Lattner53e677a2004-04-02 20:23:17 +00003311}
3312
Dan Gohman4c7279a2009-10-31 15:04:55 +00003313/// forgetLoop - This method should be called by the client when it has
3314/// changed a loop in a way that may effect ScalarEvolution's ability to
3315/// compute a trip count, or if the loop is deleted.
3316void ScalarEvolution::forgetLoop(const Loop *L) {
3317 // Drop any stored trip count value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003318 BackedgeTakenCounts.erase(L);
Dan Gohmanfb7d35f2009-05-02 17:43:35 +00003319
Dan Gohman4c7279a2009-10-31 15:04:55 +00003320 // Drop information about expressions based on loop-header PHIs.
Dan Gohman35738ac2009-05-04 22:30:44 +00003321 SmallVector<Instruction *, 16> Worklist;
Dan Gohman59ae6b92009-07-08 19:23:34 +00003322 PushLoopPHIs(L, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003323
Dan Gohman59ae6b92009-07-08 19:23:34 +00003324 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00003325 while (!Worklist.empty()) {
3326 Instruction *I = Worklist.pop_back_val();
Dan Gohman59ae6b92009-07-08 19:23:34 +00003327 if (!Visited.insert(I)) continue;
3328
Dan Gohman5d984912009-12-18 01:14:11 +00003329 std::map<SCEVCallbackVH, const SCEV *>::iterator It =
Dan Gohman59ae6b92009-07-08 19:23:34 +00003330 Scalars.find(static_cast<Value *>(I));
3331 if (It != Scalars.end()) {
Dan Gohman42214892009-08-31 21:15:23 +00003332 ValuesAtScopes.erase(It->second);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003333 Scalars.erase(It);
Dan Gohman59ae6b92009-07-08 19:23:34 +00003334 if (PHINode *PN = dyn_cast<PHINode>(I))
3335 ConstantEvolutionLoopExitValue.erase(PN);
3336 }
3337
3338 PushDefUseChildren(I, Worklist);
Dan Gohman35738ac2009-05-04 22:30:44 +00003339 }
Dan Gohman60f8a632009-02-17 20:49:49 +00003340}
3341
Dan Gohman46bdfb02009-02-24 18:55:53 +00003342/// ComputeBackedgeTakenCount - Compute the number of times the backedge
3343/// of the specified loop will execute.
Dan Gohmana1af7572009-04-30 20:47:05 +00003344ScalarEvolution::BackedgeTakenInfo
3345ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman5d984912009-12-18 01:14:11 +00003346 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohmana334aa72009-06-22 00:31:57 +00003347 L->getExitingBlocks(ExitingBlocks);
Chris Lattner53e677a2004-04-02 20:23:17 +00003348
Dan Gohmana334aa72009-06-22 00:31:57 +00003349 // Examine all exits and pick the most conservative values.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003350 const SCEV *BECount = getCouldNotCompute();
3351 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003352 bool CouldNotComputeBECount = false;
Dan Gohmana334aa72009-06-22 00:31:57 +00003353 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
3354 BackedgeTakenInfo NewBTI =
3355 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Chris Lattner53e677a2004-04-02 20:23:17 +00003356
Dan Gohman1c343752009-06-27 21:21:31 +00003357 if (NewBTI.Exact == getCouldNotCompute()) {
Dan Gohmana334aa72009-06-22 00:31:57 +00003358 // We couldn't compute an exact value for this exit, so
Dan Gohmand32f5bf2009-06-22 21:10:22 +00003359 // we won't be able to compute an exact value for the loop.
Dan Gohmana334aa72009-06-22 00:31:57 +00003360 CouldNotComputeBECount = true;
Dan Gohman1c343752009-06-27 21:21:31 +00003361 BECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003362 } else if (!CouldNotComputeBECount) {
Dan Gohman1c343752009-06-27 21:21:31 +00003363 if (BECount == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003364 BECount = NewBTI.Exact;
Dan Gohmana334aa72009-06-22 00:31:57 +00003365 else
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003366 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohmana334aa72009-06-22 00:31:57 +00003367 }
Dan Gohman1c343752009-06-27 21:21:31 +00003368 if (MaxBECount == getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003369 MaxBECount = NewBTI.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003370 else if (NewBTI.Max != getCouldNotCompute())
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003371 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003372 }
3373
3374 return BackedgeTakenInfo(BECount, MaxBECount);
3375}
3376
3377/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
3378/// of the specified loop will execute if it exits via the specified block.
3379ScalarEvolution::BackedgeTakenInfo
3380ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
3381 BasicBlock *ExitingBlock) {
3382
3383 // Okay, we've chosen an exiting block. See what condition causes us to
3384 // exit at this block.
Chris Lattner53e677a2004-04-02 20:23:17 +00003385 //
3386 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00003387 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman1c343752009-06-27 21:21:31 +00003388 if (ExitBr == 0) return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003389 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman64a845e2009-06-24 04:48:43 +00003390
Chris Lattner8b0e3602007-01-07 02:24:26 +00003391 // At this point, we know we have a conditional branch that determines whether
3392 // the loop is exited. However, we don't know if the branch is executed each
3393 // time through the loop. If not, then the execution count of the branch will
3394 // not be equal to the trip count of the loop.
3395 //
3396 // Currently we check for this by checking to see if the Exit branch goes to
3397 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00003398 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohmana334aa72009-06-22 00:31:57 +00003399 // loop header. This is common for un-rotated loops.
3400 //
3401 // If both of those tests fail, walk up the unique predecessor chain to the
3402 // header, stopping if there is an edge that doesn't exit the loop. If the
3403 // header is reached, the execution count of the branch will be equal to the
3404 // trip count of the loop.
3405 //
3406 // More extensive analysis could be done to handle more cases here.
3407 //
Chris Lattner8b0e3602007-01-07 02:24:26 +00003408 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00003409 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohmana334aa72009-06-22 00:31:57 +00003410 ExitBr->getParent() != L->getHeader()) {
3411 // The simple checks failed, try climbing the unique predecessor chain
3412 // up to the header.
3413 bool Ok = false;
3414 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
3415 BasicBlock *Pred = BB->getUniquePredecessor();
3416 if (!Pred)
Dan Gohman1c343752009-06-27 21:21:31 +00003417 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003418 TerminatorInst *PredTerm = Pred->getTerminator();
3419 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
3420 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
3421 if (PredSucc == BB)
3422 continue;
3423 // If the predecessor has a successor that isn't BB and isn't
3424 // outside the loop, assume the worst.
3425 if (L->contains(PredSucc))
Dan Gohman1c343752009-06-27 21:21:31 +00003426 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003427 }
3428 if (Pred == L->getHeader()) {
3429 Ok = true;
3430 break;
3431 }
3432 BB = Pred;
3433 }
3434 if (!Ok)
Dan Gohman1c343752009-06-27 21:21:31 +00003435 return getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003436 }
3437
3438 // Procede to the next level to examine the exit condition expression.
3439 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
3440 ExitBr->getSuccessor(0),
3441 ExitBr->getSuccessor(1));
3442}
3443
3444/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
3445/// backedge of the specified loop will execute if its exit condition
3446/// were a conditional branch of ExitCond, TBB, and FBB.
3447ScalarEvolution::BackedgeTakenInfo
3448ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
3449 Value *ExitCond,
3450 BasicBlock *TBB,
3451 BasicBlock *FBB) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00003452 // Check if the controlling expression for this loop is an And or Or.
Dan Gohmana334aa72009-06-22 00:31:57 +00003453 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
3454 if (BO->getOpcode() == Instruction::And) {
3455 // Recurse on the operands of the and.
3456 BackedgeTakenInfo BTI0 =
3457 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3458 BackedgeTakenInfo BTI1 =
3459 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003460 const SCEV *BECount = getCouldNotCompute();
3461 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003462 if (L->contains(TBB)) {
3463 // Both conditions must be true for the loop to continue executing.
3464 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003465 if (BTI0.Exact == getCouldNotCompute() ||
3466 BTI1.Exact == getCouldNotCompute())
3467 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003468 else
3469 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003470 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003471 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003472 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003473 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003474 else
3475 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003476 } else {
3477 // Both conditions must be true for the loop to exit.
3478 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003479 if (BTI0.Exact != getCouldNotCompute() &&
3480 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003481 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003482 if (BTI0.Max != getCouldNotCompute() &&
3483 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003484 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3485 }
3486
3487 return BackedgeTakenInfo(BECount, MaxBECount);
3488 }
3489 if (BO->getOpcode() == Instruction::Or) {
3490 // Recurse on the operands of the or.
3491 BackedgeTakenInfo BTI0 =
3492 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
3493 BackedgeTakenInfo BTI1 =
3494 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Dan Gohman0bba49c2009-07-07 17:06:11 +00003495 const SCEV *BECount = getCouldNotCompute();
3496 const SCEV *MaxBECount = getCouldNotCompute();
Dan Gohmana334aa72009-06-22 00:31:57 +00003497 if (L->contains(FBB)) {
3498 // Both conditions must be false for the loop to continue executing.
3499 // Choose the less conservative count.
Dan Gohman1c343752009-06-27 21:21:31 +00003500 if (BTI0.Exact == getCouldNotCompute() ||
3501 BTI1.Exact == getCouldNotCompute())
3502 BECount = getCouldNotCompute();
Dan Gohman60e9b072009-06-22 15:09:28 +00003503 else
3504 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003505 if (BTI0.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003506 MaxBECount = BTI1.Max;
Dan Gohman1c343752009-06-27 21:21:31 +00003507 else if (BTI1.Max == getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003508 MaxBECount = BTI0.Max;
Dan Gohman60e9b072009-06-22 15:09:28 +00003509 else
3510 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohmana334aa72009-06-22 00:31:57 +00003511 } else {
3512 // Both conditions must be false for the loop to exit.
3513 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Dan Gohman1c343752009-06-27 21:21:31 +00003514 if (BTI0.Exact != getCouldNotCompute() &&
3515 BTI1.Exact != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003516 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman1c343752009-06-27 21:21:31 +00003517 if (BTI0.Max != getCouldNotCompute() &&
3518 BTI1.Max != getCouldNotCompute())
Dan Gohmana334aa72009-06-22 00:31:57 +00003519 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
3520 }
3521
3522 return BackedgeTakenInfo(BECount, MaxBECount);
3523 }
3524 }
3525
3526 // With an icmp, it may be feasible to compute an exact backedge-taken count.
3527 // Procede to the next level to examine the icmp.
3528 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
3529 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003530
Eli Friedman361e54d2009-05-09 12:32:42 +00003531 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohmana334aa72009-06-22 00:31:57 +00003532 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
3533}
3534
3535/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
3536/// backedge of the specified loop will execute if its exit condition
3537/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
3538ScalarEvolution::BackedgeTakenInfo
3539ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
3540 ICmpInst *ExitCond,
3541 BasicBlock *TBB,
3542 BasicBlock *FBB) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003543
Reid Spencere4d87aa2006-12-23 06:05:41 +00003544 // If the condition was exit on true, convert the condition to exit on false
3545 ICmpInst::Predicate Cond;
Dan Gohmana334aa72009-06-22 00:31:57 +00003546 if (!L->contains(FBB))
Reid Spencere4d87aa2006-12-23 06:05:41 +00003547 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003548 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00003549 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00003550
3551 // Handle common loops like: for (X = "string"; *X; ++X)
3552 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
3553 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003554 const SCEV *ItCnt =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003555 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmana334aa72009-06-22 00:31:57 +00003556 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
3557 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
3558 return BackedgeTakenInfo(ItCnt,
3559 isa<SCEVConstant>(ItCnt) ? ItCnt :
3560 getConstant(APInt::getMaxValue(BitWidth)-1));
3561 }
Chris Lattner673e02b2004-10-12 01:49:27 +00003562 }
3563
Dan Gohman0bba49c2009-07-07 17:06:11 +00003564 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
3565 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattner53e677a2004-04-02 20:23:17 +00003566
3567 // Try to evaluate any dependencies out of the loop.
Dan Gohmand594e6f2009-05-24 23:25:42 +00003568 LHS = getSCEVAtScope(LHS, L);
3569 RHS = getSCEVAtScope(RHS, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00003570
Dan Gohman64a845e2009-06-24 04:48:43 +00003571 // At this point, we would like to compute how many iterations of the
Reid Spencere4d87aa2006-12-23 06:05:41 +00003572 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00003573 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3574 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00003575 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003576 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00003577 }
3578
Chris Lattner53e677a2004-04-02 20:23:17 +00003579 // If we have a comparison of a chrec against a constant, try to use value
3580 // ranges to answer this query.
Dan Gohman622ed672009-05-04 22:02:23 +00003581 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3582 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattner53e677a2004-04-02 20:23:17 +00003583 if (AddRec->getLoop() == L) {
Eli Friedman361e54d2009-05-09 12:32:42 +00003584 // Form the constant range.
3585 ConstantRange CompRange(
3586 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003587
Dan Gohman0bba49c2009-07-07 17:06:11 +00003588 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman361e54d2009-05-09 12:32:42 +00003589 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattner53e677a2004-04-02 20:23:17 +00003590 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003591
Chris Lattner53e677a2004-04-02 20:23:17 +00003592 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003593 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00003594 // Convert to: while (X-Y != 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003595 const SCEV *TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003596 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003597 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003598 }
Dan Gohman4c0d5d52009-08-20 16:42:55 +00003599 case ICmpInst::ICMP_EQ: { // while (X == Y)
3600 // Convert to: while (X-Y == 0)
Dan Gohman0bba49c2009-07-07 17:06:11 +00003601 const SCEV *TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003602 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00003603 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003604 }
3605 case ICmpInst::ICMP_SLT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003606 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3607 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003608 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003609 }
3610 case ICmpInst::ICMP_SGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003611 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3612 getNotSCEV(RHS), L, true);
3613 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003614 break;
3615 }
3616 case ICmpInst::ICMP_ULT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003617 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3618 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00003619 break;
3620 }
3621 case ICmpInst::ICMP_UGT: {
Dan Gohmana1af7572009-04-30 20:47:05 +00003622 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3623 getNotSCEV(RHS), L, false);
3624 if (BTI.hasAnyInfo()) return BTI;
Chris Lattnerdb25de42005-08-15 23:33:51 +00003625 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003626 }
Chris Lattner53e677a2004-04-02 20:23:17 +00003627 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003628#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003629 errs() << "ComputeBackedgeTakenCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003630 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003631 errs() << "[unsigned] ";
3632 errs() << *LHS << " "
Dan Gohman64a845e2009-06-24 04:48:43 +00003633 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencere4d87aa2006-12-23 06:05:41 +00003634 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00003635#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00003636 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00003637 }
Dan Gohman46bdfb02009-02-24 18:55:53 +00003638 return
Dan Gohmana334aa72009-06-22 00:31:57 +00003639 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner7980fb92004-04-17 18:36:24 +00003640}
3641
Chris Lattner673e02b2004-10-12 01:49:27 +00003642static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00003643EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3644 ScalarEvolution &SE) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00003645 const SCEV *InVal = SE.getConstant(C);
3646 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00003647 assert(isa<SCEVConstant>(Val) &&
3648 "Evaluation of SCEV at constant didn't fold correctly?");
3649 return cast<SCEVConstant>(Val)->getValue();
3650}
3651
3652/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3653/// and a GEP expression (missing the pointer index) indexing into it, return
3654/// the addressed element of the initializer or null if the index expression is
3655/// invalid.
3656static Constant *
Nick Lewyckyc6501b12009-11-23 03:26:09 +00003657GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00003658 const std::vector<ConstantInt*> &Indices) {
3659 Constant *Init = GV->getInitializer();
3660 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003661 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00003662 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3663 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3664 Init = cast<Constant>(CS->getOperand(Idx));
3665 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3666 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3667 Init = cast<Constant>(CA->getOperand(Idx));
3668 } else if (isa<ConstantAggregateZero>(Init)) {
3669 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3670 assert(Idx < STy->getNumElements() && "Bad struct index!");
Owen Andersona7235ea2009-07-31 20:28:14 +00003671 Init = Constant::getNullValue(STy->getElementType(Idx));
Chris Lattner673e02b2004-10-12 01:49:27 +00003672 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3673 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
Owen Andersona7235ea2009-07-31 20:28:14 +00003674 Init = Constant::getNullValue(ATy->getElementType());
Chris Lattner673e02b2004-10-12 01:49:27 +00003675 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +00003676 llvm_unreachable("Unknown constant aggregate type!");
Chris Lattner673e02b2004-10-12 01:49:27 +00003677 }
3678 return 0;
3679 } else {
3680 return 0; // Unknown initializer type
3681 }
3682 }
3683 return Init;
3684}
3685
Dan Gohman46bdfb02009-02-24 18:55:53 +00003686/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3687/// 'icmp op load X, cst', try to see if we can compute the backedge
3688/// execution count.
Dan Gohman64a845e2009-06-24 04:48:43 +00003689const SCEV *
3690ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3691 LoadInst *LI,
3692 Constant *RHS,
3693 const Loop *L,
3694 ICmpInst::Predicate predicate) {
Dan Gohman1c343752009-06-27 21:21:31 +00003695 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003696
3697 // Check to see if the loaded pointer is a getelementptr of a global.
3698 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman1c343752009-06-27 21:21:31 +00003699 if (!GEP) return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003700
3701 // Make sure that it is really a constant global we are gepping, with an
3702 // initializer, and make sure the first IDX is really 0.
3703 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman82555732009-08-19 18:20:44 +00003704 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattner673e02b2004-10-12 01:49:27 +00003705 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3706 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman1c343752009-06-27 21:21:31 +00003707 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003708
3709 // Okay, we allow one non-constant index into the GEP instruction.
3710 Value *VarIdx = 0;
3711 std::vector<ConstantInt*> Indexes;
3712 unsigned VarIdxNum = 0;
3713 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3714 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3715 Indexes.push_back(CI);
3716 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman1c343752009-06-27 21:21:31 +00003717 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattner673e02b2004-10-12 01:49:27 +00003718 VarIdx = GEP->getOperand(i);
3719 VarIdxNum = i-2;
3720 Indexes.push_back(0);
3721 }
3722
3723 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3724 // Check to see if X is a loop variant variable value now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003725 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohmand594e6f2009-05-24 23:25:42 +00003726 Idx = getSCEVAtScope(Idx, L);
Chris Lattner673e02b2004-10-12 01:49:27 +00003727
3728 // We can only recognize very limited forms of loop index expressions, in
3729 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman35738ac2009-05-04 22:30:44 +00003730 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Chris Lattner673e02b2004-10-12 01:49:27 +00003731 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3732 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3733 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman1c343752009-06-27 21:21:31 +00003734 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003735
3736 unsigned MaxSteps = MaxBruteForceIterations;
3737 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003738 ConstantInt *ItCst = ConstantInt::get(
Owen Anderson9adc0ab2009-07-14 23:09:55 +00003739 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003740 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattner673e02b2004-10-12 01:49:27 +00003741
3742 // Form the GEP offset.
3743 Indexes[VarIdxNum] = Val;
3744
Nick Lewyckyc6501b12009-11-23 03:26:09 +00003745 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
Chris Lattner673e02b2004-10-12 01:49:27 +00003746 if (Result == 0) break; // Cannot compute!
3747
3748 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003749 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003750 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00003751 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00003752#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00003753 errs() << "\n***\n*** Computed loop count " << *ItCst
3754 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3755 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00003756#endif
3757 ++NumArrayLenItCounts;
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003758 return getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00003759 }
3760 }
Dan Gohman1c343752009-06-27 21:21:31 +00003761 return getCouldNotCompute();
Chris Lattner673e02b2004-10-12 01:49:27 +00003762}
3763
3764
Chris Lattner3221ad02004-04-17 22:58:41 +00003765/// CanConstantFold - Return true if we can constant fold an instruction of the
3766/// specified type, assuming that all operands were constants.
3767static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00003768 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00003769 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3770 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003771
Chris Lattner3221ad02004-04-17 22:58:41 +00003772 if (const CallInst *CI = dyn_cast<CallInst>(I))
3773 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00003774 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00003775 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00003776}
3777
Chris Lattner3221ad02004-04-17 22:58:41 +00003778/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3779/// in the loop that V is derived from. We allow arbitrary operations along the
3780/// way, but the operands of an operation must either be constants or a value
3781/// derived from a constant PHI. If this expression does not fit with these
3782/// constraints, return null.
3783static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3784 // If this is not an instruction, or if this is an instruction outside of the
3785 // loop, it can't be derived from a loop PHI.
3786 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman92329c72009-12-18 01:24:09 +00003787 if (I == 0 || !L->contains(I)) return 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003788
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003789 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003790 if (L->getHeader() == I->getParent())
3791 return PN;
3792 else
3793 // We don't currently keep track of the control flow needed to evaluate
3794 // PHIs, so we cannot handle PHIs inside of loops.
3795 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00003796 }
Chris Lattner3221ad02004-04-17 22:58:41 +00003797
3798 // If we won't be able to constant fold this expression even if the operands
3799 // are constants, return early.
3800 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003801
Chris Lattner3221ad02004-04-17 22:58:41 +00003802 // Otherwise, we can evaluate this instruction if all of its operands are
3803 // constant or derived from a PHI node themselves.
3804 PHINode *PHI = 0;
3805 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3806 if (!(isa<Constant>(I->getOperand(Op)) ||
3807 isa<GlobalValue>(I->getOperand(Op)))) {
3808 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3809 if (P == 0) return 0; // Not evolving from PHI
3810 if (PHI == 0)
3811 PHI = P;
3812 else if (PHI != P)
3813 return 0; // Evolving from multiple different PHIs.
3814 }
3815
3816 // This is a expression evolving from a constant PHI!
3817 return PHI;
3818}
3819
3820/// EvaluateExpression - Given an expression that passes the
3821/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3822/// in the loop has the value PHIVal. If we can't fold this expression for some
3823/// reason, return null.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00003824static Constant *EvaluateExpression(Value *V, Constant *PHIVal,
3825 const TargetData *TD) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003826 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00003827 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman2d1be872009-04-16 03:18:22 +00003828 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Chris Lattner3221ad02004-04-17 22:58:41 +00003829 Instruction *I = cast<Instruction>(V);
3830
3831 std::vector<Constant*> Operands;
3832 Operands.resize(I->getNumOperands());
3833
3834 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00003835 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00003836 if (Operands[i] == 0) return 0;
3837 }
3838
Chris Lattnerf286f6f2007-12-10 22:53:04 +00003839 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattner8f73dea2009-11-09 23:06:58 +00003840 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00003841 Operands[1], TD);
Chris Lattner8f73dea2009-11-09 23:06:58 +00003842 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00003843 &Operands[0], Operands.size(), TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00003844}
3845
3846/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3847/// in the header of its containing loop, we know the loop executes a
3848/// constant number of times, and the PHI node is just a recurrence
3849/// involving constants, fold it.
Dan Gohman64a845e2009-06-24 04:48:43 +00003850Constant *
3851ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohman5d984912009-12-18 01:14:11 +00003852 const APInt &BEs,
Dan Gohman64a845e2009-06-24 04:48:43 +00003853 const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003854 std::map<PHINode*, Constant*>::iterator I =
3855 ConstantEvolutionLoopExitValue.find(PN);
3856 if (I != ConstantEvolutionLoopExitValue.end())
3857 return I->second;
3858
Dan Gohman46bdfb02009-02-24 18:55:53 +00003859 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00003860 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3861
3862 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3863
3864 // Since the loop is canonicalized, the PHI node must have two entries. One
3865 // entry must be a constant (coming in from outside of the loop), and the
3866 // second must be derived from the same PHI.
3867 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3868 Constant *StartCST =
3869 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3870 if (StartCST == 0)
3871 return RetVal = 0; // Must be a constant.
3872
3873 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3874 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3875 if (PN2 != PN)
3876 return RetVal = 0; // Not derived from same PHI.
3877
3878 // Execute the loop symbolically to determine the exit value.
Dan Gohman46bdfb02009-02-24 18:55:53 +00003879 if (BEs.getActiveBits() >= 32)
Reid Spencere8019bb2007-03-01 07:25:48 +00003880 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00003881
Dan Gohman46bdfb02009-02-24 18:55:53 +00003882 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencere8019bb2007-03-01 07:25:48 +00003883 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00003884 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3885 if (IterationNum == NumIterations)
3886 return RetVal = PHIVal; // Got exit value!
3887
3888 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00003889 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00003890 if (NextPHI == PHIVal)
3891 return RetVal = NextPHI; // Stopped evolving!
3892 if (NextPHI == 0)
3893 return 0; // Couldn't evaluate!
3894 PHIVal = NextPHI;
3895 }
3896}
3897
Dan Gohman07ad19b2009-07-27 16:09:48 +00003898/// ComputeBackedgeTakenCountExhaustively - If the loop is known to execute a
Chris Lattner7980fb92004-04-17 18:36:24 +00003899/// constant number of times (the condition evolves only from constants),
3900/// try to evaluate a few iterations of the loop until we get the exit
3901/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman1c343752009-06-27 21:21:31 +00003902/// evaluate the trip count of the loop, return getCouldNotCompute().
Dan Gohman64a845e2009-06-24 04:48:43 +00003903const SCEV *
3904ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3905 Value *Cond,
3906 bool ExitWhen) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003907 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman1c343752009-06-27 21:21:31 +00003908 if (PN == 0) return getCouldNotCompute();
Chris Lattner7980fb92004-04-17 18:36:24 +00003909
3910 // Since the loop is canonicalized, the PHI node must have two entries. One
3911 // entry must be a constant (coming in from outside of the loop), and the
3912 // second must be derived from the same PHI.
3913 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3914 Constant *StartCST =
3915 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman1c343752009-06-27 21:21:31 +00003916 if (StartCST == 0) return getCouldNotCompute(); // Must be a constant.
Chris Lattner7980fb92004-04-17 18:36:24 +00003917
3918 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3919 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman1c343752009-06-27 21:21:31 +00003920 if (PN2 != PN) return getCouldNotCompute(); // Not derived from same PHI.
Chris Lattner7980fb92004-04-17 18:36:24 +00003921
3922 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3923 // the loop symbolically to determine when the condition gets a value of
3924 // "ExitWhen".
3925 unsigned IterationNum = 0;
3926 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3927 for (Constant *PHIVal = StartCST;
3928 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003929 ConstantInt *CondVal =
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00003930 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal, TD));
Chris Lattner3221ad02004-04-17 22:58:41 +00003931
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003932 // Couldn't symbolically evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00003933 if (!CondVal) return getCouldNotCompute();
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003934
Reid Spencere8019bb2007-03-01 07:25:48 +00003935 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner7980fb92004-04-17 18:36:24 +00003936 ++NumBruteForceTripCountsComputed;
Owen Anderson1d0be152009-08-13 21:58:54 +00003937 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner7980fb92004-04-17 18:36:24 +00003938 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003939
Chris Lattner3221ad02004-04-17 22:58:41 +00003940 // Compute the value of the PHI node for the next iteration.
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00003941 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal, TD);
Chris Lattner3221ad02004-04-17 22:58:41 +00003942 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman1c343752009-06-27 21:21:31 +00003943 return getCouldNotCompute();// Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00003944 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00003945 }
3946
3947 // Too many iterations were needed to evaluate.
Dan Gohman1c343752009-06-27 21:21:31 +00003948 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00003949}
3950
Dan Gohmane7125f42009-09-03 15:00:26 +00003951/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohman66a7e852009-05-08 20:38:54 +00003952/// at the specified scope in the program. The L value specifies a loop
3953/// nest to evaluate the expression at, where null is the top-level or a
3954/// specified loop is immediately inside of the loop.
3955///
3956/// This method can be used to compute the exit value for a variable defined
3957/// in a loop by querying what the value will hold in the parent loop.
3958///
Dan Gohmand594e6f2009-05-24 23:25:42 +00003959/// In the case that a relevant loop exit value cannot be computed, the
3960/// original value V is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003961const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohman42214892009-08-31 21:15:23 +00003962 // Check to see if we've folded this expression at this loop before.
3963 std::map<const Loop *, const SCEV *> &Values = ValuesAtScopes[V];
3964 std::pair<std::map<const Loop *, const SCEV *>::iterator, bool> Pair =
3965 Values.insert(std::make_pair(L, static_cast<const SCEV *>(0)));
3966 if (!Pair.second)
3967 return Pair.first->second ? Pair.first->second : V;
Chris Lattner53e677a2004-04-02 20:23:17 +00003968
Dan Gohman42214892009-08-31 21:15:23 +00003969 // Otherwise compute it.
3970 const SCEV *C = computeSCEVAtScope(V, L);
Dan Gohmana5505cb2009-08-31 21:58:28 +00003971 ValuesAtScopes[V][L] = C;
Dan Gohman42214892009-08-31 21:15:23 +00003972 return C;
3973}
3974
3975const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003976 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003977
Nick Lewycky3e630762008-02-20 06:48:22 +00003978 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00003979 // exit value from the loop without using SCEVs.
Dan Gohman622ed672009-05-04 22:02:23 +00003980 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003981 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00003982 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattner3221ad02004-04-17 22:58:41 +00003983 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3984 if (PHINode *PN = dyn_cast<PHINode>(I))
3985 if (PN->getParent() == LI->getHeader()) {
3986 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman46bdfb02009-02-24 18:55:53 +00003987 // to see if the loop that contains it has a known backedge-taken
3988 // count. If so, we may be able to force computation of the exit
3989 // value.
Dan Gohman0bba49c2009-07-07 17:06:11 +00003990 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohman622ed672009-05-04 22:02:23 +00003991 if (const SCEVConstant *BTCC =
Dan Gohman46bdfb02009-02-24 18:55:53 +00003992 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00003993 // Okay, we know how many times the containing loop executes. If
3994 // this is a constant evolving PHI node, get the final value at
3995 // the specified iteration number.
3996 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman46bdfb02009-02-24 18:55:53 +00003997 BTCC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00003998 LI);
Dan Gohman09987962009-06-29 21:31:18 +00003999 if (RV) return getSCEV(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00004000 }
4001 }
4002
Reid Spencer09906f32006-12-04 21:33:23 +00004003 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00004004 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00004005 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00004006 // result. This is particularly useful for computing loop exit values.
4007 if (CanConstantFold(I)) {
4008 std::vector<Constant*> Operands;
4009 Operands.reserve(I->getNumOperands());
4010 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
4011 Value *Op = I->getOperand(i);
4012 if (Constant *C = dyn_cast<Constant>(Op)) {
4013 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004014 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00004015 // If any of the operands is non-constant and if they are
Dan Gohman2d1be872009-04-16 03:18:22 +00004016 // non-integer and non-pointer, don't even try to analyze them
4017 // with scev techniques.
Dan Gohman4acd12a2009-04-30 16:40:30 +00004018 if (!isSCEVable(Op->getType()))
Chris Lattner42b5e082007-11-23 08:46:22 +00004019 return V;
Dan Gohman2d1be872009-04-16 03:18:22 +00004020
Dan Gohman5d984912009-12-18 01:14:11 +00004021 const SCEV *OpV = getSCEVAtScope(Op, L);
Dan Gohman622ed672009-05-04 22:02:23 +00004022 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004023 Constant *C = SC->getValue();
4024 if (C->getType() != Op->getType())
4025 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4026 Op->getType(),
4027 false),
4028 C, Op->getType());
4029 Operands.push_back(C);
Dan Gohman622ed672009-05-04 22:02:23 +00004030 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman4acd12a2009-04-30 16:40:30 +00004031 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
4032 if (C->getType() != Op->getType())
4033 C =
4034 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
4035 Op->getType(),
4036 false),
4037 C, Op->getType());
4038 Operands.push_back(C);
4039 } else
Chris Lattner3221ad02004-04-17 22:58:41 +00004040 return V;
4041 } else {
4042 return V;
4043 }
4044 }
4045 }
Dan Gohman64a845e2009-06-24 04:48:43 +00004046
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004047 Constant *C;
4048 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
4049 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004050 Operands[0], Operands[1], TD);
Chris Lattnerf286f6f2007-12-10 22:53:04 +00004051 else
4052 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Dan Gohman1ba3b6c2009-11-09 23:34:17 +00004053 &Operands[0], Operands.size(), TD);
Dan Gohman09987962009-06-29 21:31:18 +00004054 return getSCEV(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00004055 }
4056 }
4057
4058 // This is some other type of SCEVUnknown, just return it.
4059 return V;
4060 }
4061
Dan Gohman622ed672009-05-04 22:02:23 +00004062 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004063 // Avoid performing the look-up in the common case where the specified
4064 // expression has no loop-variant portions.
4065 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004066 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004067 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004068 // Okay, at least one of these operands is loop variant but might be
4069 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman64a845e2009-06-24 04:48:43 +00004070 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
4071 Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00004072 NewOps.push_back(OpAtScope);
4073
4074 for (++i; i != e; ++i) {
4075 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00004076 NewOps.push_back(OpAtScope);
4077 }
4078 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004079 return getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004080 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004081 return getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00004082 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004083 return getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00004084 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004085 return getUMaxExpr(NewOps);
Torok Edwinc23197a2009-07-14 16:55:14 +00004086 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00004087 }
4088 }
4089 // If we got here, all operands are loop invariant.
4090 return Comm;
4091 }
4092
Dan Gohman622ed672009-05-04 22:02:23 +00004093 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004094 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
4095 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky789558d2009-01-13 09:18:58 +00004096 if (LHS == Div->getLHS() && RHS == Div->getRHS())
4097 return Div; // must be loop invariant
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004098 return getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00004099 }
4100
4101 // If this is a loop recurrence for a loop that does not contain L, then we
4102 // are dealing with the final value computed by the loop.
Dan Gohman622ed672009-05-04 22:02:23 +00004103 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohman92329c72009-12-18 01:24:09 +00004104 if (!L || !AddRec->getLoop()->contains(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004105 // To evaluate this recurrence, we need to know how many times the AddRec
4106 // loop iterates. Compute this now.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004107 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman1c343752009-06-27 21:21:31 +00004108 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004109
Eli Friedmanb42a6262008-08-04 23:49:06 +00004110 // Then, evaluate the AddRec.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004111 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004112 }
Dan Gohmand594e6f2009-05-24 23:25:42 +00004113 return AddRec;
Chris Lattner53e677a2004-04-02 20:23:17 +00004114 }
4115
Dan Gohman622ed672009-05-04 22:02:23 +00004116 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004117 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004118 if (Op == Cast->getOperand())
4119 return Cast; // must be loop invariant
4120 return getZeroExtendExpr(Op, Cast->getType());
4121 }
4122
Dan Gohman622ed672009-05-04 22:02:23 +00004123 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004124 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004125 if (Op == Cast->getOperand())
4126 return Cast; // must be loop invariant
4127 return getSignExtendExpr(Op, Cast->getType());
4128 }
4129
Dan Gohman622ed672009-05-04 22:02:23 +00004130 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004131 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohmaneb3948b2009-04-29 22:29:01 +00004132 if (Op == Cast->getOperand())
4133 return Cast; // must be loop invariant
4134 return getTruncateExpr(Op, Cast->getType());
4135 }
4136
Dan Gohmanc40f17b2009-08-18 16:46:41 +00004137 if (isa<SCEVTargetDataConstant>(V))
4138 return V;
4139
Torok Edwinc23197a2009-07-14 16:55:14 +00004140 llvm_unreachable("Unknown SCEV type!");
Daniel Dunbar8c562e22009-05-18 16:43:04 +00004141 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +00004142}
4143
Dan Gohman66a7e852009-05-08 20:38:54 +00004144/// getSCEVAtScope - This is a convenience function which does
4145/// getSCEVAtScope(getSCEV(V), L).
Dan Gohman0bba49c2009-07-07 17:06:11 +00004146const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004147 return getSCEVAtScope(getSCEV(V), L);
4148}
4149
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004150/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
4151/// following equation:
4152///
4153/// A * X = B (mod N)
4154///
4155/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
4156/// A and B isn't important.
4157///
4158/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004159static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004160 ScalarEvolution &SE) {
4161 uint32_t BW = A.getBitWidth();
4162 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
4163 assert(A != 0 && "A must be non-zero.");
4164
4165 // 1. D = gcd(A, N)
4166 //
4167 // The gcd of A and N may have only one prime factor: 2. The number of
4168 // trailing zeros in A is its multiplicity
4169 uint32_t Mult2 = A.countTrailingZeros();
4170 // D = 2^Mult2
4171
4172 // 2. Check if B is divisible by D.
4173 //
4174 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
4175 // is not less than multiplicity of this prime factor for D.
4176 if (B.countTrailingZeros() < Mult2)
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004177 return SE.getCouldNotCompute();
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004178
4179 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
4180 // modulo (N / D).
4181 //
4182 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
4183 // bit width during computations.
4184 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
4185 APInt Mod(BW + 1, 0);
4186 Mod.set(BW - Mult2); // Mod = N / D
4187 APInt I = AD.multiplicativeInverse(Mod);
4188
4189 // 4. Compute the minimum unsigned root of the equation:
4190 // I * (B / D) mod (N / D)
4191 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
4192
4193 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
4194 // bits.
4195 return SE.getConstant(Result.trunc(BW));
4196}
Chris Lattner53e677a2004-04-02 20:23:17 +00004197
4198/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
4199/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
4200/// might be the same) or two SCEVCouldNotCompute objects.
4201///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004202static std::pair<const SCEV *,const SCEV *>
Dan Gohman246b2562007-10-22 18:31:58 +00004203SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004204 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman35738ac2009-05-04 22:30:44 +00004205 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
4206 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
4207 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004208
Chris Lattner53e677a2004-04-02 20:23:17 +00004209 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00004210 if (!LC || !MC || !NC) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004211 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004212 return std::make_pair(CNC, CNC);
4213 }
4214
Reid Spencere8019bb2007-03-01 07:25:48 +00004215 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00004216 const APInt &L = LC->getValue()->getValue();
4217 const APInt &M = MC->getValue()->getValue();
4218 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00004219 APInt Two(BitWidth, 2);
4220 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004221
Dan Gohman64a845e2009-06-24 04:48:43 +00004222 {
Reid Spencere8019bb2007-03-01 07:25:48 +00004223 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00004224 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00004225 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
4226 // The B coefficient is M-N/2
4227 APInt B(M);
4228 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004229
Reid Spencere8019bb2007-03-01 07:25:48 +00004230 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00004231 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00004232
Reid Spencere8019bb2007-03-01 07:25:48 +00004233 // Compute the B^2-4ac term.
4234 APInt SqrtTerm(B);
4235 SqrtTerm *= B;
4236 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00004237
Reid Spencere8019bb2007-03-01 07:25:48 +00004238 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
4239 // integer value or else APInt::sqrt() will assert.
4240 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004241
Dan Gohman64a845e2009-06-24 04:48:43 +00004242 // Compute the two solutions for the quadratic formula.
Reid Spencere8019bb2007-03-01 07:25:48 +00004243 // The divisions must be performed as signed divisions.
4244 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00004245 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004246 if (TwoA.isMinValue()) {
Dan Gohman35738ac2009-05-04 22:30:44 +00004247 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00004248 return std::make_pair(CNC, CNC);
4249 }
4250
Owen Andersone922c022009-07-22 00:24:57 +00004251 LLVMContext &Context = SE.getContext();
Owen Anderson76f600b2009-07-06 22:37:39 +00004252
4253 ConstantInt *Solution1 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004254 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Anderson76f600b2009-07-06 22:37:39 +00004255 ConstantInt *Solution2 =
Owen Andersoneed707b2009-07-24 23:12:02 +00004256 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004257
Dan Gohman64a845e2009-06-24 04:48:43 +00004258 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman246b2562007-10-22 18:31:58 +00004259 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00004260 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00004261}
4262
4263/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004264/// value to zero will execute. If not computable, return CouldNotCompute.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004265const SCEV *ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004266 // If the value is a constant
Dan Gohman622ed672009-05-04 22:02:23 +00004267 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004268 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00004269 if (C->getValue()->isZero()) return C;
Dan Gohman1c343752009-06-27 21:21:31 +00004270 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004271 }
4272
Dan Gohman35738ac2009-05-04 22:30:44 +00004273 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00004274 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004275 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004276
4277 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004278 // If this is an affine expression, the execution count of this branch is
4279 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00004280 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004281 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00004282 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004283 // equivalent to:
4284 //
4285 // Step*N = -Start (mod 2^BW)
4286 //
4287 // where BW is the common bit width of Start and Step.
4288
Chris Lattner53e677a2004-04-02 20:23:17 +00004289 // Get the initial value for the loop.
Dan Gohman64a845e2009-06-24 04:48:43 +00004290 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
4291 L->getParentLoop());
4292 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
4293 L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00004294
Dan Gohman622ed672009-05-04 22:02:23 +00004295 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004296 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00004297
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004298 // First, handle unitary steps.
4299 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohman4c0d5d52009-08-20 16:42:55 +00004300 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004301 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
4302 return Start; // N = Start (as unsigned)
4303
4304 // Then, try to solve the above equation provided that Start is constant.
Dan Gohman622ed672009-05-04 22:02:23 +00004305 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00004306 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004307 -StartC->getValue()->getValue(),
4308 *this);
Chris Lattner53e677a2004-04-02 20:23:17 +00004309 }
Chris Lattner42a75512007-01-15 02:27:26 +00004310 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004311 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
4312 // the quadratic equation to solve it.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004313 std::pair<const SCEV *,const SCEV *> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004314 *this);
Dan Gohman35738ac2009-05-04 22:30:44 +00004315 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4316 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00004317 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004318#if 0
Dan Gohmanb7ef7292009-04-21 00:47:46 +00004319 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
4320 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00004321#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00004322 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004323 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00004324 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004325 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00004326 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00004327 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004328
Chris Lattner53e677a2004-04-02 20:23:17 +00004329 // We can only use this value if the chrec ends up with an exact zero
4330 // value at this index. When solving for "X*X != 5", for example, we
4331 // should not accept a root of 2.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004332 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00004333 if (Val->isZero())
4334 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00004335 }
4336 }
4337 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004338
Dan Gohman1c343752009-06-27 21:21:31 +00004339 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004340}
4341
4342/// HowFarToNonZero - Return the number of times a backedge checking the
4343/// specified value for nonzero will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004344/// CouldNotCompute
Dan Gohman0bba49c2009-07-07 17:06:11 +00004345const SCEV *ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattner53e677a2004-04-02 20:23:17 +00004346 // Loops that look like: while (X == 0) are very strange indeed. We don't
4347 // handle them yet except for the trivial case. This could be expanded in the
4348 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004349
Chris Lattner53e677a2004-04-02 20:23:17 +00004350 // If the value is a constant, check to see if it is known to be non-zero
4351 // already. If so, the backedge will execute zero times.
Dan Gohman622ed672009-05-04 22:02:23 +00004352 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00004353 if (!C->getValue()->isNullValue())
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004354 return getIntegerSCEV(0, C->getType());
Dan Gohman1c343752009-06-27 21:21:31 +00004355 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattner53e677a2004-04-02 20:23:17 +00004356 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00004357
Chris Lattner53e677a2004-04-02 20:23:17 +00004358 // We could implement others, but I really doubt anyone writes loops like
4359 // this, and if they did, they would already be constant folded.
Dan Gohman1c343752009-06-27 21:21:31 +00004360 return getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004361}
4362
Dan Gohman859b4822009-05-18 15:36:09 +00004363/// getLoopPredecessor - If the given loop's header has exactly one unique
4364/// predecessor outside the loop, return it. Otherwise return null.
4365///
4366BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
4367 BasicBlock *Header = L->getHeader();
4368 BasicBlock *Pred = 0;
4369 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
4370 PI != E; ++PI)
4371 if (!L->contains(*PI)) {
4372 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
4373 Pred = *PI;
4374 }
4375 return Pred;
4376}
4377
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004378/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
4379/// (which may not be an immediate predecessor) which has exactly one
4380/// successor from which BB is reachable, or null if no such block is
4381/// found.
4382///
4383BasicBlock *
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004384ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman3d739fe2009-04-30 20:48:53 +00004385 // If the block has a unique predecessor, then there is no path from the
4386 // predecessor to the block that does not go through the direct edge
4387 // from the predecessor to the block.
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004388 if (BasicBlock *Pred = BB->getSinglePredecessor())
4389 return Pred;
4390
4391 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman859b4822009-05-18 15:36:09 +00004392 // If the header has a unique predecessor outside the loop, it must be
4393 // a block that has exactly one successor that can reach the loop.
Dan Gohmanf8a8be82009-04-21 23:15:49 +00004394 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman859b4822009-05-18 15:36:09 +00004395 return getLoopPredecessor(L);
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004396
4397 return 0;
4398}
4399
Dan Gohman763bad12009-06-20 00:35:32 +00004400/// HasSameValue - SCEV structural equivalence is usually sufficient for
4401/// testing whether two expressions are equal, however for the purposes of
4402/// looking for a condition guarding a loop, it can be useful to be a little
4403/// more general, since a front-end may have replicated the controlling
4404/// expression.
4405///
Dan Gohman0bba49c2009-07-07 17:06:11 +00004406static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman763bad12009-06-20 00:35:32 +00004407 // Quick check to see if they are the same SCEV.
4408 if (A == B) return true;
4409
4410 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
4411 // two different instructions with the same value. Check for this case.
4412 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
4413 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
4414 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
4415 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman041de422009-08-25 17:56:57 +00004416 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman763bad12009-06-20 00:35:32 +00004417 return true;
4418
4419 // Otherwise assume they may have a different value.
4420 return false;
4421}
4422
Dan Gohman85b05a22009-07-13 21:35:55 +00004423bool ScalarEvolution::isKnownNegative(const SCEV *S) {
4424 return getSignedRange(S).getSignedMax().isNegative();
4425}
4426
4427bool ScalarEvolution::isKnownPositive(const SCEV *S) {
4428 return getSignedRange(S).getSignedMin().isStrictlyPositive();
4429}
4430
4431bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
4432 return !getSignedRange(S).getSignedMin().isNegative();
4433}
4434
4435bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
4436 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
4437}
4438
4439bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
4440 return isKnownNegative(S) || isKnownPositive(S);
4441}
4442
4443bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
4444 const SCEV *LHS, const SCEV *RHS) {
4445
4446 if (HasSameValue(LHS, RHS))
4447 return ICmpInst::isTrueWhenEqual(Pred);
4448
4449 switch (Pred) {
4450 default:
Dan Gohman850f7912009-07-16 17:34:36 +00004451 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohman85b05a22009-07-13 21:35:55 +00004452 break;
4453 case ICmpInst::ICMP_SGT:
4454 Pred = ICmpInst::ICMP_SLT;
4455 std::swap(LHS, RHS);
4456 case ICmpInst::ICMP_SLT: {
4457 ConstantRange LHSRange = getSignedRange(LHS);
4458 ConstantRange RHSRange = getSignedRange(RHS);
4459 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
4460 return true;
4461 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
4462 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004463 break;
4464 }
4465 case ICmpInst::ICMP_SGE:
4466 Pred = ICmpInst::ICMP_SLE;
4467 std::swap(LHS, RHS);
4468 case ICmpInst::ICMP_SLE: {
4469 ConstantRange LHSRange = getSignedRange(LHS);
4470 ConstantRange RHSRange = getSignedRange(RHS);
4471 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
4472 return true;
4473 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
4474 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004475 break;
4476 }
4477 case ICmpInst::ICMP_UGT:
4478 Pred = ICmpInst::ICMP_ULT;
4479 std::swap(LHS, RHS);
4480 case ICmpInst::ICMP_ULT: {
4481 ConstantRange LHSRange = getUnsignedRange(LHS);
4482 ConstantRange RHSRange = getUnsignedRange(RHS);
4483 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
4484 return true;
4485 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
4486 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004487 break;
4488 }
4489 case ICmpInst::ICMP_UGE:
4490 Pred = ICmpInst::ICMP_ULE;
4491 std::swap(LHS, RHS);
4492 case ICmpInst::ICMP_ULE: {
4493 ConstantRange LHSRange = getUnsignedRange(LHS);
4494 ConstantRange RHSRange = getUnsignedRange(RHS);
4495 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
4496 return true;
4497 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
4498 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004499 break;
4500 }
4501 case ICmpInst::ICMP_NE: {
4502 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
4503 return true;
4504 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
4505 return true;
4506
4507 const SCEV *Diff = getMinusSCEV(LHS, RHS);
4508 if (isKnownNonZero(Diff))
4509 return true;
4510 break;
4511 }
4512 case ICmpInst::ICMP_EQ:
Dan Gohmanf117ed42009-07-20 23:54:43 +00004513 // The check at the top of the function catches the case where
4514 // the values are known to be equal.
Dan Gohman85b05a22009-07-13 21:35:55 +00004515 break;
4516 }
4517 return false;
4518}
4519
4520/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
4521/// protected by a conditional between LHS and RHS. This is used to
4522/// to eliminate casts.
4523bool
4524ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
4525 ICmpInst::Predicate Pred,
4526 const SCEV *LHS, const SCEV *RHS) {
4527 // Interpret a null as meaning no loop, where there is obviously no guard
4528 // (interprocedural conditions notwithstanding).
4529 if (!L) return true;
4530
4531 BasicBlock *Latch = L->getLoopLatch();
4532 if (!Latch)
4533 return false;
4534
4535 BranchInst *LoopContinuePredicate =
4536 dyn_cast<BranchInst>(Latch->getTerminator());
4537 if (!LoopContinuePredicate ||
4538 LoopContinuePredicate->isUnconditional())
4539 return false;
4540
Dan Gohman0f4b2852009-07-21 23:03:19 +00004541 return isImpliedCond(LoopContinuePredicate->getCondition(), Pred, LHS, RHS,
4542 LoopContinuePredicate->getSuccessor(0) != L->getHeader());
Dan Gohman85b05a22009-07-13 21:35:55 +00004543}
4544
4545/// isLoopGuardedByCond - Test whether entry to the loop is protected
4546/// by a conditional between LHS and RHS. This is used to help avoid max
4547/// expressions in loop trip counts, and to eliminate casts.
4548bool
4549ScalarEvolution::isLoopGuardedByCond(const Loop *L,
4550 ICmpInst::Predicate Pred,
4551 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8ea94522009-05-18 16:03:58 +00004552 // Interpret a null as meaning no loop, where there is obviously no guard
4553 // (interprocedural conditions notwithstanding).
4554 if (!L) return false;
4555
Dan Gohman859b4822009-05-18 15:36:09 +00004556 BasicBlock *Predecessor = getLoopPredecessor(L);
4557 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00004558
Dan Gohman859b4822009-05-18 15:36:09 +00004559 // Starting at the loop predecessor, climb up the predecessor chain, as long
4560 // as there are predecessors that can be found that have unique successors
Dan Gohmanfd6edef2008-09-15 22:18:04 +00004561 // leading to the original header.
Dan Gohman859b4822009-05-18 15:36:09 +00004562 for (; Predecessor;
4563 PredecessorDest = Predecessor,
4564 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohman38372182008-08-12 20:17:31 +00004565
4566 BranchInst *LoopEntryPredicate =
Dan Gohman859b4822009-05-18 15:36:09 +00004567 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00004568 if (!LoopEntryPredicate ||
4569 LoopEntryPredicate->isUnconditional())
4570 continue;
4571
Dan Gohman0f4b2852009-07-21 23:03:19 +00004572 if (isImpliedCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
4573 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohman38372182008-08-12 20:17:31 +00004574 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00004575 }
4576
Dan Gohman38372182008-08-12 20:17:31 +00004577 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00004578}
4579
Dan Gohman0f4b2852009-07-21 23:03:19 +00004580/// isImpliedCond - Test whether the condition described by Pred, LHS,
4581/// and RHS is true whenever the given Cond value evaluates to true.
4582bool ScalarEvolution::isImpliedCond(Value *CondValue,
4583 ICmpInst::Predicate Pred,
4584 const SCEV *LHS, const SCEV *RHS,
4585 bool Inverse) {
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004586 // Recursivly handle And and Or conditions.
4587 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
4588 if (BO->getOpcode() == Instruction::And) {
4589 if (!Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004590 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4591 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004592 } else if (BO->getOpcode() == Instruction::Or) {
4593 if (Inverse)
Dan Gohman0f4b2852009-07-21 23:03:19 +00004594 return isImpliedCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
4595 isImpliedCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004596 }
4597 }
4598
4599 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
4600 if (!ICI) return false;
4601
Dan Gohman85b05a22009-07-13 21:35:55 +00004602 // Bail if the ICmp's operands' types are wider than the needed type
4603 // before attempting to call getSCEV on them. This avoids infinite
4604 // recursion, since the analysis of widening casts can require loop
4605 // exit condition information for overflow checking, which would
4606 // lead back here.
4607 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman0f4b2852009-07-21 23:03:19 +00004608 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohman85b05a22009-07-13 21:35:55 +00004609 return false;
4610
Dan Gohman0f4b2852009-07-21 23:03:19 +00004611 // Now that we found a conditional branch that dominates the loop, check to
4612 // see if it is the comparison we are looking for.
4613 ICmpInst::Predicate FoundPred;
4614 if (Inverse)
4615 FoundPred = ICI->getInversePredicate();
4616 else
4617 FoundPred = ICI->getPredicate();
4618
4619 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
4620 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohman85b05a22009-07-13 21:35:55 +00004621
4622 // Balance the types. The case where FoundLHS' type is wider than
4623 // LHS' type is checked for above.
4624 if (getTypeSizeInBits(LHS->getType()) >
4625 getTypeSizeInBits(FoundLHS->getType())) {
4626 if (CmpInst::isSigned(Pred)) {
4627 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
4628 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
4629 } else {
4630 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
4631 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
4632 }
4633 }
4634
Dan Gohman0f4b2852009-07-21 23:03:19 +00004635 // Canonicalize the query to match the way instcombine will have
4636 // canonicalized the comparison.
4637 // First, put a constant operand on the right.
4638 if (isa<SCEVConstant>(LHS)) {
4639 std::swap(LHS, RHS);
4640 Pred = ICmpInst::getSwappedPredicate(Pred);
4641 }
4642 // Then, canonicalize comparisons with boundary cases.
4643 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
4644 const APInt &RA = RC->getValue()->getValue();
4645 switch (Pred) {
4646 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4647 case ICmpInst::ICMP_EQ:
4648 case ICmpInst::ICMP_NE:
4649 break;
4650 case ICmpInst::ICMP_UGE:
4651 if ((RA - 1).isMinValue()) {
4652 Pred = ICmpInst::ICMP_NE;
4653 RHS = getConstant(RA - 1);
4654 break;
4655 }
4656 if (RA.isMaxValue()) {
4657 Pred = ICmpInst::ICMP_EQ;
4658 break;
4659 }
4660 if (RA.isMinValue()) return true;
4661 break;
4662 case ICmpInst::ICMP_ULE:
4663 if ((RA + 1).isMaxValue()) {
4664 Pred = ICmpInst::ICMP_NE;
4665 RHS = getConstant(RA + 1);
4666 break;
4667 }
4668 if (RA.isMinValue()) {
4669 Pred = ICmpInst::ICMP_EQ;
4670 break;
4671 }
4672 if (RA.isMaxValue()) return true;
4673 break;
4674 case ICmpInst::ICMP_SGE:
4675 if ((RA - 1).isMinSignedValue()) {
4676 Pred = ICmpInst::ICMP_NE;
4677 RHS = getConstant(RA - 1);
4678 break;
4679 }
4680 if (RA.isMaxSignedValue()) {
4681 Pred = ICmpInst::ICMP_EQ;
4682 break;
4683 }
4684 if (RA.isMinSignedValue()) return true;
4685 break;
4686 case ICmpInst::ICMP_SLE:
4687 if ((RA + 1).isMaxSignedValue()) {
4688 Pred = ICmpInst::ICMP_NE;
4689 RHS = getConstant(RA + 1);
4690 break;
4691 }
4692 if (RA.isMinSignedValue()) {
4693 Pred = ICmpInst::ICMP_EQ;
4694 break;
4695 }
4696 if (RA.isMaxSignedValue()) return true;
4697 break;
4698 case ICmpInst::ICMP_UGT:
4699 if (RA.isMinValue()) {
4700 Pred = ICmpInst::ICMP_NE;
4701 break;
4702 }
4703 if ((RA + 1).isMaxValue()) {
4704 Pred = ICmpInst::ICMP_EQ;
4705 RHS = getConstant(RA + 1);
4706 break;
4707 }
4708 if (RA.isMaxValue()) return false;
4709 break;
4710 case ICmpInst::ICMP_ULT:
4711 if (RA.isMaxValue()) {
4712 Pred = ICmpInst::ICMP_NE;
4713 break;
4714 }
4715 if ((RA - 1).isMinValue()) {
4716 Pred = ICmpInst::ICMP_EQ;
4717 RHS = getConstant(RA - 1);
4718 break;
4719 }
4720 if (RA.isMinValue()) return false;
4721 break;
4722 case ICmpInst::ICMP_SGT:
4723 if (RA.isMinSignedValue()) {
4724 Pred = ICmpInst::ICMP_NE;
4725 break;
4726 }
4727 if ((RA + 1).isMaxSignedValue()) {
4728 Pred = ICmpInst::ICMP_EQ;
4729 RHS = getConstant(RA + 1);
4730 break;
4731 }
4732 if (RA.isMaxSignedValue()) return false;
4733 break;
4734 case ICmpInst::ICMP_SLT:
4735 if (RA.isMaxSignedValue()) {
4736 Pred = ICmpInst::ICMP_NE;
4737 break;
4738 }
4739 if ((RA - 1).isMinSignedValue()) {
4740 Pred = ICmpInst::ICMP_EQ;
4741 RHS = getConstant(RA - 1);
4742 break;
4743 }
4744 if (RA.isMinSignedValue()) return false;
4745 break;
4746 }
4747 }
4748
4749 // Check to see if we can make the LHS or RHS match.
4750 if (LHS == FoundRHS || RHS == FoundLHS) {
4751 if (isa<SCEVConstant>(RHS)) {
4752 std::swap(FoundLHS, FoundRHS);
4753 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
4754 } else {
4755 std::swap(LHS, RHS);
4756 Pred = ICmpInst::getSwappedPredicate(Pred);
4757 }
4758 }
4759
4760 // Check whether the found predicate is the same as the desired predicate.
4761 if (FoundPred == Pred)
4762 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
4763
4764 // Check whether swapping the found predicate makes it the same as the
4765 // desired predicate.
4766 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
4767 if (isa<SCEVConstant>(RHS))
4768 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
4769 else
4770 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
4771 RHS, LHS, FoundLHS, FoundRHS);
4772 }
4773
4774 // Check whether the actual condition is beyond sufficient.
4775 if (FoundPred == ICmpInst::ICMP_EQ)
4776 if (ICmpInst::isTrueWhenEqual(Pred))
4777 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
4778 return true;
4779 if (Pred == ICmpInst::ICMP_NE)
4780 if (!ICmpInst::isTrueWhenEqual(FoundPred))
4781 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
4782 return true;
4783
4784 // Otherwise assume the worst.
4785 return false;
Dan Gohman85b05a22009-07-13 21:35:55 +00004786}
4787
Dan Gohman0f4b2852009-07-21 23:03:19 +00004788/// isImpliedCondOperands - Test whether the condition described by Pred,
4789/// LHS, and RHS is true whenever the condition desribed by Pred, FoundLHS,
4790/// and FoundRHS is true.
4791bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
4792 const SCEV *LHS, const SCEV *RHS,
4793 const SCEV *FoundLHS,
4794 const SCEV *FoundRHS) {
4795 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
4796 FoundLHS, FoundRHS) ||
4797 // ~x < ~y --> x > y
4798 isImpliedCondOperandsHelper(Pred, LHS, RHS,
4799 getNotSCEV(FoundRHS),
4800 getNotSCEV(FoundLHS));
4801}
4802
4803/// isImpliedCondOperandsHelper - Test whether the condition described by
4804/// Pred, LHS, and RHS is true whenever the condition desribed by Pred,
4805/// FoundLHS, and FoundRHS is true.
Dan Gohman85b05a22009-07-13 21:35:55 +00004806bool
Dan Gohman0f4b2852009-07-21 23:03:19 +00004807ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
4808 const SCEV *LHS, const SCEV *RHS,
4809 const SCEV *FoundLHS,
4810 const SCEV *FoundRHS) {
Dan Gohman85b05a22009-07-13 21:35:55 +00004811 switch (Pred) {
Dan Gohman850f7912009-07-16 17:34:36 +00004812 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
4813 case ICmpInst::ICMP_EQ:
4814 case ICmpInst::ICMP_NE:
4815 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
4816 return true;
4817 break;
Dan Gohman85b05a22009-07-13 21:35:55 +00004818 case ICmpInst::ICMP_SLT:
Dan Gohman850f7912009-07-16 17:34:36 +00004819 case ICmpInst::ICMP_SLE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004820 if (isKnownPredicate(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
4821 isKnownPredicate(ICmpInst::ICMP_SGE, RHS, FoundRHS))
4822 return true;
4823 break;
4824 case ICmpInst::ICMP_SGT:
Dan Gohman850f7912009-07-16 17:34:36 +00004825 case ICmpInst::ICMP_SGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004826 if (isKnownPredicate(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
4827 isKnownPredicate(ICmpInst::ICMP_SLE, RHS, FoundRHS))
4828 return true;
4829 break;
4830 case ICmpInst::ICMP_ULT:
Dan Gohman850f7912009-07-16 17:34:36 +00004831 case ICmpInst::ICMP_ULE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004832 if (isKnownPredicate(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
4833 isKnownPredicate(ICmpInst::ICMP_UGE, RHS, FoundRHS))
4834 return true;
4835 break;
4836 case ICmpInst::ICMP_UGT:
Dan Gohman850f7912009-07-16 17:34:36 +00004837 case ICmpInst::ICMP_UGE:
Dan Gohman85b05a22009-07-13 21:35:55 +00004838 if (isKnownPredicate(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
4839 isKnownPredicate(ICmpInst::ICMP_ULE, RHS, FoundRHS))
4840 return true;
4841 break;
4842 }
4843
4844 return false;
Dan Gohman40a5a1b2009-06-24 01:18:18 +00004845}
4846
Dan Gohman51f53b72009-06-21 23:46:38 +00004847/// getBECount - Subtract the end and start values and divide by the step,
4848/// rounding up, to get the number of times the backedge is executed. Return
4849/// CouldNotCompute if an intermediate computation overflows.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004850const SCEV *ScalarEvolution::getBECount(const SCEV *Start,
Dan Gohmanf5074ec2009-07-13 22:05:32 +00004851 const SCEV *End,
Dan Gohman1f96e672009-09-17 18:05:20 +00004852 const SCEV *Step,
4853 bool NoWrap) {
Dan Gohman51f53b72009-06-21 23:46:38 +00004854 const Type *Ty = Start->getType();
Dan Gohman0bba49c2009-07-07 17:06:11 +00004855 const SCEV *NegOne = getIntegerSCEV(-1, Ty);
4856 const SCEV *Diff = getMinusSCEV(End, Start);
4857 const SCEV *RoundUp = getAddExpr(Step, NegOne);
Dan Gohman51f53b72009-06-21 23:46:38 +00004858
4859 // Add an adjustment to the difference between End and Start so that
4860 // the division will effectively round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004861 const SCEV *Add = getAddExpr(Diff, RoundUp);
Dan Gohman51f53b72009-06-21 23:46:38 +00004862
Dan Gohman1f96e672009-09-17 18:05:20 +00004863 if (!NoWrap) {
4864 // Check Add for unsigned overflow.
4865 // TODO: More sophisticated things could be done here.
4866 const Type *WideTy = IntegerType::get(getContext(),
4867 getTypeSizeInBits(Ty) + 1);
4868 const SCEV *EDiff = getZeroExtendExpr(Diff, WideTy);
4869 const SCEV *ERoundUp = getZeroExtendExpr(RoundUp, WideTy);
4870 const SCEV *OperandExtendedAdd = getAddExpr(EDiff, ERoundUp);
4871 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
4872 return getCouldNotCompute();
4873 }
Dan Gohman51f53b72009-06-21 23:46:38 +00004874
4875 return getUDivExpr(Add, Step);
4876}
4877
Chris Lattnerdb25de42005-08-15 23:33:51 +00004878/// HowManyLessThans - Return the number of times a backedge containing the
4879/// specified less-than comparison will execute. If not computable, return
Dan Gohman86fbf2f2009-06-06 14:37:11 +00004880/// CouldNotCompute.
Dan Gohman64a845e2009-06-24 04:48:43 +00004881ScalarEvolution::BackedgeTakenInfo
4882ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4883 const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00004884 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman1c343752009-06-27 21:21:31 +00004885 if (!RHS->isLoopInvariant(L)) return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004886
Dan Gohman35738ac2009-05-04 22:30:44 +00004887 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004888 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman1c343752009-06-27 21:21:31 +00004889 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004890
Dan Gohman1f96e672009-09-17 18:05:20 +00004891 // Check to see if we have a flag which makes analysis easy.
4892 bool NoWrap = isSigned ? AddRec->hasNoSignedWrap() :
4893 AddRec->hasNoUnsignedWrap();
4894
Chris Lattnerdb25de42005-08-15 23:33:51 +00004895 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00004896 // FORNOW: We only support unit strides.
Dan Gohmana1af7572009-04-30 20:47:05 +00004897 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00004898 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmana1af7572009-04-30 20:47:05 +00004899
4900 // TODO: handle non-constant strides.
4901 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4902 if (!CStep || CStep->isZero())
Dan Gohman1c343752009-06-27 21:21:31 +00004903 return getCouldNotCompute();
Dan Gohman70a1fe72009-05-18 15:22:39 +00004904 if (CStep->isOne()) {
Dan Gohmana1af7572009-04-30 20:47:05 +00004905 // With unit stride, the iteration never steps past the limit value.
4906 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
Dan Gohman1f96e672009-09-17 18:05:20 +00004907 if (NoWrap) {
4908 // We know the iteration won't step past the maximum value for its type.
4909 ;
4910 } else if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmana1af7572009-04-30 20:47:05 +00004911 // Test whether a positive iteration iteration can step past the limit
4912 // value and past the maximum value for its type in a single step.
4913 if (isSigned) {
4914 APInt Max = APInt::getSignedMaxValue(BitWidth);
4915 if ((Max - CStep->getValue()->getValue())
4916 .slt(CLimit->getValue()->getValue()))
Dan Gohman1c343752009-06-27 21:21:31 +00004917 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004918 } else {
4919 APInt Max = APInt::getMaxValue(BitWidth);
4920 if ((Max - CStep->getValue()->getValue())
4921 .ult(CLimit->getValue()->getValue()))
Dan Gohman1c343752009-06-27 21:21:31 +00004922 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004923 }
4924 } else
4925 // TODO: handle non-constant limit values below.
Dan Gohman1c343752009-06-27 21:21:31 +00004926 return getCouldNotCompute();
Dan Gohmana1af7572009-04-30 20:47:05 +00004927 } else
4928 // TODO: handle negative strides below.
Dan Gohman1c343752009-06-27 21:21:31 +00004929 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004930
Dan Gohmana1af7572009-04-30 20:47:05 +00004931 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4932 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4933 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00004934 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00004935
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004936 // First, we get the value of the LHS in the first iteration: n
Dan Gohman0bba49c2009-07-07 17:06:11 +00004937 const SCEV *Start = AddRec->getOperand(0);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004938
Dan Gohmana1af7572009-04-30 20:47:05 +00004939 // Determine the minimum constant start value.
Dan Gohman85b05a22009-07-13 21:35:55 +00004940 const SCEV *MinStart = getConstant(isSigned ?
4941 getSignedRange(Start).getSignedMin() :
4942 getUnsignedRange(Start).getUnsignedMin());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00004943
Dan Gohmana1af7572009-04-30 20:47:05 +00004944 // If we know that the condition is true in order to enter the loop,
4945 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohman6c0866c2009-05-24 23:45:28 +00004946 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4947 // the division must round up.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004948 const SCEV *End = RHS;
Dan Gohmana1af7572009-04-30 20:47:05 +00004949 if (!isLoopGuardedByCond(L,
Dan Gohman85b05a22009-07-13 21:35:55 +00004950 isSigned ? ICmpInst::ICMP_SLT :
4951 ICmpInst::ICMP_ULT,
Dan Gohmana1af7572009-04-30 20:47:05 +00004952 getMinusSCEV(Start, Step), RHS))
4953 End = isSigned ? getSMaxExpr(RHS, Start)
4954 : getUMaxExpr(RHS, Start);
4955
4956 // Determine the maximum constant end value.
Dan Gohman85b05a22009-07-13 21:35:55 +00004957 const SCEV *MaxEnd = getConstant(isSigned ?
4958 getSignedRange(End).getSignedMax() :
4959 getUnsignedRange(End).getUnsignedMax());
Dan Gohmana1af7572009-04-30 20:47:05 +00004960
4961 // Finally, we subtract these two values and divide, rounding up, to get
4962 // the number of times the backedge is executed.
Dan Gohman1f96e672009-09-17 18:05:20 +00004963 const SCEV *BECount = getBECount(Start, End, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00004964
4965 // The maximum backedge count is similar, except using the minimum start
4966 // value and the maximum end value.
Dan Gohman1f96e672009-09-17 18:05:20 +00004967 const SCEV *MaxBECount = getBECount(MinStart, MaxEnd, Step, NoWrap);
Dan Gohmana1af7572009-04-30 20:47:05 +00004968
4969 return BackedgeTakenInfo(BECount, MaxBECount);
Chris Lattnerdb25de42005-08-15 23:33:51 +00004970 }
4971
Dan Gohman1c343752009-06-27 21:21:31 +00004972 return getCouldNotCompute();
Chris Lattnerdb25de42005-08-15 23:33:51 +00004973}
4974
Chris Lattner53e677a2004-04-02 20:23:17 +00004975/// getNumIterationsInRange - Return the number of iterations of this loop that
4976/// produce values in the specified constant range. Another way of looking at
4977/// this is that it returns the first iteration number where the value is not in
4978/// the condition, thus computing the exit count. If the iteration count can't
4979/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman0bba49c2009-07-07 17:06:11 +00004980const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman64a845e2009-06-24 04:48:43 +00004981 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00004982 if (Range.isFullSet()) // Infinite loop.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004983 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004984
4985 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohman622ed672009-05-04 22:02:23 +00004986 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00004987 if (!SC->getValue()->isZero()) {
Dan Gohman0bba49c2009-07-07 17:06:11 +00004988 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00004989 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Dan Gohman0bba49c2009-07-07 17:06:11 +00004990 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohman622ed672009-05-04 22:02:23 +00004991 if (const SCEVAddRecExpr *ShiftedAddRec =
4992 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattner53e677a2004-04-02 20:23:17 +00004993 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00004994 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00004995 // This is strange and shouldn't happen.
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00004996 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00004997 }
4998
4999 // The only time we can solve this is when we have all constant indices.
5000 // Otherwise, we cannot determine the overflow conditions.
5001 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5002 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005003 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005004
5005
5006 // Okay at this point we know that all elements of the chrec are constants and
5007 // that the start element is zero.
5008
5009 // First check to see if the range contains zero. If not, the first
5010 // iteration exits.
Dan Gohmanaf79fb52009-04-21 01:07:12 +00005011 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman2d1be872009-04-16 03:18:22 +00005012 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman6de29f82009-06-15 22:12:54 +00005013 return SE.getIntegerSCEV(0, getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005014
Chris Lattner53e677a2004-04-02 20:23:17 +00005015 if (isAffine()) {
5016 // If this is an affine expression then we have this situation:
5017 // Solve {0,+,A} in Range === Ax in Range
5018
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005019 // We know that zero is in the range. If A is positive then we know that
5020 // the upper value of the range must be the first possible exit value.
5021 // If A is negative then the lower of the range is the last possible loop
5022 // value. Also note that we already checked for a full range.
Dan Gohman2d1be872009-04-16 03:18:22 +00005023 APInt One(BitWidth,1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005024 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
5025 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00005026
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00005027 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00005028 APInt ExitVal = (End + A).udiv(A);
Owen Andersoneed707b2009-07-24 23:12:02 +00005029 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00005030
5031 // Evaluate at the exit value. If we really did fall out of the valid
5032 // range, then we computed our trip count, otherwise wrap around or other
5033 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00005034 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005035 if (Range.contains(Val->getValue()))
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005036 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005037
5038 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00005039 assert(Range.contains(
Dan Gohman64a845e2009-06-24 04:48:43 +00005040 EvaluateConstantChrecAtConstant(this,
Owen Andersoneed707b2009-07-24 23:12:02 +00005041 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00005042 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00005043 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00005044 } else if (isQuadratic()) {
5045 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
5046 // quadratic equation to solve it. To do this, we must frame our problem in
5047 // terms of figuring out when zero is crossed, instead of when
5048 // Range.getUpper() is crossed.
Dan Gohman0bba49c2009-07-07 17:06:11 +00005049 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00005050 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Dan Gohman0bba49c2009-07-07 17:06:11 +00005051 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00005052
5053 // Next, solve the constructed addrec
Dan Gohman0bba49c2009-07-07 17:06:11 +00005054 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00005055 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman35738ac2009-05-04 22:30:44 +00005056 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5057 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattner53e677a2004-04-02 20:23:17 +00005058 if (R1) {
5059 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005060 if (ConstantInt *CB =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005061 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Anderson76f600b2009-07-06 22:37:39 +00005062 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00005063 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00005064 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005065
Chris Lattner53e677a2004-04-02 20:23:17 +00005066 // Make sure the root is not off by one. The returned iteration should
5067 // not be in the range, but the previous one should be. When solving
5068 // for "X*X < 5", for example, we should not return a root of 2.
5069 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00005070 R1->getValue(),
5071 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005072 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005073 // The next iteration must be out of the range...
Owen Anderson76f600b2009-07-06 22:37:39 +00005074 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005075 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005076
Dan Gohman246b2562007-10-22 18:31:58 +00005077 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005078 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00005079 return SE.getConstant(NextVal);
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005080 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005081 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005082
Chris Lattner53e677a2004-04-02 20:23:17 +00005083 // If R1 was not in the range, then it is a good return value. Make
5084 // sure that R1-1 WAS in the range though, just in case.
Owen Anderson76f600b2009-07-06 22:37:39 +00005085 ConstantInt *NextVal =
Owen Andersoneed707b2009-07-24 23:12:02 +00005086 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00005087 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00005088 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00005089 return R1;
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005090 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattner53e677a2004-04-02 20:23:17 +00005091 }
5092 }
5093 }
5094
Dan Gohmanf4ccfcb2009-04-18 17:58:19 +00005095 return SE.getCouldNotCompute();
Chris Lattner53e677a2004-04-02 20:23:17 +00005096}
5097
5098
5099
5100//===----------------------------------------------------------------------===//
Dan Gohman35738ac2009-05-04 22:30:44 +00005101// SCEVCallbackVH Class Implementation
5102//===----------------------------------------------------------------------===//
5103
Dan Gohman1959b752009-05-19 19:22:47 +00005104void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005105 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005106 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
5107 SE->ConstantEvolutionLoopExitValue.erase(PN);
5108 SE->Scalars.erase(getValPtr());
5109 // this now dangles!
5110}
5111
Dan Gohman1959b752009-05-19 19:22:47 +00005112void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanddf9f992009-07-13 22:20:53 +00005113 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman35738ac2009-05-04 22:30:44 +00005114
5115 // Forget all the expressions associated with users of the old value,
5116 // so that future queries will recompute the expressions using the new
5117 // value.
5118 SmallVector<User *, 16> Worklist;
Dan Gohman69fcae92009-07-14 14:34:04 +00005119 SmallPtrSet<User *, 8> Visited;
Dan Gohman35738ac2009-05-04 22:30:44 +00005120 Value *Old = getValPtr();
5121 bool DeleteOld = false;
5122 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
5123 UI != UE; ++UI)
5124 Worklist.push_back(*UI);
5125 while (!Worklist.empty()) {
5126 User *U = Worklist.pop_back_val();
5127 // Deleting the Old value will cause this to dangle. Postpone
5128 // that until everything else is done.
5129 if (U == Old) {
5130 DeleteOld = true;
5131 continue;
5132 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005133 if (!Visited.insert(U))
5134 continue;
Dan Gohman35738ac2009-05-04 22:30:44 +00005135 if (PHINode *PN = dyn_cast<PHINode>(U))
5136 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman69fcae92009-07-14 14:34:04 +00005137 SE->Scalars.erase(U);
5138 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
5139 UI != UE; ++UI)
5140 Worklist.push_back(*UI);
Dan Gohman35738ac2009-05-04 22:30:44 +00005141 }
Dan Gohman69fcae92009-07-14 14:34:04 +00005142 // Delete the Old value if it (indirectly) references itself.
Dan Gohman35738ac2009-05-04 22:30:44 +00005143 if (DeleteOld) {
5144 if (PHINode *PN = dyn_cast<PHINode>(Old))
5145 SE->ConstantEvolutionLoopExitValue.erase(PN);
5146 SE->Scalars.erase(Old);
5147 // this now dangles!
5148 }
5149 // this may dangle!
5150}
5151
Dan Gohman1959b752009-05-19 19:22:47 +00005152ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman35738ac2009-05-04 22:30:44 +00005153 : CallbackVH(V), SE(se) {}
5154
5155//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00005156// ScalarEvolution Class Implementation
5157//===----------------------------------------------------------------------===//
5158
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005159ScalarEvolution::ScalarEvolution()
Dan Gohman1c343752009-06-27 21:21:31 +00005160 : FunctionPass(&ID) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005161}
5162
Chris Lattner53e677a2004-04-02 20:23:17 +00005163bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005164 this->F = &F;
5165 LI = &getAnalysis<LoopInfo>();
5166 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattner53e677a2004-04-02 20:23:17 +00005167 return false;
5168}
5169
5170void ScalarEvolution::releaseMemory() {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005171 Scalars.clear();
5172 BackedgeTakenCounts.clear();
5173 ConstantEvolutionLoopExitValue.clear();
Dan Gohman6bce6432009-05-08 20:47:27 +00005174 ValuesAtScopes.clear();
Dan Gohman1c343752009-06-27 21:21:31 +00005175 UniqueSCEVs.clear();
5176 SCEVAllocator.Reset();
Chris Lattner53e677a2004-04-02 20:23:17 +00005177}
5178
5179void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
5180 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00005181 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman2d1be872009-04-16 03:18:22 +00005182}
5183
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005184bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005185 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattner53e677a2004-04-02 20:23:17 +00005186}
5187
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005188static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00005189 const Loop *L) {
5190 // Print all inner loops first
5191 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5192 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005193
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005194 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005195
Dan Gohman5d984912009-12-18 01:14:11 +00005196 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00005197 L->getExitBlocks(ExitBlocks);
5198 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005199 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005200
Dan Gohman46bdfb02009-02-24 18:55:53 +00005201 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
5202 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattner53e677a2004-04-02 20:23:17 +00005203 } else {
Dan Gohman46bdfb02009-02-24 18:55:53 +00005204 OS << "Unpredictable backedge-taken count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00005205 }
5206
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00005207 OS << "\n";
Dan Gohmanaa551ae2009-06-24 00:33:16 +00005208 OS << "Loop " << L->getHeader()->getName() << ": ";
5209
5210 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
5211 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
5212 } else {
5213 OS << "Unpredictable max backedge-taken count. ";
5214 }
5215
5216 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005217}
5218
Dan Gohman5d984912009-12-18 01:14:11 +00005219void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005220 // ScalarEvolution's implementaiton of the print method is to print
5221 // out SCEV values of all instructions that are interesting. Doing
5222 // this potentially causes it to create new SCEV objects though,
5223 // which technically conflicts with the const qualifier. This isn't
Dan Gohman1afdc5f2009-07-10 20:25:29 +00005224 // observable from outside the class though, so casting away the
5225 // const isn't dangerous.
Dan Gohman5d984912009-12-18 01:14:11 +00005226 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattner53e677a2004-04-02 20:23:17 +00005227
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005228 OS << "Classifying expressions for: " << F->getName() << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00005229 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand9c1c852009-04-30 01:30:18 +00005230 if (isSCEVable(I->getType())) {
Dan Gohmanc902e132009-07-13 23:03:05 +00005231 OS << *I << '\n';
Dan Gohman8dae1382008-09-14 17:21:12 +00005232 OS << " --> ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005233 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005234 SV->print(OS);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00005235
Dan Gohman0c689c52009-06-19 17:49:54 +00005236 const Loop *L = LI->getLoopFor((*I).getParent());
5237
Dan Gohman0bba49c2009-07-07 17:06:11 +00005238 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman0c689c52009-06-19 17:49:54 +00005239 if (AtUse != SV) {
5240 OS << " --> ";
5241 AtUse->print(OS);
5242 }
5243
5244 if (L) {
Dan Gohman9e7d9882009-06-18 00:37:45 +00005245 OS << "\t\t" "Exits: ";
Dan Gohman0bba49c2009-07-07 17:06:11 +00005246 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmand594e6f2009-05-24 23:25:42 +00005247 if (!ExitValue->isLoopInvariant(L)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00005248 OS << "<<Unknown>>";
5249 } else {
5250 OS << *ExitValue;
5251 }
5252 }
5253
Chris Lattner53e677a2004-04-02 20:23:17 +00005254 OS << "\n";
5255 }
5256
Dan Gohmanf8a8be82009-04-21 23:15:49 +00005257 OS << "Determining loop execution counts for: " << F->getName() << "\n";
5258 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
5259 PrintLoopInfo(OS, &SE, *I);
Chris Lattner53e677a2004-04-02 20:23:17 +00005260}
Dan Gohmanb7ef7292009-04-21 00:47:46 +00005261