blob: c98414d66a4b456bdabe3622b0c305b8309fd216 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
Owen Andersonecd0cd72009-06-22 21:39:50 +000017// can handle. These classes are reference counted, managed by the const SCEV*
Dan Gohmanf17a25c2007-07-18 16:29:46 +000018// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
31//
32// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
36// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
62#define DEBUG_TYPE "scalar-evolution"
63#include "llvm/Analysis/ScalarEvolutionExpressions.h"
64#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
66#include "llvm/GlobalVariable.h"
67#include "llvm/Instructions.h"
68#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng98c073b2009-02-17 00:13:06 +000069#include "llvm/Analysis/Dominators.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070#include "llvm/Analysis/LoopInfo.h"
Dan Gohmana7726c32009-06-16 19:52:01 +000071#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000072#include "llvm/Assembly/Writer.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000073#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000074#include "llvm/Support/CommandLine.h"
75#include "llvm/Support/Compiler.h"
76#include "llvm/Support/ConstantRange.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000077#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000078#include "llvm/Support/InstIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079#include "llvm/Support/MathExtras.h"
Dan Gohman13058cc2009-04-21 00:47:46 +000080#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081#include "llvm/ADT/Statistic.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000082#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083#include <algorithm>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084using namespace llvm;
85
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086STATISTIC(NumArrayLenItCounts,
87 "Number of trip counts computed with array length");
88STATISTIC(NumTripCountsComputed,
89 "Number of loops with predictable loop counts");
90STATISTIC(NumTripCountsNotComputed,
91 "Number of loops without predictable loop counts");
92STATISTIC(NumBruteForceTripCountsComputed,
93 "Number of loops with trip counts computed by force");
94
Dan Gohman089efff2008-05-13 00:00:25 +000095static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000096MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
97 cl::desc("Maximum number of iterations SCEV will "
Dan Gohman9bc642f2009-06-24 04:48:43 +000098 "symbolically execute a constant "
99 "derived loop"),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000100 cl::init(100));
101
Dan Gohman089efff2008-05-13 00:00:25 +0000102static RegisterPass<ScalarEvolution>
103R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000104char ScalarEvolution::ID = 0;
105
106//===----------------------------------------------------------------------===//
107// SCEV class definitions
108//===----------------------------------------------------------------------===//
109
110//===----------------------------------------------------------------------===//
111// Implementation of the SCEV class.
112//
113SCEV::~SCEV() {}
114void SCEV::dump() const {
Dan Gohman13058cc2009-04-21 00:47:46 +0000115 print(errs());
116 errs() << '\n';
117}
118
119void SCEV::print(std::ostream &o) const {
120 raw_os_ostream OS(o);
121 print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122}
123
Dan Gohman7b560c42008-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 Gohmanf8bc8e82009-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}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000135
Dan Gohmanf05118e2009-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 Andersonb70139d2009-06-22 21:57:23 +0000142SCEVCouldNotCompute::SCEVCouldNotCompute() :
143 SCEV(scCouldNotCompute) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144
145bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
147 return false;
148}
149
150const Type *SCEVCouldNotCompute::getType() const {
151 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
152 return 0;
153}
154
155bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
156 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
157 return false;
158}
159
Dan Gohman9bc642f2009-06-24 04:48:43 +0000160const SCEV *
161SCEVCouldNotCompute::replaceSymbolicValuesWithConcrete(
162 const SCEV *Sym,
163 const SCEV *Conc,
164 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000165 return this;
166}
167
Dan Gohman13058cc2009-04-21 00:47:46 +0000168void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000169 OS << "***COULDNOTCOMPUTE***";
170}
171
172bool SCEVCouldNotCompute::classof(const SCEV *S) {
173 return S->getSCEVType() == scCouldNotCompute;
174}
175
Owen Andersonecd0cd72009-06-22 21:39:50 +0000176const SCEV* ScalarEvolution::getConstant(ConstantInt *V) {
Owen Andersonc48fbfe2009-06-22 18:25:46 +0000177 SCEVConstant *&R = SCEVConstants[V];
Owen Andersonb70139d2009-06-22 21:57:23 +0000178 if (R == 0) R = new SCEVConstant(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 return R;
180}
181
Owen Andersonecd0cd72009-06-22 21:39:50 +0000182const SCEV* ScalarEvolution::getConstant(const APInt& Val) {
Dan Gohman89f85052007-10-22 18:31:58 +0000183 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184}
185
Owen Andersonecd0cd72009-06-22 21:39:50 +0000186const SCEV*
Dan Gohman8fd520a2009-06-15 22:12:54 +0000187ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
188 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
189}
190
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191const Type *SCEVConstant::getType() const { return V->getType(); }
192
Dan Gohman13058cc2009-04-21 00:47:46 +0000193void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000194 WriteAsOperand(OS, V, false);
195}
196
Dan Gohman2a381532009-04-21 01:25:57 +0000197SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
Owen Andersonb70139d2009-06-22 21:57:23 +0000198 const SCEV* op, const Type *ty)
199 : SCEV(SCEVTy), Op(op), Ty(ty) {}
Dan Gohman2a381532009-04-21 01:25:57 +0000200
201bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
202 return Op->dominates(BB, DT);
203}
204
Owen Andersonb70139d2009-06-22 21:57:23 +0000205SCEVTruncateExpr::SCEVTruncateExpr(const SCEV* op, const Type *ty)
206 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000207 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
208 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000209 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210}
211
Dan Gohman13058cc2009-04-21 00:47:46 +0000212void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000213 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214}
215
Owen Andersonb70139d2009-06-22 21:57:23 +0000216SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEV* op, const Type *ty)
217 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000218 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
219 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000221}
222
Dan Gohman13058cc2009-04-21 00:47:46 +0000223void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000224 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225}
226
Owen Andersonb70139d2009-06-22 21:57:23 +0000227SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEV* op, const Type *ty)
228 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000229 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
230 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232}
233
Dan Gohman13058cc2009-04-21 00:47:46 +0000234void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000235 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236}
237
Dan Gohman13058cc2009-04-21 00:47:46 +0000238void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
240 const char *OpStr = getOperationStr();
241 OS << "(" << *Operands[0];
242 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
243 OS << OpStr << *Operands[i];
244 OS << ")";
245}
246
Dan Gohman9bc642f2009-06-24 04:48:43 +0000247const SCEV *
248SCEVCommutativeExpr::replaceSymbolicValuesWithConcrete(
249 const SCEV *Sym,
250 const SCEV *Conc,
251 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000253 const SCEV* H =
Dan Gohman89f85052007-10-22 18:31:58 +0000254 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000255 if (H != getOperand(i)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000256 SmallVector<const SCEV*, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 NewOps.reserve(getNumOperands());
258 for (unsigned j = 0; j != i; ++j)
259 NewOps.push_back(getOperand(j));
260 NewOps.push_back(H);
261 for (++i; i != e; ++i)
262 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000263 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000264
265 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000266 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000267 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000268 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000269 else if (isa<SCEVSMaxExpr>(this))
270 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000271 else if (isa<SCEVUMaxExpr>(this))
272 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 else
274 assert(0 && "Unknown commutative expr!");
275 }
276 }
277 return this;
278}
279
Dan Gohman72a8a022009-05-07 14:00:19 +0000280bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng98c073b2009-02-17 00:13:06 +0000281 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
282 if (!getOperand(i)->dominates(BB, DT))
283 return false;
284 }
285 return true;
286}
287
Evan Cheng98c073b2009-02-17 00:13:06 +0000288bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
289 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
290}
291
Dan Gohman13058cc2009-04-21 00:47:46 +0000292void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000293 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294}
295
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000296const Type *SCEVUDivExpr::getType() const {
Dan Gohman140f08f2009-05-26 17:44:05 +0000297 // In most cases the types of LHS and RHS will be the same, but in some
298 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
299 // depend on the type for correctness, but handling types carefully can
300 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
301 // a pointer type than the RHS, so use the RHS' type here.
302 return RHS->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000303}
304
Dan Gohman9bc642f2009-06-24 04:48:43 +0000305const SCEV *
306SCEVAddRecExpr::replaceSymbolicValuesWithConcrete(const SCEV *Sym,
307 const SCEV *Conc,
308 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000310 const SCEV* H =
Dan Gohman89f85052007-10-22 18:31:58 +0000311 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312 if (H != getOperand(i)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000313 SmallVector<const SCEV*, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000314 NewOps.reserve(getNumOperands());
315 for (unsigned j = 0; j != i; ++j)
316 NewOps.push_back(getOperand(j));
317 NewOps.push_back(H);
318 for (++i; i != e; ++i)
319 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000320 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000321
Dan Gohman89f85052007-10-22 18:31:58 +0000322 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000323 }
324 }
325 return this;
326}
327
328
329bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
330 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
331 // contain L and if the start is invariant.
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000332 // Add recurrences are never invariant in the function-body (null loop).
333 return QueryLoop &&
334 !QueryLoop->contains(L->getHeader()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000335 getOperand(0)->isLoopInvariant(QueryLoop);
336}
337
338
Dan Gohman13058cc2009-04-21 00:47:46 +0000339void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000340 OS << "{" << *Operands[0];
341 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
342 OS << ",+," << *Operands[i];
343 OS << "}<" << L->getHeader()->getName() + ">";
344}
345
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
347 // All non-instruction values are loop invariant. All instructions are loop
348 // invariant if they are not contained in the specified loop.
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000349 // Instructions are never considered invariant in the function body
350 // (null loop) because they are defined within the "loop".
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000351 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000352 return L && !L->contains(I->getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000353 return true;
354}
355
Evan Cheng98c073b2009-02-17 00:13:06 +0000356bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
357 if (Instruction *I = dyn_cast<Instruction>(getValue()))
358 return DT->dominates(I->getParent(), BB);
359 return true;
360}
361
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000362const Type *SCEVUnknown::getType() const {
363 return V->getType();
364}
365
Dan Gohman13058cc2009-04-21 00:47:46 +0000366void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000367 WriteAsOperand(OS, V, false);
368}
369
370//===----------------------------------------------------------------------===//
371// SCEV Utilities
372//===----------------------------------------------------------------------===//
373
374namespace {
375 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
376 /// than the complexity of the RHS. This comparator is used to canonicalize
377 /// expressions.
Dan Gohman5d486452009-05-07 14:39:04 +0000378 class VISIBILITY_HIDDEN SCEVComplexityCompare {
379 LoopInfo *LI;
380 public:
381 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
382
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000383 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman5d486452009-05-07 14:39:04 +0000384 // Primarily, sort the SCEVs by their getSCEVType().
385 if (LHS->getSCEVType() != RHS->getSCEVType())
386 return LHS->getSCEVType() < RHS->getSCEVType();
387
388 // Aside from the getSCEVType() ordering, the particular ordering
389 // isn't very important except that it's beneficial to be consistent,
390 // so that (a + b) and (b + a) don't end up as different expressions.
391
392 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
393 // not as complete as it could be.
394 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
395 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
396
Dan Gohmand0c01232009-05-19 02:15:55 +0000397 // Order pointer values after integer values. This helps SCEVExpander
398 // form GEPs.
399 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
400 return false;
401 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
402 return true;
403
Dan Gohman5d486452009-05-07 14:39:04 +0000404 // Compare getValueID values.
405 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
406 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
407
408 // Sort arguments by their position.
409 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
410 const Argument *RA = cast<Argument>(RU->getValue());
411 return LA->getArgNo() < RA->getArgNo();
412 }
413
414 // For instructions, compare their loop depth, and their opcode.
415 // This is pretty loose.
416 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
417 Instruction *RV = cast<Instruction>(RU->getValue());
418
419 // Compare loop depths.
420 if (LI->getLoopDepth(LV->getParent()) !=
421 LI->getLoopDepth(RV->getParent()))
422 return LI->getLoopDepth(LV->getParent()) <
423 LI->getLoopDepth(RV->getParent());
424
425 // Compare opcodes.
426 if (LV->getOpcode() != RV->getOpcode())
427 return LV->getOpcode() < RV->getOpcode();
428
429 // Compare the number of operands.
430 if (LV->getNumOperands() != RV->getNumOperands())
431 return LV->getNumOperands() < RV->getNumOperands();
432 }
433
434 return false;
435 }
436
Dan Gohman56fc8f12009-06-14 22:51:25 +0000437 // Compare constant values.
438 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
439 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
440 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
441 }
442
443 // Compare addrec loop depths.
444 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
445 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
446 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
447 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
448 }
Dan Gohman5d486452009-05-07 14:39:04 +0000449
450 // Lexicographically compare n-ary expressions.
451 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
452 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
453 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
454 if (i >= RC->getNumOperands())
455 return false;
456 if (operator()(LC->getOperand(i), RC->getOperand(i)))
457 return true;
458 if (operator()(RC->getOperand(i), LC->getOperand(i)))
459 return false;
460 }
461 return LC->getNumOperands() < RC->getNumOperands();
462 }
463
Dan Gohman6e10db12009-05-07 19:23:21 +0000464 // Lexicographically compare udiv expressions.
465 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
466 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
467 if (operator()(LC->getLHS(), RC->getLHS()))
468 return true;
469 if (operator()(RC->getLHS(), LC->getLHS()))
470 return false;
471 if (operator()(LC->getRHS(), RC->getRHS()))
472 return true;
473 if (operator()(RC->getRHS(), LC->getRHS()))
474 return false;
475 return false;
476 }
477
Dan Gohman5d486452009-05-07 14:39:04 +0000478 // Compare cast expressions by operand.
479 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
480 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
481 return operator()(LC->getOperand(), RC->getOperand());
482 }
483
484 assert(0 && "Unknown SCEV kind!");
485 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000486 }
487 };
488}
489
490/// GroupByComplexity - Given a list of SCEV objects, order them by their
491/// complexity, and group objects of the same complexity together by value.
492/// When this routine is finished, we know that any duplicates in the vector are
493/// consecutive and that complexity is monotonically increasing.
494///
495/// Note that we go take special precautions to ensure that we get determinstic
496/// results from this routine. In other words, we don't want the results of
497/// this to depend on where the addresses of various SCEV objects happened to
498/// land in memory.
499///
Owen Andersonecd0cd72009-06-22 21:39:50 +0000500static void GroupByComplexity(SmallVectorImpl<const SCEV*> &Ops,
Dan Gohman5d486452009-05-07 14:39:04 +0000501 LoopInfo *LI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000502 if (Ops.size() < 2) return; // Noop
503 if (Ops.size() == 2) {
504 // This is the common case, which also happens to be trivially simple.
505 // Special case it.
Dan Gohman5d486452009-05-07 14:39:04 +0000506 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000507 std::swap(Ops[0], Ops[1]);
508 return;
509 }
510
511 // Do the rough sort by complexity.
Dan Gohman5d486452009-05-07 14:39:04 +0000512 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000513
514 // Now that we are sorted by complexity, group elements of the same
515 // complexity. Note that this is, at worst, N^2, but the vector is likely to
516 // be extremely short in practice. Note that we take this approach because we
517 // do not want to depend on the addresses of the objects we are grouping.
518 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000519 const SCEV *S = Ops[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000520 unsigned Complexity = S->getSCEVType();
521
522 // If there are any objects of the same complexity and same value as this
523 // one, group them.
524 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
525 if (Ops[j] == S) { // Found a duplicate.
526 // Move it to immediately after i'th element.
527 std::swap(Ops[i+1], Ops[j]);
528 ++i; // no need to rescan it.
529 if (i == e-2) return; // Done!
530 }
531 }
532 }
533}
534
535
536
537//===----------------------------------------------------------------------===//
538// Simple SCEV method implementations
539//===----------------------------------------------------------------------===//
540
Eli Friedman7489ec92008-08-04 23:49:06 +0000541/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohmanc8a29272009-05-24 23:45:28 +0000542/// Assume, K > 0.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000543static const SCEV* BinomialCoefficient(const SCEV* It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000544 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000545 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000546 // Handle the simplest case efficiently.
547 if (K == 1)
548 return SE.getTruncateOrZeroExtend(It, ResultTy);
549
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000550 // We are using the following formula for BC(It, K):
551 //
552 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
553 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000554 // Suppose, W is the bitwidth of the return value. We must be prepared for
555 // overflow. Hence, we must assure that the result of our computation is
556 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
557 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000558 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000559 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohman9bc642f2009-06-24 04:48:43 +0000560 // is something like the following, where T is the number of factors of 2 in
Eli Friedman7489ec92008-08-04 23:49:06 +0000561 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
562 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000563 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000564 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000565 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000566 // This formula is trivially equivalent to the previous formula. However,
567 // this formula can be implemented much more efficiently. The trick is that
568 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
569 // arithmetic. To do exact division in modular arithmetic, all we have
570 // to do is multiply by the inverse. Therefore, this step can be done at
571 // width W.
Dan Gohman9bc642f2009-06-24 04:48:43 +0000572 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000573 // The next issue is how to safely do the division by 2^T. The way this
574 // is done is by doing the multiplication step at a width of at least W + T
575 // bits. This way, the bottom W+T bits of the product are accurate. Then,
576 // when we perform the division by 2^T (which is equivalent to a right shift
577 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
578 // truncated out after the division by 2^T.
579 //
580 // In comparison to just directly using the first formula, this technique
581 // is much more efficient; using the first formula requires W * K bits,
582 // but this formula less than W + K bits. Also, the first formula requires
583 // a division step, whereas this formula only requires multiplies and shifts.
584 //
585 // It doesn't matter whether the subtraction step is done in the calculation
586 // width or the input iteration count's width; if the subtraction overflows,
587 // the result must be zero anyway. We prefer here to do it in the width of
588 // the induction variable because it helps a lot for certain cases; CodeGen
589 // isn't smart enough to ignore the overflow, which leads to much less
590 // efficient code if the width of the subtraction is wider than the native
591 // register width.
592 //
593 // (It's possible to not widen at all by pulling out factors of 2 before
594 // the multiplication; for example, K=2 can be calculated as
595 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
596 // extra arithmetic, so it's not an obvious win, and it gets
597 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000598
Eli Friedman7489ec92008-08-04 23:49:06 +0000599 // Protection from insane SCEVs; this bound is conservative,
600 // but it probably doesn't matter.
601 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000602 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000603
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000604 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000605
Eli Friedman7489ec92008-08-04 23:49:06 +0000606 // Calculate K! / 2^T and T; we divide out the factors of two before
607 // multiplying for calculating K! / 2^T to avoid overflow.
608 // Other overflow doesn't matter because we only care about the bottom
609 // W bits of the result.
610 APInt OddFactorial(W, 1);
611 unsigned T = 1;
612 for (unsigned i = 3; i <= K; ++i) {
613 APInt Mult(W, i);
614 unsigned TwoFactors = Mult.countTrailingZeros();
615 T += TwoFactors;
616 Mult = Mult.lshr(TwoFactors);
617 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000618 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000619
Eli Friedman7489ec92008-08-04 23:49:06 +0000620 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000621 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000622
623 // Calcuate 2^T, at width T+W.
624 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
625
626 // Calculate the multiplicative inverse of K! / 2^T;
627 // this multiplication factor will perform the exact division by
628 // K! / 2^T.
629 APInt Mod = APInt::getSignedMinValue(W+1);
630 APInt MultiplyFactor = OddFactorial.zext(W+1);
631 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
632 MultiplyFactor = MultiplyFactor.trunc(W);
633
634 // Calculate the product, at width T+W
635 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
Owen Andersonecd0cd72009-06-22 21:39:50 +0000636 const SCEV* Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman7489ec92008-08-04 23:49:06 +0000637 for (unsigned i = 1; i != K; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000638 const SCEV* S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedman7489ec92008-08-04 23:49:06 +0000639 Dividend = SE.getMulExpr(Dividend,
640 SE.getTruncateOrZeroExtend(S, CalculationTy));
641 }
642
643 // Divide by 2^T
Owen Andersonecd0cd72009-06-22 21:39:50 +0000644 const SCEV* DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman7489ec92008-08-04 23:49:06 +0000645
646 // Truncate the result, and divide by K! / 2^T.
647
648 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
649 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000650}
651
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000652/// evaluateAtIteration - Return the value of this chain of recurrences at
653/// the specified iteration number. We can evaluate this recurrence by
654/// multiplying each element in the chain by the binomial coefficient
655/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
656///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000657/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000659/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000660///
Owen Andersonecd0cd72009-06-22 21:39:50 +0000661const SCEV* SCEVAddRecExpr::evaluateAtIteration(const SCEV* It,
Dan Gohman89f85052007-10-22 18:31:58 +0000662 ScalarEvolution &SE) const {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000663 const SCEV* Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000665 // The computation is correct in the face of overflow provided that the
666 // multiplication is performed _after_ the evaluation of the binomial
667 // coefficient.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000668 const SCEV* Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000669 if (isa<SCEVCouldNotCompute>(Coeff))
670 return Coeff;
671
672 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673 }
674 return Result;
675}
676
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677//===----------------------------------------------------------------------===//
678// SCEV Expression folder implementations
679//===----------------------------------------------------------------------===//
680
Owen Andersonecd0cd72009-06-22 21:39:50 +0000681const SCEV* ScalarEvolution::getTruncateExpr(const SCEV* Op,
Dan Gohman9c8abcc2009-05-01 16:44:56 +0000682 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000683 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000684 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000685 assert(isSCEVable(Ty) &&
686 "This is not a conversion to a SCEVable type!");
687 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000688
Dan Gohmanc76b5452009-05-04 22:02:23 +0000689 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman55788cf2009-06-24 00:38:39 +0000690 return getConstant(
691 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000692
Dan Gohman1a5c4992009-04-22 16:20:48 +0000693 // trunc(trunc(x)) --> trunc(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000694 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000695 return getTruncateExpr(ST->getOperand(), Ty);
696
Nick Lewycky37d04642009-04-23 05:15:08 +0000697 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000698 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000699 return getTruncateOrSignExtend(SS->getOperand(), Ty);
700
701 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000702 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000703 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
704
Dan Gohman1c0aa2c2009-06-18 16:24:47 +0000705 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000706 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000707 SmallVector<const SCEV*, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000708 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman45b3b542009-05-08 21:03:19 +0000709 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
710 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000711 }
712
Owen Andersonc48fbfe2009-06-22 18:25:46 +0000713 SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)];
Owen Andersonb70139d2009-06-22 21:57:23 +0000714 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000715 return Result;
716}
717
Owen Andersonecd0cd72009-06-22 21:39:50 +0000718const SCEV* ScalarEvolution::getZeroExtendExpr(const SCEV* Op,
Dan Gohman36d40922009-04-16 19:25:55 +0000719 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000720 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000721 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000722 assert(isSCEVable(Ty) &&
723 "This is not a conversion to a SCEVable type!");
724 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000725
Dan Gohmanc76b5452009-05-04 22:02:23 +0000726 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000727 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000728 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
729 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohman55788cf2009-06-24 00:38:39 +0000730 return getConstant(cast<ConstantInt>(C));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000731 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000732
Dan Gohman1a5c4992009-04-22 16:20:48 +0000733 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000734 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000735 return getZeroExtendExpr(SZ->getOperand(), Ty);
736
Dan Gohmana9dba962009-04-27 20:16:15 +0000737 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000738 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000739 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000740 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000741 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000742 if (AR->isAffine()) {
743 // Check whether the backedge-taken count is SCEVCouldNotCompute.
744 // Note that this serves two purposes: It filters out loops that are
745 // simply not analyzable, and it covers the case where this code is
746 // being called from within backedge-taken count analysis, such that
747 // attempting to ask for the backedge-taken count would likely result
748 // in infinite recursion. In the later case, the analysis code will
749 // cope with a conservative value, and it will take care to purge
750 // that value once it has finished.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000751 const SCEV* MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000752 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000753 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000754 // overflow.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000755 const SCEV* Start = AR->getStart();
756 const SCEV* Step = AR->getStepRecurrence(*this);
Dan Gohmana9dba962009-04-27 20:16:15 +0000757
758 // Check whether the backedge-taken count can be losslessly casted to
759 // the addrec's type. The count is always unsigned.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000760 const SCEV* CastedMaxBECount =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000761 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Owen Andersonecd0cd72009-06-22 21:39:50 +0000762 const SCEV* RecastedMaxBECount =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000763 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
764 if (MaxBECount == RecastedMaxBECount) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000765 const Type *WideTy =
766 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000767 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000768 const SCEV* ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000769 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000770 getTruncateOrZeroExtend(Step, Start->getType()));
Owen Andersonecd0cd72009-06-22 21:39:50 +0000771 const SCEV* Add = getAddExpr(Start, ZMul);
772 const SCEV* OperandExtendedAdd =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000773 getAddExpr(getZeroExtendExpr(Start, WideTy),
774 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
775 getZeroExtendExpr(Step, WideTy)));
776 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000777 // Return the expression with the addrec on the outside.
778 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
779 getZeroExtendExpr(Step, Ty),
780 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000781
782 // Similar to above, only this time treat the step value as signed.
783 // This covers loops that count down.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000784 const SCEV* SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000785 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000786 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000787 Add = getAddExpr(Start, SMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000788 OperandExtendedAdd =
789 getAddExpr(getZeroExtendExpr(Start, WideTy),
790 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
791 getSignExtendExpr(Step, WideTy)));
792 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000793 // Return the expression with the addrec on the outside.
794 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
795 getSignExtendExpr(Step, Ty),
796 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000797 }
798 }
799 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000800
Owen Andersonc48fbfe2009-06-22 18:25:46 +0000801 SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)];
Owen Andersonb70139d2009-06-22 21:57:23 +0000802 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000803 return Result;
804}
805
Owen Andersonecd0cd72009-06-22 21:39:50 +0000806const SCEV* ScalarEvolution::getSignExtendExpr(const SCEV* Op,
Dan Gohmana9dba962009-04-27 20:16:15 +0000807 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000808 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000809 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000810 assert(isSCEVable(Ty) &&
811 "This is not a conversion to a SCEVable type!");
812 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000813
Dan Gohmanc76b5452009-05-04 22:02:23 +0000814 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000815 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000816 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
817 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohman55788cf2009-06-24 00:38:39 +0000818 return getConstant(cast<ConstantInt>(C));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000819 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000820
Dan Gohman1a5c4992009-04-22 16:20:48 +0000821 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000822 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000823 return getSignExtendExpr(SS->getOperand(), Ty);
824
Dan Gohmana9dba962009-04-27 20:16:15 +0000825 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000826 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000827 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000828 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000829 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000830 if (AR->isAffine()) {
831 // Check whether the backedge-taken count is SCEVCouldNotCompute.
832 // Note that this serves two purposes: It filters out loops that are
833 // simply not analyzable, and it covers the case where this code is
834 // being called from within backedge-taken count analysis, such that
835 // attempting to ask for the backedge-taken count would likely result
836 // in infinite recursion. In the later case, the analysis code will
837 // cope with a conservative value, and it will take care to purge
838 // that value once it has finished.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000839 const SCEV* MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000840 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000841 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000842 // overflow.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000843 const SCEV* Start = AR->getStart();
844 const SCEV* Step = AR->getStepRecurrence(*this);
Dan Gohmana9dba962009-04-27 20:16:15 +0000845
846 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000847 // the addrec's type. The count is always unsigned.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000848 const SCEV* CastedMaxBECount =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000849 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Owen Andersonecd0cd72009-06-22 21:39:50 +0000850 const SCEV* RecastedMaxBECount =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000851 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
852 if (MaxBECount == RecastedMaxBECount) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000853 const Type *WideTy =
854 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000855 // Check whether Start+Step*MaxBECount has no signed overflow.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000856 const SCEV* SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000857 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000858 getTruncateOrSignExtend(Step, Start->getType()));
Owen Andersonecd0cd72009-06-22 21:39:50 +0000859 const SCEV* Add = getAddExpr(Start, SMul);
860 const SCEV* OperandExtendedAdd =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000861 getAddExpr(getSignExtendExpr(Start, WideTy),
862 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
863 getSignExtendExpr(Step, WideTy)));
864 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000865 // Return the expression with the addrec on the outside.
866 return getAddRecExpr(getSignExtendExpr(Start, Ty),
867 getSignExtendExpr(Step, Ty),
868 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000869 }
870 }
871 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000872
Owen Andersonc48fbfe2009-06-22 18:25:46 +0000873 SCEVSignExtendExpr *&Result = SCEVSignExtends[std::make_pair(Op, Ty)];
Owen Andersonb70139d2009-06-22 21:57:23 +0000874 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000875 return Result;
876}
877
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000878/// getAnyExtendExpr - Return a SCEV for the given operand extended with
879/// unspecified bits out to the given type.
880///
Owen Andersonecd0cd72009-06-22 21:39:50 +0000881const SCEV* ScalarEvolution::getAnyExtendExpr(const SCEV* Op,
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000882 const Type *Ty) {
883 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
884 "This is not an extending conversion!");
885 assert(isSCEVable(Ty) &&
886 "This is not a conversion to a SCEVable type!");
887 Ty = getEffectiveSCEVType(Ty);
888
889 // Sign-extend negative constants.
890 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
891 if (SC->getValue()->getValue().isNegative())
892 return getSignExtendExpr(Op, Ty);
893
894 // Peel off a truncate cast.
895 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000896 const SCEV* NewOp = T->getOperand();
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000897 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
898 return getAnyExtendExpr(NewOp, Ty);
899 return getTruncateOrNoop(NewOp, Ty);
900 }
901
902 // Next try a zext cast. If the cast is folded, use it.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000903 const SCEV* ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000904 if (!isa<SCEVZeroExtendExpr>(ZExt))
905 return ZExt;
906
907 // Next try a sext cast. If the cast is folded, use it.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000908 const SCEV* SExt = getSignExtendExpr(Op, Ty);
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000909 if (!isa<SCEVSignExtendExpr>(SExt))
910 return SExt;
911
912 // If the expression is obviously signed, use the sext cast value.
913 if (isa<SCEVSMaxExpr>(Op))
914 return SExt;
915
916 // Absent any other information, use the zext cast value.
917 return ZExt;
918}
919
Dan Gohman27bd4cb2009-06-14 22:58:51 +0000920/// CollectAddOperandsWithScales - Process the given Ops list, which is
921/// a list of operands to be added under the given scale, update the given
922/// map. This is a helper function for getAddRecExpr. As an example of
923/// what it does, given a sequence of operands that would form an add
924/// expression like this:
925///
926/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
927///
928/// where A and B are constants, update the map with these values:
929///
930/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
931///
932/// and add 13 + A*B*29 to AccumulatedConstant.
933/// This will allow getAddRecExpr to produce this:
934///
935/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
936///
937/// This form often exposes folding opportunities that are hidden in
938/// the original operand list.
939///
940/// Return true iff it appears that any interesting folding opportunities
941/// may be exposed. This helps getAddRecExpr short-circuit extra work in
942/// the common case where no interesting opportunities are present, and
943/// is also used as a check to avoid infinite recursion.
944///
945static bool
Owen Andersonecd0cd72009-06-22 21:39:50 +0000946CollectAddOperandsWithScales(DenseMap<const SCEV*, APInt> &M,
947 SmallVector<const SCEV*, 8> &NewOps,
Dan Gohman27bd4cb2009-06-14 22:58:51 +0000948 APInt &AccumulatedConstant,
Owen Andersonecd0cd72009-06-22 21:39:50 +0000949 const SmallVectorImpl<const SCEV*> &Ops,
Dan Gohman27bd4cb2009-06-14 22:58:51 +0000950 const APInt &Scale,
951 ScalarEvolution &SE) {
952 bool Interesting = false;
953
954 // Iterate over the add operands.
955 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
956 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
957 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
958 APInt NewScale =
959 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
960 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
961 // A multiplication of a constant with another add; recurse.
962 Interesting |=
963 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
964 cast<SCEVAddExpr>(Mul->getOperand(1))
965 ->getOperands(),
966 NewScale, SE);
967 } else {
968 // A multiplication of a constant with some other value. Update
969 // the map.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000970 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
971 const SCEV* Key = SE.getMulExpr(MulOps);
972 std::pair<DenseMap<const SCEV*, APInt>::iterator, bool> Pair =
Dan Gohman27bd4cb2009-06-14 22:58:51 +0000973 M.insert(std::make_pair(Key, APInt()));
974 if (Pair.second) {
975 Pair.first->second = NewScale;
976 NewOps.push_back(Pair.first->first);
977 } else {
978 Pair.first->second += NewScale;
979 // The map already had an entry for this value, which may indicate
980 // a folding opportunity.
981 Interesting = true;
982 }
983 }
984 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
985 // Pull a buried constant out to the outside.
986 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
987 Interesting = true;
988 AccumulatedConstant += Scale * C->getValue()->getValue();
989 } else {
990 // An ordinary operand. Update the map.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000991 std::pair<DenseMap<const SCEV*, APInt>::iterator, bool> Pair =
Dan Gohman27bd4cb2009-06-14 22:58:51 +0000992 M.insert(std::make_pair(Ops[i], APInt()));
993 if (Pair.second) {
994 Pair.first->second = Scale;
995 NewOps.push_back(Pair.first->first);
996 } else {
997 Pair.first->second += Scale;
998 // The map already had an entry for this value, which may indicate
999 // a folding opportunity.
1000 Interesting = true;
1001 }
1002 }
1003 }
1004
1005 return Interesting;
1006}
1007
1008namespace {
1009 struct APIntCompare {
1010 bool operator()(const APInt &LHS, const APInt &RHS) const {
1011 return LHS.ult(RHS);
1012 }
1013 };
1014}
1015
Dan Gohmanc8a29272009-05-24 23:45:28 +00001016/// getAddExpr - Get a canonical add expression, or something simpler if
1017/// possible.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001018const SCEV* ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV*> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001019 assert(!Ops.empty() && "Cannot get empty add!");
1020 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001021#ifndef NDEBUG
1022 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1023 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1024 getEffectiveSCEVType(Ops[0]->getType()) &&
1025 "SCEVAddExpr operand types don't match!");
1026#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001027
1028 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001029 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001030
1031 // If there are any constants, fold them together.
1032 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001033 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001034 ++Idx;
1035 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001036 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001037 // We found two constants, fold them together!
Dan Gohman02ff9392009-06-14 22:47:23 +00001038 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1039 RHSC->getValue()->getValue());
Dan Gohman68f23e82009-06-14 22:53:57 +00001040 if (Ops.size() == 2) return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001041 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001042 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043 }
1044
1045 // If we are left with a constant zero being added, strip it off.
1046 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1047 Ops.erase(Ops.begin());
1048 --Idx;
1049 }
1050 }
1051
1052 if (Ops.size() == 1) return Ops[0];
1053
1054 // Okay, check to see if the same value occurs in the operand list twice. If
1055 // so, merge them together into an multiply expression. Since we sorted the
1056 // list, these values are required to be adjacent.
1057 const Type *Ty = Ops[0]->getType();
1058 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1059 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1060 // Found a match, merge the two values into a multiply, and add any
1061 // remaining values to the result.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001062 const SCEV* Two = getIntegerSCEV(2, Ty);
1063 const SCEV* Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001064 if (Ops.size() == 2)
1065 return Mul;
1066 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1067 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +00001068 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001069 }
1070
Dan Gohman45b3b542009-05-08 21:03:19 +00001071 // Check for truncates. If all the operands are truncated from the same
1072 // type, see if factoring out the truncate would permit the result to be
1073 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1074 // if the contents of the resulting outer trunc fold to something simple.
1075 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1076 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1077 const Type *DstType = Trunc->getType();
1078 const Type *SrcType = Trunc->getOperand()->getType();
Owen Andersonecd0cd72009-06-22 21:39:50 +00001079 SmallVector<const SCEV*, 8> LargeOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001080 bool Ok = true;
1081 // Check all the operands to see if they can be represented in the
1082 // source type of the truncate.
1083 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1084 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1085 if (T->getOperand()->getType() != SrcType) {
1086 Ok = false;
1087 break;
1088 }
1089 LargeOps.push_back(T->getOperand());
1090 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1091 // This could be either sign or zero extension, but sign extension
1092 // is much more likely to be foldable here.
1093 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1094 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001095 SmallVector<const SCEV*, 8> LargeMulOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001096 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1097 if (const SCEVTruncateExpr *T =
1098 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1099 if (T->getOperand()->getType() != SrcType) {
1100 Ok = false;
1101 break;
1102 }
1103 LargeMulOps.push_back(T->getOperand());
1104 } else if (const SCEVConstant *C =
1105 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1106 // This could be either sign or zero extension, but sign extension
1107 // is much more likely to be foldable here.
1108 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1109 } else {
1110 Ok = false;
1111 break;
1112 }
1113 }
1114 if (Ok)
1115 LargeOps.push_back(getMulExpr(LargeMulOps));
1116 } else {
1117 Ok = false;
1118 break;
1119 }
1120 }
1121 if (Ok) {
1122 // Evaluate the expression in the larger type.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001123 const SCEV* Fold = getAddExpr(LargeOps);
Dan Gohman45b3b542009-05-08 21:03:19 +00001124 // If it folds to something simple, use it. Otherwise, don't.
1125 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1126 return getTruncateExpr(Fold, DstType);
1127 }
1128 }
1129
1130 // Skip past any other cast SCEVs.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001131 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1132 ++Idx;
1133
1134 // If there are add operands they would be next.
1135 if (Idx < Ops.size()) {
1136 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001137 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001138 // If we have an add, expand the add operands onto the end of the operands
1139 // list.
1140 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1141 Ops.erase(Ops.begin()+Idx);
1142 DeletedAdd = true;
1143 }
1144
1145 // If we deleted at least one add, we added operands to the end of the list,
1146 // and they are not necessarily sorted. Recurse to resort and resimplify
1147 // any operands we just aquired.
1148 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +00001149 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001150 }
1151
1152 // Skip over the add expression until we get to a multiply.
1153 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1154 ++Idx;
1155
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001156 // Check to see if there are any folding opportunities present with
1157 // operands multiplied by constant values.
1158 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1159 uint64_t BitWidth = getTypeSizeInBits(Ty);
Owen Andersonecd0cd72009-06-22 21:39:50 +00001160 DenseMap<const SCEV*, APInt> M;
1161 SmallVector<const SCEV*, 8> NewOps;
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001162 APInt AccumulatedConstant(BitWidth, 0);
1163 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1164 Ops, APInt(BitWidth, 1), *this)) {
1165 // Some interesting folding opportunity is present, so its worthwhile to
1166 // re-generate the operands list. Group the operands by constant scale,
1167 // to avoid multiplying by the same constant scale multiple times.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001168 std::map<APInt, SmallVector<const SCEV*, 4>, APIntCompare> MulOpLists;
1169 for (SmallVector<const SCEV*, 8>::iterator I = NewOps.begin(),
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001170 E = NewOps.end(); I != E; ++I)
1171 MulOpLists[M.find(*I)->second].push_back(*I);
1172 // Re-generate the operands list.
1173 Ops.clear();
1174 if (AccumulatedConstant != 0)
1175 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohman9bc642f2009-06-24 04:48:43 +00001176 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1177 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001178 if (I->first != 0)
Dan Gohman9bc642f2009-06-24 04:48:43 +00001179 Ops.push_back(getMulExpr(getConstant(I->first),
1180 getAddExpr(I->second)));
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001181 if (Ops.empty())
1182 return getIntegerSCEV(0, Ty);
1183 if (Ops.size() == 1)
1184 return Ops[0];
1185 return getAddExpr(Ops);
1186 }
1187 }
1188
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001189 // If we are adding something to a multiply expression, make sure the
1190 // something is not already an operand of the multiply. If so, merge it into
1191 // the multiply.
1192 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001193 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001194 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001195 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001196 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman02ff9392009-06-14 22:47:23 +00001197 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001198 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Owen Andersonecd0cd72009-06-22 21:39:50 +00001199 const SCEV* InnerMul = Mul->getOperand(MulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001200 if (Mul->getNumOperands() != 2) {
1201 // If the multiply has more than two operands, we must get the
1202 // Y*Z term.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001203 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin(), Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001204 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001205 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001206 }
Owen Andersonecd0cd72009-06-22 21:39:50 +00001207 const SCEV* One = getIntegerSCEV(1, Ty);
1208 const SCEV* AddOne = getAddExpr(InnerMul, One);
1209 const SCEV* OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001210 if (Ops.size() == 2) return OuterMul;
1211 if (AddOp < Idx) {
1212 Ops.erase(Ops.begin()+AddOp);
1213 Ops.erase(Ops.begin()+Idx-1);
1214 } else {
1215 Ops.erase(Ops.begin()+Idx);
1216 Ops.erase(Ops.begin()+AddOp-1);
1217 }
1218 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001219 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001220 }
1221
1222 // Check this multiply against other multiplies being added together.
1223 for (unsigned OtherMulIdx = Idx+1;
1224 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1225 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001226 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001227 // If MulOp occurs in OtherMul, we can fold the two multiplies
1228 // together.
1229 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1230 OMulOp != e; ++OMulOp)
1231 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1232 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Owen Andersonecd0cd72009-06-22 21:39:50 +00001233 const SCEV* InnerMul1 = Mul->getOperand(MulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001234 if (Mul->getNumOperands() != 2) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00001235 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1236 Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001237 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001238 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001239 }
Owen Andersonecd0cd72009-06-22 21:39:50 +00001240 const SCEV* InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001241 if (OtherMul->getNumOperands() != 2) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00001242 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
1243 OtherMul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001244 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001245 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001246 }
Owen Andersonecd0cd72009-06-22 21:39:50 +00001247 const SCEV* InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1248 const SCEV* OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001249 if (Ops.size() == 2) return OuterMul;
1250 Ops.erase(Ops.begin()+Idx);
1251 Ops.erase(Ops.begin()+OtherMulIdx-1);
1252 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001253 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001254 }
1255 }
1256 }
1257 }
1258
1259 // If there are any add recurrences in the operands list, see if any other
1260 // added values are loop invariant. If so, we can fold them into the
1261 // recurrence.
1262 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1263 ++Idx;
1264
1265 // Scan over all recurrences, trying to fold loop invariants into them.
1266 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1267 // Scan all of the other operands to this add and add them to the vector if
1268 // they are loop invariant w.r.t. the recurrence.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001269 SmallVector<const SCEV*, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001270 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001271 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1272 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1273 LIOps.push_back(Ops[i]);
1274 Ops.erase(Ops.begin()+i);
1275 --i; --e;
1276 }
1277
1278 // If we found some loop invariants, fold them into the recurrence.
1279 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001280 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001281 LIOps.push_back(AddRec->getStart());
1282
Owen Andersonecd0cd72009-06-22 21:39:50 +00001283 SmallVector<const SCEV*, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001284 AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001285 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001286
Owen Andersonecd0cd72009-06-22 21:39:50 +00001287 const SCEV* NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001288 // If all of the other operands were loop invariant, we are done.
1289 if (Ops.size() == 1) return NewRec;
1290
1291 // Otherwise, add the folded AddRec by the non-liv parts.
1292 for (unsigned i = 0;; ++i)
1293 if (Ops[i] == AddRec) {
1294 Ops[i] = NewRec;
1295 break;
1296 }
Dan Gohman89f85052007-10-22 18:31:58 +00001297 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001298 }
1299
1300 // Okay, if there weren't any loop invariants to be folded, check to see if
1301 // there are multiple AddRec's with the same loop induction variable being
1302 // added together. If so, we can fold them.
1303 for (unsigned OtherIdx = Idx+1;
1304 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1305 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001306 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001307 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1308 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Dan Gohman9bc642f2009-06-24 04:48:43 +00001309 SmallVector<const SCEV *, 4> NewOps(AddRec->op_begin(),
1310 AddRec->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001311 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1312 if (i >= NewOps.size()) {
1313 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1314 OtherAddRec->op_end());
1315 break;
1316 }
Dan Gohman89f85052007-10-22 18:31:58 +00001317 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001318 }
Owen Andersonecd0cd72009-06-22 21:39:50 +00001319 const SCEV* NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001320
1321 if (Ops.size() == 2) return NewAddRec;
1322
1323 Ops.erase(Ops.begin()+Idx);
1324 Ops.erase(Ops.begin()+OtherIdx-1);
1325 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001326 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001327 }
1328 }
1329
1330 // Otherwise couldn't fold anything into this recurrence. Move onto the
1331 // next one.
1332 }
1333
1334 // Okay, it looks like we really DO need an add expr. Check to see if we
1335 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001336 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001337 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001338 SCEVOps)];
Owen Andersonb70139d2009-06-22 21:57:23 +00001339 if (Result == 0) Result = new SCEVAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001340 return Result;
1341}
1342
1343
Dan Gohmanc8a29272009-05-24 23:45:28 +00001344/// getMulExpr - Get a canonical multiply expression, or something simpler if
1345/// possible.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001346const SCEV* ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV*> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001347 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana77b3d42009-05-18 15:44:58 +00001348#ifndef NDEBUG
1349 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1350 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1351 getEffectiveSCEVType(Ops[0]->getType()) &&
1352 "SCEVMulExpr operand types don't match!");
1353#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001354
1355 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001356 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001357
1358 // If there are any constants, fold them together.
1359 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001360 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001361
1362 // C1*(C2+V) -> C1*C2 + C1*V
1363 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001364 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001365 if (Add->getNumOperands() == 2 &&
1366 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001367 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1368 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001369
1370
1371 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001372 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001373 // We found two constants, fold them together!
Dan Gohman9bc642f2009-06-24 04:48:43 +00001374 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001375 RHSC->getValue()->getValue());
1376 Ops[0] = getConstant(Fold);
1377 Ops.erase(Ops.begin()+1); // Erase the folded element
1378 if (Ops.size() == 1) return Ops[0];
1379 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001380 }
1381
1382 // If we are left with a constant one being multiplied, strip it off.
1383 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1384 Ops.erase(Ops.begin());
1385 --Idx;
1386 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1387 // If we have a multiply of zero, it will always be zero.
1388 return Ops[0];
1389 }
1390 }
1391
1392 // Skip over the add expression until we get to a multiply.
1393 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1394 ++Idx;
1395
1396 if (Ops.size() == 1)
1397 return Ops[0];
1398
1399 // If there are mul operands inline them all into this expression.
1400 if (Idx < Ops.size()) {
1401 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001402 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001403 // If we have an mul, expand the mul operands onto the end of the operands
1404 // list.
1405 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1406 Ops.erase(Ops.begin()+Idx);
1407 DeletedMul = true;
1408 }
1409
1410 // If we deleted at least one mul, we added operands to the end of the list,
1411 // and they are not necessarily sorted. Recurse to resort and resimplify
1412 // any operands we just aquired.
1413 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001414 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001415 }
1416
1417 // If there are any add recurrences in the operands list, see if any other
1418 // added values are loop invariant. If so, we can fold them into the
1419 // recurrence.
1420 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1421 ++Idx;
1422
1423 // Scan over all recurrences, trying to fold loop invariants into them.
1424 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1425 // Scan all of the other operands to this mul and add them to the vector if
1426 // they are loop invariant w.r.t. the recurrence.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001427 SmallVector<const SCEV*, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001428 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001429 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1430 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1431 LIOps.push_back(Ops[i]);
1432 Ops.erase(Ops.begin()+i);
1433 --i; --e;
1434 }
1435
1436 // If we found some loop invariants, fold them into the recurrence.
1437 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001438 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Owen Andersonecd0cd72009-06-22 21:39:50 +00001439 SmallVector<const SCEV*, 4> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001440 NewOps.reserve(AddRec->getNumOperands());
1441 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001442 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001443 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001444 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001445 } else {
1446 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001447 SmallVector<const SCEV*, 4> MulOps(LIOps.begin(), LIOps.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001448 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001449 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001450 }
1451 }
1452
Owen Andersonecd0cd72009-06-22 21:39:50 +00001453 const SCEV* NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001454
1455 // If all of the other operands were loop invariant, we are done.
1456 if (Ops.size() == 1) return NewRec;
1457
1458 // Otherwise, multiply the folded AddRec by the non-liv parts.
1459 for (unsigned i = 0;; ++i)
1460 if (Ops[i] == AddRec) {
1461 Ops[i] = NewRec;
1462 break;
1463 }
Dan Gohman89f85052007-10-22 18:31:58 +00001464 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001465 }
1466
1467 // Okay, if there weren't any loop invariants to be folded, check to see if
1468 // there are multiple AddRec's with the same loop induction variable being
1469 // multiplied together. If so, we can fold them.
1470 for (unsigned OtherIdx = Idx+1;
1471 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1472 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001473 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001474 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1475 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001476 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Owen Andersonecd0cd72009-06-22 21:39:50 +00001477 const SCEV* NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001478 G->getStart());
Owen Andersonecd0cd72009-06-22 21:39:50 +00001479 const SCEV* B = F->getStepRecurrence(*this);
1480 const SCEV* D = G->getStepRecurrence(*this);
1481 const SCEV* NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman89f85052007-10-22 18:31:58 +00001482 getMulExpr(G, B),
1483 getMulExpr(B, D));
Owen Andersonecd0cd72009-06-22 21:39:50 +00001484 const SCEV* NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman89f85052007-10-22 18:31:58 +00001485 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001486 if (Ops.size() == 2) return NewAddRec;
1487
1488 Ops.erase(Ops.begin()+Idx);
1489 Ops.erase(Ops.begin()+OtherIdx-1);
1490 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001491 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001492 }
1493 }
1494
1495 // Otherwise couldn't fold anything into this recurrence. Move onto the
1496 // next one.
1497 }
1498
1499 // Okay, it looks like we really DO need an mul expr. Check to see if we
1500 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001501 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001502 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001503 SCEVOps)];
1504 if (Result == 0)
Owen Andersonb70139d2009-06-22 21:57:23 +00001505 Result = new SCEVMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001506 return Result;
1507}
1508
Dan Gohmanc8a29272009-05-24 23:45:28 +00001509/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1510/// possible.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001511const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
1512 const SCEV *RHS) {
Dan Gohmana77b3d42009-05-18 15:44:58 +00001513 assert(getEffectiveSCEVType(LHS->getType()) ==
1514 getEffectiveSCEVType(RHS->getType()) &&
1515 "SCEVUDivExpr operand types don't match!");
1516
Dan Gohmanc76b5452009-05-04 22:02:23 +00001517 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001518 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001519 return LHS; // X udiv 1 --> x
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001520 if (RHSC->isZero())
1521 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001522
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001523 // Determine if the division can be folded into the operands of
1524 // its operands.
1525 // TODO: Generalize this to non-constants by using known-bits information.
1526 const Type *Ty = LHS->getType();
1527 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1528 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1529 // For non-power-of-two values, effectively round the value up to the
1530 // nearest power of two.
1531 if (!RHSC->getValue()->getValue().isPowerOf2())
1532 ++MaxShiftAmt;
1533 const IntegerType *ExtTy =
1534 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1535 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1536 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1537 if (const SCEVConstant *Step =
1538 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1539 if (!Step->getValue()->getValue()
1540 .urem(RHSC->getValue()->getValue()) &&
Dan Gohman14374d32009-05-08 23:11:16 +00001541 getZeroExtendExpr(AR, ExtTy) ==
1542 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1543 getZeroExtendExpr(Step, ExtTy),
1544 AR->getLoop())) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001545 SmallVector<const SCEV*, 4> Operands;
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001546 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1547 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1548 return getAddRecExpr(Operands, AR->getLoop());
1549 }
1550 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001551 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001552 SmallVector<const SCEV*, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001553 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1554 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1555 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001556 // Find an operand that's safely divisible.
1557 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001558 const SCEV* Op = M->getOperand(i);
1559 const SCEV* Div = getUDivExpr(Op, RHSC);
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001560 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001561 const SmallVectorImpl<const SCEV*> &MOperands = M->getOperands();
1562 Operands = SmallVector<const SCEV*, 4>(MOperands.begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001563 MOperands.end());
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001564 Operands[i] = Div;
1565 return getMulExpr(Operands);
1566 }
1567 }
Dan Gohman14374d32009-05-08 23:11:16 +00001568 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001569 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001570 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001571 SmallVector<const SCEV*, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001572 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1573 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1574 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1575 Operands.clear();
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001576 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001577 const SCEV* Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001578 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1579 break;
1580 Operands.push_back(Op);
1581 }
1582 if (Operands.size() == A->getNumOperands())
1583 return getAddExpr(Operands);
1584 }
Dan Gohman14374d32009-05-08 23:11:16 +00001585 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001586
1587 // Fold if both operands are constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001588 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001589 Constant *LHSCV = LHSC->getValue();
1590 Constant *RHSCV = RHSC->getValue();
Dan Gohman55788cf2009-06-24 00:38:39 +00001591 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1592 RHSCV)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001593 }
1594 }
1595
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001596 SCEVUDivExpr *&Result = SCEVUDivs[std::make_pair(LHS, RHS)];
Owen Andersonb70139d2009-06-22 21:57:23 +00001597 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001598 return Result;
1599}
1600
1601
Dan Gohmanc8a29272009-05-24 23:45:28 +00001602/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1603/// Simplify the expression as much as possible.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001604const SCEV* ScalarEvolution::getAddRecExpr(const SCEV* Start,
1605 const SCEV* Step, const Loop *L) {
1606 SmallVector<const SCEV*, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001607 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001608 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001609 if (StepChrec->getLoop() == L) {
1610 Operands.insert(Operands.end(), StepChrec->op_begin(),
1611 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001612 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001613 }
1614
1615 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001616 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001617}
1618
Dan Gohmanc8a29272009-05-24 23:45:28 +00001619/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1620/// Simplify the expression as much as possible.
Dan Gohman9bc642f2009-06-24 04:48:43 +00001621const SCEV *
1622ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV*> &Operands,
1623 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001624 if (Operands.size() == 1) return Operands[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001625#ifndef NDEBUG
1626 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1627 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1628 getEffectiveSCEVType(Operands[0]->getType()) &&
1629 "SCEVAddRecExpr operand types don't match!");
1630#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001631
Dan Gohman7b560c42008-06-18 16:23:07 +00001632 if (Operands.back()->isZero()) {
1633 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001634 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001635 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001636
Dan Gohman42936882008-08-08 18:33:12 +00001637 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001638 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001639 const Loop* NestedLoop = NestedAR->getLoop();
1640 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001641 SmallVector<const SCEV*, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001642 NestedAR->op_end());
Dan Gohman42936882008-08-08 18:33:12 +00001643 Operands[0] = NestedAR->getStart();
1644 NestedOperands[0] = getAddRecExpr(Operands, L);
1645 return getAddRecExpr(NestedOperands, NestedLoop);
1646 }
1647 }
1648
Dan Gohmanbff6b582009-05-04 22:30:44 +00001649 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001650 SCEVAddRecExpr *&Result = SCEVAddRecExprs[std::make_pair(L, SCEVOps)];
Owen Andersonb70139d2009-06-22 21:57:23 +00001651 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001652 return Result;
1653}
1654
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001655const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
1656 const SCEV *RHS) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001657 SmallVector<const SCEV*, 2> Ops;
Nick Lewycky711640a2007-11-25 22:41:31 +00001658 Ops.push_back(LHS);
1659 Ops.push_back(RHS);
1660 return getSMaxExpr(Ops);
1661}
1662
Owen Andersonecd0cd72009-06-22 21:39:50 +00001663const SCEV*
1664ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV*> &Ops) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001665 assert(!Ops.empty() && "Cannot get empty smax!");
1666 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001667#ifndef NDEBUG
1668 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1669 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1670 getEffectiveSCEVType(Ops[0]->getType()) &&
1671 "SCEVSMaxExpr operand types don't match!");
1672#endif
Nick Lewycky711640a2007-11-25 22:41:31 +00001673
1674 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001675 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001676
1677 // If there are any constants, fold them together.
1678 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001679 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001680 ++Idx;
1681 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001682 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001683 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001684 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001685 APIntOps::smax(LHSC->getValue()->getValue(),
1686 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001687 Ops[0] = getConstant(Fold);
1688 Ops.erase(Ops.begin()+1); // Erase the folded element
1689 if (Ops.size() == 1) return Ops[0];
1690 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001691 }
1692
Dan Gohmand156c092009-06-24 14:46:22 +00001693 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky711640a2007-11-25 22:41:31 +00001694 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1695 Ops.erase(Ops.begin());
1696 --Idx;
Dan Gohmand156c092009-06-24 14:46:22 +00001697 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
1698 // If we have an smax with a constant maximum-int, it will always be
1699 // maximum-int.
1700 return Ops[0];
Nick Lewycky711640a2007-11-25 22:41:31 +00001701 }
1702 }
1703
1704 if (Ops.size() == 1) return Ops[0];
1705
1706 // Find the first SMax
1707 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1708 ++Idx;
1709
1710 // Check to see if one of the operands is an SMax. If so, expand its operands
1711 // onto our operand list, and recurse to simplify.
1712 if (Idx < Ops.size()) {
1713 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001714 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001715 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1716 Ops.erase(Ops.begin()+Idx);
1717 DeletedSMax = true;
1718 }
1719
1720 if (DeletedSMax)
1721 return getSMaxExpr(Ops);
1722 }
1723
1724 // Okay, check to see if the same value occurs in the operand list twice. If
1725 // so, delete one. Since we sorted the list, these values are required to
1726 // be adjacent.
1727 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1728 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1729 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1730 --i; --e;
1731 }
1732
1733 if (Ops.size() == 1) return Ops[0];
1734
1735 assert(!Ops.empty() && "Reduced smax down to nothing!");
1736
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001737 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001738 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001739 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001740 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scSMaxExpr,
Nick Lewycky711640a2007-11-25 22:41:31 +00001741 SCEVOps)];
Owen Andersonb70139d2009-06-22 21:57:23 +00001742 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
Nick Lewycky711640a2007-11-25 22:41:31 +00001743 return Result;
1744}
1745
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001746const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
1747 const SCEV *RHS) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001748 SmallVector<const SCEV*, 2> Ops;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001749 Ops.push_back(LHS);
1750 Ops.push_back(RHS);
1751 return getUMaxExpr(Ops);
1752}
1753
Owen Andersonecd0cd72009-06-22 21:39:50 +00001754const SCEV*
1755ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV*> &Ops) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001756 assert(!Ops.empty() && "Cannot get empty umax!");
1757 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001758#ifndef NDEBUG
1759 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1760 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1761 getEffectiveSCEVType(Ops[0]->getType()) &&
1762 "SCEVUMaxExpr operand types don't match!");
1763#endif
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001764
1765 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001766 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001767
1768 // If there are any constants, fold them together.
1769 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001770 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001771 ++Idx;
1772 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001773 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001774 // We found two constants, fold them together!
1775 ConstantInt *Fold = ConstantInt::get(
1776 APIntOps::umax(LHSC->getValue()->getValue(),
1777 RHSC->getValue()->getValue()));
1778 Ops[0] = getConstant(Fold);
1779 Ops.erase(Ops.begin()+1); // Erase the folded element
1780 if (Ops.size() == 1) return Ops[0];
1781 LHSC = cast<SCEVConstant>(Ops[0]);
1782 }
1783
Dan Gohmand156c092009-06-24 14:46:22 +00001784 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001785 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1786 Ops.erase(Ops.begin());
1787 --Idx;
Dan Gohmand156c092009-06-24 14:46:22 +00001788 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
1789 // If we have an umax with a constant maximum-int, it will always be
1790 // maximum-int.
1791 return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001792 }
1793 }
1794
1795 if (Ops.size() == 1) return Ops[0];
1796
1797 // Find the first UMax
1798 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1799 ++Idx;
1800
1801 // Check to see if one of the operands is a UMax. If so, expand its operands
1802 // onto our operand list, and recurse to simplify.
1803 if (Idx < Ops.size()) {
1804 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001805 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001806 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1807 Ops.erase(Ops.begin()+Idx);
1808 DeletedUMax = true;
1809 }
1810
1811 if (DeletedUMax)
1812 return getUMaxExpr(Ops);
1813 }
1814
1815 // Okay, check to see if the same value occurs in the operand list twice. If
1816 // so, delete one. Since we sorted the list, these values are required to
1817 // be adjacent.
1818 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1819 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1820 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1821 --i; --e;
1822 }
1823
1824 if (Ops.size() == 1) return Ops[0];
1825
1826 assert(!Ops.empty() && "Reduced umax down to nothing!");
1827
1828 // Okay, it looks like we really DO need a umax expr. Check to see if we
1829 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001830 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001831 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scUMaxExpr,
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001832 SCEVOps)];
Owen Andersonb70139d2009-06-22 21:57:23 +00001833 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001834 return Result;
1835}
1836
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001837const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
1838 const SCEV *RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00001839 // ~smax(~x, ~y) == smin(x, y).
1840 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1841}
1842
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001843const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
1844 const SCEV *RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00001845 // ~umax(~x, ~y) == umin(x, y)
1846 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1847}
1848
Owen Andersonecd0cd72009-06-22 21:39:50 +00001849const SCEV* ScalarEvolution::getUnknown(Value *V) {
Dan Gohman984c78a2009-06-24 00:54:57 +00001850 // Don't attempt to do anything other than create a SCEVUnknown object
1851 // here. createSCEV only calls getUnknown after checking for all other
1852 // interesting possibilities, and any other code that calls getUnknown
1853 // is doing so in order to hide a value from SCEV canonicalization.
1854
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001855 SCEVUnknown *&Result = SCEVUnknowns[V];
Owen Andersonb70139d2009-06-22 21:57:23 +00001856 if (Result == 0) Result = new SCEVUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001857 return Result;
1858}
1859
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001860//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001861// Basic SCEV Analysis and PHI Idiom Recognition Code
1862//
1863
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001864/// isSCEVable - Test if values of the given type are analyzable within
1865/// the SCEV framework. This primarily includes integer types, and it
1866/// can optionally include pointer types if the ScalarEvolution class
1867/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001868bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001869 // Integers are always SCEVable.
1870 if (Ty->isInteger())
1871 return true;
1872
1873 // Pointers are SCEVable if TargetData information is available
1874 // to provide pointer size information.
1875 if (isa<PointerType>(Ty))
1876 return TD != NULL;
1877
1878 // Otherwise it's not SCEVable.
1879 return false;
1880}
1881
1882/// getTypeSizeInBits - Return the size in bits of the specified type,
1883/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001884uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001885 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1886
1887 // If we have a TargetData, use it!
1888 if (TD)
1889 return TD->getTypeSizeInBits(Ty);
1890
1891 // Otherwise, we support only integer types.
1892 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1893 return Ty->getPrimitiveSizeInBits();
1894}
1895
1896/// getEffectiveSCEVType - Return a type with the same bitwidth as
1897/// the given type and which represents how SCEV will treat the given
1898/// type, for which isSCEVable must return true. For pointer types,
1899/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001900const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001901 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1902
1903 if (Ty->isInteger())
1904 return Ty;
1905
1906 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1907 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001908}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001909
Owen Andersonecd0cd72009-06-22 21:39:50 +00001910const SCEV* ScalarEvolution::getCouldNotCompute() {
Dan Gohman0c850912009-06-06 14:37:11 +00001911 return CouldNotCompute;
Dan Gohman0ad08b02009-04-18 17:58:19 +00001912}
1913
Dan Gohmand83d4af2009-05-04 22:20:30 +00001914/// hasSCEV - Return true if the SCEV for this value has already been
Edwin Török0e828d62009-05-01 08:33:47 +00001915/// computed.
1916bool ScalarEvolution::hasSCEV(Value *V) const {
1917 return Scalars.count(V);
1918}
1919
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001920/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1921/// expression and create a new one.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001922const SCEV* ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001923 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001924
Owen Andersonecd0cd72009-06-22 21:39:50 +00001925 std::map<SCEVCallbackVH, const SCEV*>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001926 if (I != Scalars.end()) return I->second;
Owen Andersonecd0cd72009-06-22 21:39:50 +00001927 const SCEV* S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00001928 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001929 return S;
1930}
1931
Dan Gohman984c78a2009-06-24 00:54:57 +00001932/// getIntegerSCEV - Given a SCEVable type, create a constant for the
Dan Gohman01c2ee72009-04-16 03:18:22 +00001933/// specified signed integer value and return a SCEV for the constant.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001934const SCEV* ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohman984c78a2009-06-24 00:54:57 +00001935 const IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
1936 return getConstant(ConstantInt::get(ITy, Val));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001937}
1938
1939/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1940///
Owen Andersonecd0cd72009-06-22 21:39:50 +00001941const SCEV* ScalarEvolution::getNegativeSCEV(const SCEV* V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001942 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman55788cf2009-06-24 00:38:39 +00001943 return getConstant(cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001944
1945 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001946 Ty = getEffectiveSCEVType(Ty);
1947 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001948}
1949
1950/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Owen Andersonecd0cd72009-06-22 21:39:50 +00001951const SCEV* ScalarEvolution::getNotSCEV(const SCEV* V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001952 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman55788cf2009-06-24 00:38:39 +00001953 return getConstant(cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001954
1955 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001956 Ty = getEffectiveSCEVType(Ty);
Owen Andersonecd0cd72009-06-22 21:39:50 +00001957 const SCEV* AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001958 return getMinusSCEV(AllOnes, V);
1959}
1960
1961/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1962///
Dan Gohman8c4f20b2009-06-24 14:49:00 +00001963const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS,
1964 const SCEV *RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001965 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001966 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001967}
1968
1969/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1970/// input value to the specified type. If the type must be extended, it is zero
1971/// extended.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001972const SCEV*
1973ScalarEvolution::getTruncateOrZeroExtend(const SCEV* V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001974 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001975 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001976 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1977 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001978 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001979 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001980 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001981 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001982 return getTruncateExpr(V, Ty);
1983 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001984}
1985
1986/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1987/// input value to the specified type. If the type must be extended, it is sign
1988/// extended.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001989const SCEV*
1990ScalarEvolution::getTruncateOrSignExtend(const SCEV* V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001991 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001992 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001993 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1994 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001995 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001996 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001997 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001998 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001999 return getTruncateExpr(V, Ty);
2000 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002001}
2002
Dan Gohmanac959332009-05-13 03:46:30 +00002003/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2004/// input value to the specified type. If the type must be extended, it is zero
2005/// extended. The conversion must not be narrowing.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002006const SCEV*
2007ScalarEvolution::getNoopOrZeroExtend(const SCEV* V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002008 const Type *SrcTy = V->getType();
2009 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2010 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2011 "Cannot noop or zero extend with non-integer arguments!");
2012 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2013 "getNoopOrZeroExtend cannot truncate!");
2014 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2015 return V; // No conversion
2016 return getZeroExtendExpr(V, Ty);
2017}
2018
2019/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2020/// input value to the specified type. If the type must be extended, it is sign
2021/// extended. The conversion must not be narrowing.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002022const SCEV*
2023ScalarEvolution::getNoopOrSignExtend(const SCEV* V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002024 const Type *SrcTy = V->getType();
2025 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2026 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2027 "Cannot noop or sign extend with non-integer arguments!");
2028 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2029 "getNoopOrSignExtend cannot truncate!");
2030 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2031 return V; // No conversion
2032 return getSignExtendExpr(V, Ty);
2033}
2034
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002035/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2036/// the input value to the specified type. If the type must be extended,
2037/// it is extended with unspecified bits. The conversion must not be
2038/// narrowing.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002039const SCEV*
2040ScalarEvolution::getNoopOrAnyExtend(const SCEV* V, const Type *Ty) {
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002041 const Type *SrcTy = V->getType();
2042 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2043 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2044 "Cannot noop or any extend with non-integer arguments!");
2045 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2046 "getNoopOrAnyExtend cannot truncate!");
2047 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2048 return V; // No conversion
2049 return getAnyExtendExpr(V, Ty);
2050}
2051
Dan Gohmanac959332009-05-13 03:46:30 +00002052/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2053/// input value to the specified type. The conversion must not be widening.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002054const SCEV*
2055ScalarEvolution::getTruncateOrNoop(const SCEV* V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002056 const Type *SrcTy = V->getType();
2057 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2058 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2059 "Cannot truncate or noop with non-integer arguments!");
2060 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2061 "getTruncateOrNoop cannot extend!");
2062 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2063 return V; // No conversion
2064 return getTruncateExpr(V, Ty);
2065}
2066
Dan Gohman8e8b5232009-06-22 00:31:57 +00002067/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2068/// the types using zero-extension, and then perform a umax operation
2069/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002070const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
2071 const SCEV *RHS) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002072 const SCEV* PromotedLHS = LHS;
2073 const SCEV* PromotedRHS = RHS;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002074
2075 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2076 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2077 else
2078 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2079
2080 return getUMaxExpr(PromotedLHS, PromotedRHS);
2081}
2082
Dan Gohman9e62bb02009-06-22 15:03:27 +00002083/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2084/// the types using zero-extension, and then perform a umin operation
2085/// with them.
Dan Gohman8c4f20b2009-06-24 14:49:00 +00002086const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
2087 const SCEV *RHS) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002088 const SCEV* PromotedLHS = LHS;
2089 const SCEV* PromotedRHS = RHS;
Dan Gohman9e62bb02009-06-22 15:03:27 +00002090
2091 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2092 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2093 else
2094 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2095
2096 return getUMinExpr(PromotedLHS, PromotedRHS);
2097}
2098
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002099/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2100/// the specified instruction and replaces any references to the symbolic value
2101/// SymName with the specified value. This is used during PHI resolution.
Dan Gohman9bc642f2009-06-24 04:48:43 +00002102void
2103ScalarEvolution::ReplaceSymbolicValueWithConcrete(Instruction *I,
2104 const SCEV *SymName,
2105 const SCEV *NewVal) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002106 std::map<SCEVCallbackVH, const SCEV*>::iterator SI =
Dan Gohmanbff6b582009-05-04 22:30:44 +00002107 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002108 if (SI == Scalars.end()) return;
2109
Owen Andersonecd0cd72009-06-22 21:39:50 +00002110 const SCEV* NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002111 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002112 if (NV == SI->second) return; // No change.
2113
2114 SI->second = NV; // Update the scalars map!
2115
2116 // Any instruction values that use this instruction might also need to be
2117 // updated!
2118 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2119 UI != E; ++UI)
2120 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2121}
2122
2123/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2124/// a loop header, making it a potential recurrence, or it doesn't.
2125///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002126const SCEV* ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002127 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002128 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002129 if (L->getHeader() == PN->getParent()) {
2130 // If it lives in the loop header, it has two incoming values, one
2131 // from outside the loop, and one from inside.
2132 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2133 unsigned BackEdge = IncomingEdge^1;
2134
2135 // While we are analyzing this PHI node, handle its value symbolically.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002136 const SCEV* SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002137 assert(Scalars.find(PN) == Scalars.end() &&
2138 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002139 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002140
2141 // Using this symbolic name for the PHI, analyze the value coming around
2142 // the back-edge.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002143 const SCEV* BEValue = getSCEV(PN->getIncomingValue(BackEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002144
2145 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2146 // has a special value for the first iteration of the loop.
2147
2148 // If the value coming around the backedge is an add with the symbolic
2149 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00002150 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002151 // If there is a single occurrence of the symbolic value, replace it
2152 // with a recurrence.
2153 unsigned FoundIndex = Add->getNumOperands();
2154 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2155 if (Add->getOperand(i) == SymbolicName)
2156 if (FoundIndex == e) {
2157 FoundIndex = i;
2158 break;
2159 }
2160
2161 if (FoundIndex != Add->getNumOperands()) {
2162 // Create an add with everything but the specified operand.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002163 SmallVector<const SCEV*, 8> Ops;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002164 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2165 if (i != FoundIndex)
2166 Ops.push_back(Add->getOperand(i));
Owen Andersonecd0cd72009-06-22 21:39:50 +00002167 const SCEV* Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002168
2169 // This is not a valid addrec if the step amount is varying each
2170 // loop iteration, but is not itself an addrec in this loop.
2171 if (Accum->isLoopInvariant(L) ||
2172 (isa<SCEVAddRecExpr>(Accum) &&
2173 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002174 const SCEV *StartVal =
2175 getSCEV(PN->getIncomingValue(IncomingEdge));
2176 const SCEV *PHISCEV =
2177 getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002178
2179 // Okay, for the entire analysis of this edge we assumed the PHI
2180 // to be symbolic. We now need to go back and update all of the
2181 // entries for the scalars that use the PHI (except for the PHI
2182 // itself) to use the new analyzed value instead of the "symbolic"
2183 // value.
2184 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2185 return PHISCEV;
2186 }
2187 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00002188 } else if (const SCEVAddRecExpr *AddRec =
2189 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002190 // Otherwise, this could be a loop like this:
2191 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2192 // In this case, j = {1,+,1} and BEValue is j.
2193 // Because the other in-value of i (0) fits the evolution of BEValue
2194 // i really is an addrec evolution.
2195 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002196 const SCEV* StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002197
2198 // If StartVal = j.start - j.stride, we can use StartVal as the
2199 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002200 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00002201 AddRec->getOperand(1))) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002202 const SCEV* PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002203 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002204
2205 // Okay, for the entire analysis of this edge we assumed the PHI
2206 // to be symbolic. We now need to go back and update all of the
2207 // entries for the scalars that use the PHI (except for the PHI
2208 // itself) to use the new analyzed value instead of the "symbolic"
2209 // value.
2210 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2211 return PHISCEV;
2212 }
2213 }
2214 }
2215
2216 return SymbolicName;
2217 }
2218
2219 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002220 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002221}
2222
Dan Gohman509cf4d2009-05-08 20:26:55 +00002223/// createNodeForGEP - Expand GEP instructions into add and multiply
2224/// operations. This allows them to be analyzed by regular SCEV code.
2225///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002226const SCEV* ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman509cf4d2009-05-08 20:26:55 +00002227
2228 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002229 Value *Base = GEP->getOperand(0);
Dan Gohmand586a4f2009-05-09 00:14:52 +00002230 // Don't attempt to analyze GEPs over unsized objects.
2231 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2232 return getUnknown(GEP);
Owen Andersonecd0cd72009-06-22 21:39:50 +00002233 const SCEV* TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002234 gep_type_iterator GTI = gep_type_begin(GEP);
2235 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2236 E = GEP->op_end();
Dan Gohman509cf4d2009-05-08 20:26:55 +00002237 I != E; ++I) {
2238 Value *Index = *I;
2239 // Compute the (potentially symbolic) offset in bytes for this index.
2240 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2241 // For a struct, add the member offset.
2242 const StructLayout &SL = *TD->getStructLayout(STy);
2243 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2244 uint64_t Offset = SL.getElementOffset(FieldNo);
2245 TotalOffset = getAddExpr(TotalOffset,
2246 getIntegerSCEV(Offset, IntPtrTy));
2247 } else {
2248 // For an array, add the element offset, explicitly scaled.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002249 const SCEV* LocalOffset = getSCEV(Index);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002250 if (!isa<PointerType>(LocalOffset->getType()))
2251 // Getelementptr indicies are signed.
2252 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2253 IntPtrTy);
2254 LocalOffset =
2255 getMulExpr(LocalOffset,
Duncan Sandsec4f97d2009-05-09 07:06:46 +00002256 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman509cf4d2009-05-08 20:26:55 +00002257 IntPtrTy));
2258 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2259 }
2260 }
2261 return getAddExpr(getSCEV(Base), TotalOffset);
2262}
2263
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002264/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2265/// guaranteed to end in (at every loop iteration). It is, at the same time,
2266/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2267/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman6e923a72009-06-19 23:29:04 +00002268uint32_t
Owen Andersonecd0cd72009-06-22 21:39:50 +00002269ScalarEvolution::GetMinTrailingZeros(const SCEV* S) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002270 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00002271 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002272
Dan Gohmanc76b5452009-05-04 22:02:23 +00002273 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman6e923a72009-06-19 23:29:04 +00002274 return std::min(GetMinTrailingZeros(T->getOperand()),
2275 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002276
Dan Gohmanc76b5452009-05-04 22:02:23 +00002277 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002278 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2279 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2280 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002281 }
2282
Dan Gohmanc76b5452009-05-04 22:02:23 +00002283 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002284 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2285 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2286 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002287 }
2288
Dan Gohmanc76b5452009-05-04 22:02:23 +00002289 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002290 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002291 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002292 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002293 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002294 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002295 }
2296
Dan Gohmanc76b5452009-05-04 22:02:23 +00002297 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002298 // The result is the sum of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002299 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2300 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002301 for (unsigned i = 1, e = M->getNumOperands();
2302 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002303 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002304 BitWidth);
2305 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002306 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002307
Dan Gohmanc76b5452009-05-04 22:02:23 +00002308 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002309 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002310 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002311 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002312 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002313 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002314 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002315
Dan Gohmanc76b5452009-05-04 22:02:23 +00002316 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00002317 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002318 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky711640a2007-11-25 22:41:31 +00002319 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002320 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky711640a2007-11-25 22:41:31 +00002321 return MinOpRes;
2322 }
2323
Dan Gohmanc76b5452009-05-04 22:02:23 +00002324 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002325 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002326 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002327 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002328 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002329 return MinOpRes;
2330 }
2331
Dan Gohman6e923a72009-06-19 23:29:04 +00002332 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2333 // For a SCEVUnknown, ask ValueTracking.
2334 unsigned BitWidth = getTypeSizeInBits(U->getType());
2335 APInt Mask = APInt::getAllOnesValue(BitWidth);
2336 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2337 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2338 return Zeros.countTrailingOnes();
2339 }
2340
2341 // SCEVUDivExpr
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002342 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002343}
2344
Dan Gohman6e923a72009-06-19 23:29:04 +00002345uint32_t
Owen Andersonecd0cd72009-06-22 21:39:50 +00002346ScalarEvolution::GetMinLeadingZeros(const SCEV* S) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002347 // TODO: Handle other SCEV expression types here.
2348
2349 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2350 return C->getValue()->getValue().countLeadingZeros();
2351
2352 if (const SCEVZeroExtendExpr *C = dyn_cast<SCEVZeroExtendExpr>(S)) {
2353 // A zero-extension cast adds zero bits.
2354 return GetMinLeadingZeros(C->getOperand()) +
2355 (getTypeSizeInBits(C->getType()) -
2356 getTypeSizeInBits(C->getOperand()->getType()));
2357 }
2358
2359 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2360 // For a SCEVUnknown, ask ValueTracking.
2361 unsigned BitWidth = getTypeSizeInBits(U->getType());
2362 APInt Mask = APInt::getAllOnesValue(BitWidth);
2363 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2364 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2365 return Zeros.countLeadingOnes();
2366 }
2367
2368 return 1;
2369}
2370
2371uint32_t
Owen Andersonecd0cd72009-06-22 21:39:50 +00002372ScalarEvolution::GetMinSignBits(const SCEV* S) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002373 // TODO: Handle other SCEV expression types here.
2374
2375 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
2376 const APInt &A = C->getValue()->getValue();
2377 return A.isNegative() ? A.countLeadingOnes() :
2378 A.countLeadingZeros();
2379 }
2380
2381 if (const SCEVSignExtendExpr *C = dyn_cast<SCEVSignExtendExpr>(S)) {
2382 // A sign-extension cast adds sign bits.
2383 return GetMinSignBits(C->getOperand()) +
2384 (getTypeSizeInBits(C->getType()) -
2385 getTypeSizeInBits(C->getOperand()->getType()));
2386 }
2387
Dan Gohman61e0c4c2009-06-24 01:05:09 +00002388 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
2389 unsigned BitWidth = getTypeSizeInBits(A->getType());
2390
2391 // Special case decrementing a value (ADD X, -1):
2392 if (const SCEVConstant *CRHS = dyn_cast<SCEVConstant>(A->getOperand(0)))
2393 if (CRHS->isAllOnesValue()) {
2394 SmallVector<const SCEV *, 4> OtherOps(A->op_begin() + 1, A->op_end());
2395 const SCEV *OtherOpsAdd = getAddExpr(OtherOps);
2396 unsigned LZ = GetMinLeadingZeros(OtherOpsAdd);
2397
2398 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2399 // sign bits set.
2400 if (LZ == BitWidth - 1)
2401 return BitWidth;
2402
2403 // If we are subtracting one from a positive number, there is no carry
2404 // out of the result.
2405 if (LZ > 0)
2406 return GetMinSignBits(OtherOpsAdd);
2407 }
2408
2409 // Add can have at most one carry bit. Thus we know that the output
2410 // is, at worst, one more bit than the inputs.
2411 unsigned Min = BitWidth;
2412 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2413 unsigned N = GetMinSignBits(A->getOperand(i));
2414 Min = std::min(Min, N) - 1;
2415 if (Min == 0) return 1;
2416 }
2417 return 1;
2418 }
2419
Dan Gohman6e923a72009-06-19 23:29:04 +00002420 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2421 // For a SCEVUnknown, ask ValueTracking.
2422 return ComputeNumSignBits(U->getValue(), TD);
2423 }
2424
2425 return 1;
2426}
2427
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002428/// createSCEV - We know that there is no SCEV for the specified value.
2429/// Analyze the expression.
2430///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002431const SCEV* ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002432 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002433 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002434
Dan Gohman3996f472008-06-22 19:56:46 +00002435 unsigned Opcode = Instruction::UserOp1;
2436 if (Instruction *I = dyn_cast<Instruction>(V))
2437 Opcode = I->getOpcode();
2438 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2439 Opcode = CE->getOpcode();
Dan Gohman984c78a2009-06-24 00:54:57 +00002440 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2441 return getConstant(CI);
2442 else if (isa<ConstantPointerNull>(V))
2443 return getIntegerSCEV(0, V->getType());
2444 else if (isa<UndefValue>(V))
2445 return getIntegerSCEV(0, V->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002446 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002447 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002448
Dan Gohman3996f472008-06-22 19:56:46 +00002449 User *U = cast<User>(V);
2450 switch (Opcode) {
2451 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002452 return getAddExpr(getSCEV(U->getOperand(0)),
2453 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002454 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002455 return getMulExpr(getSCEV(U->getOperand(0)),
2456 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002457 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002458 return getUDivExpr(getSCEV(U->getOperand(0)),
2459 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002460 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002461 return getMinusSCEV(getSCEV(U->getOperand(0)),
2462 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002463 case Instruction::And:
2464 // For an expression like x&255 that merely masks off the high bits,
2465 // use zext(trunc(x)) as the SCEV expression.
2466 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002467 if (CI->isNullValue())
2468 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00002469 if (CI->isAllOnesValue())
2470 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002471 const APInt &A = CI->getValue();
Dan Gohmana7726c32009-06-16 19:52:01 +00002472
2473 // Instcombine's ShrinkDemandedConstant may strip bits out of
2474 // constants, obscuring what would otherwise be a low-bits mask.
2475 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2476 // knew about to reconstruct a low-bits mask value.
2477 unsigned LZ = A.countLeadingZeros();
2478 unsigned BitWidth = A.getBitWidth();
2479 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2480 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2481 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2482
2483 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2484
Dan Gohmanae1d7dd2009-06-17 23:54:37 +00002485 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman53bf64a2009-04-21 02:26:00 +00002486 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002487 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohmana7726c32009-06-16 19:52:01 +00002488 IntegerType::get(BitWidth - LZ)),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002489 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00002490 }
2491 break;
Dan Gohmana7726c32009-06-16 19:52:01 +00002492
Dan Gohman3996f472008-06-22 19:56:46 +00002493 case Instruction::Or:
2494 // If the RHS of the Or is a constant, we may have something like:
2495 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2496 // optimizations will transparently handle this case.
2497 //
2498 // In order for this transformation to be safe, the LHS must be of the
2499 // form X*(2^n) and the Or constant must be less than 2^n.
2500 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002501 const SCEV* LHS = getSCEV(U->getOperand(0));
Dan Gohman3996f472008-06-22 19:56:46 +00002502 const APInt &CIVal = CI->getValue();
Dan Gohman6e923a72009-06-19 23:29:04 +00002503 if (GetMinTrailingZeros(LHS) >=
Dan Gohman3996f472008-06-22 19:56:46 +00002504 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002505 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002506 }
Dan Gohman3996f472008-06-22 19:56:46 +00002507 break;
2508 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00002509 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00002510 // If the RHS of the xor is a signbit, then this is just an add.
2511 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00002512 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002513 return getAddExpr(getSCEV(U->getOperand(0)),
2514 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002515
2516 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmanc897f752009-05-18 16:17:44 +00002517 if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002518 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohmanfc78cff2009-05-18 16:29:04 +00002519
2520 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2521 // This is a variant of the check for xor with -1, and it handles
2522 // the case where instcombine has trimmed non-demanded bits out
2523 // of an xor with -1.
2524 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2525 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2526 if (BO->getOpcode() == Instruction::And &&
2527 LCI->getValue() == CI->getValue())
2528 if (const SCEVZeroExtendExpr *Z =
Dan Gohmane49ae432009-06-17 01:22:39 +00002529 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002530 const Type *UTy = U->getType();
Owen Andersonecd0cd72009-06-22 21:39:50 +00002531 const SCEV* Z0 = Z->getOperand();
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002532 const Type *Z0Ty = Z0->getType();
2533 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2534
2535 // If C is a low-bits mask, the zero extend is zerving to
2536 // mask off the high bits. Complement the operand and
2537 // re-apply the zext.
2538 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2539 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2540
2541 // If C is a single bit, it may be in the sign-bit position
2542 // before the zero-extend. In this case, represent the xor
2543 // using an add, which is equivalent, and re-apply the zext.
2544 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2545 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2546 Trunc.isSignBit())
2547 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2548 UTy);
Dan Gohmane49ae432009-06-17 01:22:39 +00002549 }
Dan Gohman3996f472008-06-22 19:56:46 +00002550 }
2551 break;
2552
2553 case Instruction::Shl:
2554 // Turn shift left of a constant amount into a multiply.
2555 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2556 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2557 Constant *X = ConstantInt::get(
2558 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002559 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00002560 }
2561 break;
2562
Nick Lewycky7fd27892008-07-07 06:15:49 +00002563 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00002564 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00002565 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2566 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2567 Constant *X = ConstantInt::get(
2568 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002569 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002570 }
2571 break;
2572
Dan Gohman53bf64a2009-04-21 02:26:00 +00002573 case Instruction::AShr:
2574 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2575 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2576 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2577 if (L->getOpcode() == Instruction::Shl &&
2578 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002579 unsigned BitWidth = getTypeSizeInBits(U->getType());
2580 uint64_t Amt = BitWidth - CI->getZExtValue();
2581 if (Amt == BitWidth)
2582 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2583 if (Amt > BitWidth)
2584 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00002585 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002586 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00002587 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00002588 U->getType());
2589 }
2590 break;
2591
Dan Gohman3996f472008-06-22 19:56:46 +00002592 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002593 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002594
2595 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002596 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002597
2598 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002599 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002600
2601 case Instruction::BitCast:
2602 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002603 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002604 return getSCEV(U->getOperand(0));
2605 break;
2606
Dan Gohman01c2ee72009-04-16 03:18:22 +00002607 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002608 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002609 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002610 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002611
2612 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002613 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002614 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2615 U->getType());
2616
Dan Gohman509cf4d2009-05-08 20:26:55 +00002617 case Instruction::GetElementPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002618 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002619 return createNodeForGEP(U);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002620
Dan Gohman3996f472008-06-22 19:56:46 +00002621 case Instruction::PHI:
2622 return createNodeForPHI(cast<PHINode>(U));
2623
2624 case Instruction::Select:
2625 // This could be a smax or umax that was lowered earlier.
2626 // Try to recover it.
2627 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2628 Value *LHS = ICI->getOperand(0);
2629 Value *RHS = ICI->getOperand(1);
2630 switch (ICI->getPredicate()) {
2631 case ICmpInst::ICMP_SLT:
2632 case ICmpInst::ICMP_SLE:
2633 std::swap(LHS, RHS);
2634 // fall through
2635 case ICmpInst::ICMP_SGT:
2636 case ICmpInst::ICMP_SGE:
2637 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002638 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002639 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002640 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002641 break;
2642 case ICmpInst::ICMP_ULT:
2643 case ICmpInst::ICMP_ULE:
2644 std::swap(LHS, RHS);
2645 // fall through
2646 case ICmpInst::ICMP_UGT:
2647 case ICmpInst::ICMP_UGE:
2648 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002649 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002650 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002651 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002652 break;
Dan Gohmanf27dc692009-06-18 20:21:07 +00002653 case ICmpInst::ICMP_NE:
2654 // n != 0 ? n : 1 -> umax(n, 1)
2655 if (LHS == U->getOperand(1) &&
2656 isa<ConstantInt>(U->getOperand(2)) &&
2657 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2658 isa<ConstantInt>(RHS) &&
2659 cast<ConstantInt>(RHS)->isZero())
2660 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2661 break;
2662 case ICmpInst::ICMP_EQ:
2663 // n == 0 ? 1 : n -> umax(n, 1)
2664 if (LHS == U->getOperand(2) &&
2665 isa<ConstantInt>(U->getOperand(1)) &&
2666 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2667 isa<ConstantInt>(RHS) &&
2668 cast<ConstantInt>(RHS)->isZero())
2669 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2670 break;
Dan Gohman3996f472008-06-22 19:56:46 +00002671 default:
2672 break;
2673 }
2674 }
2675
2676 default: // We cannot analyze this expression.
2677 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002678 }
2679
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002680 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002681}
2682
2683
2684
2685//===----------------------------------------------------------------------===//
2686// Iteration Count Computation Code
2687//
2688
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002689/// getBackedgeTakenCount - If the specified loop has a predictable
2690/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2691/// object. The backedge-taken count is the number of times the loop header
2692/// will be branched to from within the loop. This is one less than the
2693/// trip count of the loop, since it doesn't count the first iteration,
2694/// when the header is branched to from outside the loop.
2695///
2696/// Note that it is not valid to call this method on a loop without a
2697/// loop-invariant backedge-taken count (see
2698/// hasLoopInvariantBackedgeTakenCount).
2699///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002700const SCEV* ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002701 return getBackedgeTakenInfo(L).Exact;
2702}
2703
2704/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2705/// return the least SCEV value that is known never to be less than the
2706/// actual backedge taken count.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002707const SCEV* ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002708 return getBackedgeTakenInfo(L).Max;
2709}
2710
2711const ScalarEvolution::BackedgeTakenInfo &
2712ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002713 // Initially insert a CouldNotCompute for this loop. If the insertion
2714 // succeeds, procede to actually compute a backedge-taken count and
2715 // update the value. The temporary CouldNotCompute value tells SCEV
2716 // code elsewhere that it shouldn't attempt to request a new
2717 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002718 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002719 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2720 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002721 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman0c850912009-06-06 14:37:11 +00002722 if (ItCount.Exact != CouldNotCompute) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002723 assert(ItCount.Exact->isLoopInvariant(L) &&
2724 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002725 "Computed trip count isn't loop invariant for loop!");
2726 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002727
Dan Gohmana9dba962009-04-27 20:16:15 +00002728 // Update the value in the map.
2729 Pair.first->second = ItCount;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002730 } else {
2731 if (ItCount.Max != CouldNotCompute)
2732 // Update the value in the map.
2733 Pair.first->second = ItCount;
2734 if (isa<PHINode>(L->getHeader()->begin()))
2735 // Only count loops that have phi nodes as not being computable.
2736 ++NumTripCountsNotComputed;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002737 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002738
2739 // Now that we know more about the trip count for this loop, forget any
2740 // existing SCEV values for PHI nodes in this loop since they are only
2741 // conservative estimates made without the benefit
2742 // of trip count information.
2743 if (ItCount.hasAnyInfo())
Dan Gohman94623022009-05-02 17:43:35 +00002744 forgetLoopPHIs(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002745 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002746 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002747}
2748
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002749/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002750/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002751/// ScalarEvolution's ability to compute a trip count, or if the loop
2752/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002753void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002754 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002755 forgetLoopPHIs(L);
2756}
2757
2758/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2759/// PHI nodes in the given loop. This is used when the trip count of
2760/// the loop may have changed.
2761void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002762 BasicBlock *Header = L->getHeader();
2763
Dan Gohman9fd4a002009-05-12 01:27:58 +00002764 // Push all Loop-header PHIs onto the Worklist stack, except those
2765 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2766 // a PHI either means that it has an unrecognized structure, or it's
2767 // a PHI that's in the progress of being computed by createNodeForPHI.
2768 // In the former case, additional loop trip count information isn't
2769 // going to change anything. In the later case, createNodeForPHI will
2770 // perform the necessary updates on its own when it gets to that point.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002771 SmallVector<Instruction *, 16> Worklist;
2772 for (BasicBlock::iterator I = Header->begin();
Dan Gohman9fd4a002009-05-12 01:27:58 +00002773 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Dan Gohman9bc642f2009-06-24 04:48:43 +00002774 std::map<SCEVCallbackVH, const SCEV*>::iterator It =
2775 Scalars.find((Value*)I);
Dan Gohman9fd4a002009-05-12 01:27:58 +00002776 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2777 Worklist.push_back(PN);
2778 }
Dan Gohmanbff6b582009-05-04 22:30:44 +00002779
2780 while (!Worklist.empty()) {
2781 Instruction *I = Worklist.pop_back_val();
2782 if (Scalars.erase(I))
2783 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2784 UI != UE; ++UI)
2785 Worklist.push_back(cast<Instruction>(UI));
2786 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002787}
2788
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002789/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2790/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002791ScalarEvolution::BackedgeTakenInfo
2792ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman8e8b5232009-06-22 00:31:57 +00002793 SmallVector<BasicBlock*, 8> ExitingBlocks;
2794 L->getExitingBlocks(ExitingBlocks);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002795
Dan Gohman8e8b5232009-06-22 00:31:57 +00002796 // Examine all exits and pick the most conservative values.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002797 const SCEV* BECount = CouldNotCompute;
2798 const SCEV* MaxBECount = CouldNotCompute;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002799 bool CouldNotComputeBECount = false;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002800 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
2801 BackedgeTakenInfo NewBTI =
2802 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002803
Dan Gohman8e8b5232009-06-22 00:31:57 +00002804 if (NewBTI.Exact == CouldNotCompute) {
2805 // We couldn't compute an exact value for this exit, so
Dan Gohmanc6e8c832009-06-22 21:10:22 +00002806 // we won't be able to compute an exact value for the loop.
Dan Gohman8e8b5232009-06-22 00:31:57 +00002807 CouldNotComputeBECount = true;
2808 BECount = CouldNotCompute;
2809 } else if (!CouldNotComputeBECount) {
2810 if (BECount == CouldNotCompute)
2811 BECount = NewBTI.Exact;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002812 else
Dan Gohman423ed6c2009-06-24 01:18:18 +00002813 BECount = getUMinFromMismatchedTypes(BECount, NewBTI.Exact);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002814 }
Dan Gohman423ed6c2009-06-24 01:18:18 +00002815 if (MaxBECount == CouldNotCompute)
2816 MaxBECount = NewBTI.Max;
2817 else if (NewBTI.Max != CouldNotCompute)
2818 MaxBECount = getUMinFromMismatchedTypes(MaxBECount, NewBTI.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002819 }
2820
2821 return BackedgeTakenInfo(BECount, MaxBECount);
2822}
2823
2824/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
2825/// of the specified loop will execute if it exits via the specified block.
2826ScalarEvolution::BackedgeTakenInfo
2827ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
2828 BasicBlock *ExitingBlock) {
2829
2830 // Okay, we've chosen an exiting block. See what condition causes us to
2831 // exit at this block.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002832 //
2833 // FIXME: we should be able to handle switch instructions (with a single exit)
2834 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman0c850912009-06-06 14:37:11 +00002835 if (ExitBr == 0) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002836 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Dan Gohman9bc642f2009-06-24 04:48:43 +00002837
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002838 // At this point, we know we have a conditional branch that determines whether
2839 // the loop is exited. However, we don't know if the branch is executed each
2840 // time through the loop. If not, then the execution count of the branch will
2841 // not be equal to the trip count of the loop.
2842 //
2843 // Currently we check for this by checking to see if the Exit branch goes to
2844 // the loop header. If so, we know it will always execute the same number of
2845 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman8e8b5232009-06-22 00:31:57 +00002846 // loop header. This is common for un-rotated loops.
2847 //
2848 // If both of those tests fail, walk up the unique predecessor chain to the
2849 // header, stopping if there is an edge that doesn't exit the loop. If the
2850 // header is reached, the execution count of the branch will be equal to the
2851 // trip count of the loop.
2852 //
2853 // More extensive analysis could be done to handle more cases here.
2854 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002855 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2856 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohman8e8b5232009-06-22 00:31:57 +00002857 ExitBr->getParent() != L->getHeader()) {
2858 // The simple checks failed, try climbing the unique predecessor chain
2859 // up to the header.
2860 bool Ok = false;
2861 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
2862 BasicBlock *Pred = BB->getUniquePredecessor();
2863 if (!Pred)
2864 return CouldNotCompute;
2865 TerminatorInst *PredTerm = Pred->getTerminator();
2866 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
2867 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
2868 if (PredSucc == BB)
2869 continue;
2870 // If the predecessor has a successor that isn't BB and isn't
2871 // outside the loop, assume the worst.
2872 if (L->contains(PredSucc))
2873 return CouldNotCompute;
2874 }
2875 if (Pred == L->getHeader()) {
2876 Ok = true;
2877 break;
2878 }
2879 BB = Pred;
2880 }
2881 if (!Ok)
2882 return CouldNotCompute;
2883 }
2884
2885 // Procede to the next level to examine the exit condition expression.
2886 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
2887 ExitBr->getSuccessor(0),
2888 ExitBr->getSuccessor(1));
2889}
2890
2891/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
2892/// backedge of the specified loop will execute if its exit condition
2893/// were a conditional branch of ExitCond, TBB, and FBB.
2894ScalarEvolution::BackedgeTakenInfo
2895ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
2896 Value *ExitCond,
2897 BasicBlock *TBB,
2898 BasicBlock *FBB) {
Dan Gohman423ed6c2009-06-24 01:18:18 +00002899 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman8e8b5232009-06-22 00:31:57 +00002900 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
2901 if (BO->getOpcode() == Instruction::And) {
2902 // Recurse on the operands of the and.
2903 BackedgeTakenInfo BTI0 =
2904 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
2905 BackedgeTakenInfo BTI1 =
2906 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Owen Andersonecd0cd72009-06-22 21:39:50 +00002907 const SCEV* BECount = CouldNotCompute;
2908 const SCEV* MaxBECount = CouldNotCompute;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002909 if (L->contains(TBB)) {
2910 // Both conditions must be true for the loop to continue executing.
2911 // Choose the less conservative count.
Dan Gohman2cc450e2009-06-22 23:28:56 +00002912 if (BTI0.Exact == CouldNotCompute || BTI1.Exact == CouldNotCompute)
2913 BECount = CouldNotCompute;
Dan Gohmanac958b32009-06-22 15:09:28 +00002914 else
2915 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002916 if (BTI0.Max == CouldNotCompute)
2917 MaxBECount = BTI1.Max;
2918 else if (BTI1.Max == CouldNotCompute)
2919 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00002920 else
2921 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002922 } else {
2923 // Both conditions must be true for the loop to exit.
2924 assert(L->contains(FBB) && "Loop block has no successor in loop!");
2925 if (BTI0.Exact != CouldNotCompute && BTI1.Exact != CouldNotCompute)
2926 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
2927 if (BTI0.Max != CouldNotCompute && BTI1.Max != CouldNotCompute)
2928 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
2929 }
2930
2931 return BackedgeTakenInfo(BECount, MaxBECount);
2932 }
2933 if (BO->getOpcode() == Instruction::Or) {
2934 // Recurse on the operands of the or.
2935 BackedgeTakenInfo BTI0 =
2936 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
2937 BackedgeTakenInfo BTI1 =
2938 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Owen Andersonecd0cd72009-06-22 21:39:50 +00002939 const SCEV* BECount = CouldNotCompute;
2940 const SCEV* MaxBECount = CouldNotCompute;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002941 if (L->contains(FBB)) {
2942 // Both conditions must be false for the loop to continue executing.
2943 // Choose the less conservative count.
Dan Gohman2cc450e2009-06-22 23:28:56 +00002944 if (BTI0.Exact == CouldNotCompute || BTI1.Exact == CouldNotCompute)
2945 BECount = CouldNotCompute;
Dan Gohmanac958b32009-06-22 15:09:28 +00002946 else
2947 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002948 if (BTI0.Max == CouldNotCompute)
2949 MaxBECount = BTI1.Max;
2950 else if (BTI1.Max == CouldNotCompute)
2951 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00002952 else
2953 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002954 } else {
2955 // Both conditions must be false for the loop to exit.
2956 assert(L->contains(TBB) && "Loop block has no successor in loop!");
2957 if (BTI0.Exact != CouldNotCompute && BTI1.Exact != CouldNotCompute)
2958 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
2959 if (BTI0.Max != CouldNotCompute && BTI1.Max != CouldNotCompute)
2960 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
2961 }
2962
2963 return BackedgeTakenInfo(BECount, MaxBECount);
2964 }
2965 }
2966
2967 // With an icmp, it may be feasible to compute an exact backedge-taken count.
2968 // Procede to the next level to examine the icmp.
2969 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
2970 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002971
Eli Friedman459d7292009-05-09 12:32:42 +00002972 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohman8e8b5232009-06-22 00:31:57 +00002973 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
2974}
2975
2976/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
2977/// backedge of the specified loop will execute if its exit condition
2978/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
2979ScalarEvolution::BackedgeTakenInfo
2980ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
2981 ICmpInst *ExitCond,
2982 BasicBlock *TBB,
2983 BasicBlock *FBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002984
2985 // If the condition was exit on true, convert the condition to exit on false
2986 ICmpInst::Predicate Cond;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002987 if (!L->contains(FBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002988 Cond = ExitCond->getPredicate();
2989 else
2990 Cond = ExitCond->getInversePredicate();
2991
2992 // Handle common loops like: for (X = "string"; *X; ++X)
2993 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2994 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002995 const SCEV* ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002996 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002997 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
2998 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
2999 return BackedgeTakenInfo(ItCnt,
3000 isa<SCEVConstant>(ItCnt) ? ItCnt :
3001 getConstant(APInt::getMaxValue(BitWidth)-1));
3002 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003003 }
3004
Owen Andersonecd0cd72009-06-22 21:39:50 +00003005 const SCEV* LHS = getSCEV(ExitCond->getOperand(0));
3006 const SCEV* RHS = getSCEV(ExitCond->getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003007
3008 // Try to evaluate any dependencies out of the loop.
Dan Gohmanaff14d62009-05-24 23:25:42 +00003009 LHS = getSCEVAtScope(LHS, L);
3010 RHS = getSCEVAtScope(RHS, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003011
Dan Gohman9bc642f2009-06-24 04:48:43 +00003012 // At this point, we would like to compute how many iterations of the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003013 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00003014 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3015 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003016 std::swap(LHS, RHS);
3017 Cond = ICmpInst::getSwappedPredicate(Cond);
3018 }
3019
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003020 // If we have a comparison of a chrec against a constant, try to use value
3021 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003022 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3023 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003024 if (AddRec->getLoop() == L) {
Eli Friedman459d7292009-05-09 12:32:42 +00003025 // Form the constant range.
3026 ConstantRange CompRange(
3027 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003028
Owen Andersonecd0cd72009-06-22 21:39:50 +00003029 const SCEV* Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman459d7292009-05-09 12:32:42 +00003030 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003031 }
3032
3033 switch (Cond) {
3034 case ICmpInst::ICMP_NE: { // while (X != Y)
3035 // Convert to: while (X-Y != 0)
Owen Andersonecd0cd72009-06-22 21:39:50 +00003036 const SCEV* TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003037 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3038 break;
3039 }
3040 case ICmpInst::ICMP_EQ: {
3041 // Convert to: while (X-Y == 0) // while (X == Y)
Owen Andersonecd0cd72009-06-22 21:39:50 +00003042 const SCEV* TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003043 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3044 break;
3045 }
3046 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003047 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3048 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003049 break;
3050 }
3051 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003052 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3053 getNotSCEV(RHS), L, true);
3054 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003055 break;
3056 }
3057 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003058 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3059 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003060 break;
3061 }
3062 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003063 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3064 getNotSCEV(RHS), L, false);
3065 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003066 break;
3067 }
3068 default:
3069#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003070 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003071 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00003072 errs() << "[unsigned] ";
3073 errs() << *LHS << " "
Dan Gohman9bc642f2009-06-24 04:48:43 +00003074 << Instruction::getOpcodeName(Instruction::ICmp)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003075 << " " << *RHS << "\n";
3076#endif
3077 break;
3078 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003079 return
Dan Gohman8e8b5232009-06-22 00:31:57 +00003080 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003081}
3082
3083static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00003084EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3085 ScalarEvolution &SE) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003086 const SCEV* InVal = SE.getConstant(C);
3087 const SCEV* Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003088 assert(isa<SCEVConstant>(Val) &&
3089 "Evaluation of SCEV at constant didn't fold correctly?");
3090 return cast<SCEVConstant>(Val)->getValue();
3091}
3092
3093/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3094/// and a GEP expression (missing the pointer index) indexing into it, return
3095/// the addressed element of the initializer or null if the index expression is
3096/// invalid.
3097static Constant *
3098GetAddressedElementFromGlobal(GlobalVariable *GV,
3099 const std::vector<ConstantInt*> &Indices) {
3100 Constant *Init = GV->getInitializer();
3101 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3102 uint64_t Idx = Indices[i]->getZExtValue();
3103 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3104 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3105 Init = cast<Constant>(CS->getOperand(Idx));
3106 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3107 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3108 Init = cast<Constant>(CA->getOperand(Idx));
3109 } else if (isa<ConstantAggregateZero>(Init)) {
3110 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3111 assert(Idx < STy->getNumElements() && "Bad struct index!");
3112 Init = Constant::getNullValue(STy->getElementType(Idx));
3113 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3114 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3115 Init = Constant::getNullValue(ATy->getElementType());
3116 } else {
3117 assert(0 && "Unknown constant aggregate type!");
3118 }
3119 return 0;
3120 } else {
3121 return 0; // Unknown initializer type
3122 }
3123 }
3124 return Init;
3125}
3126
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003127/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3128/// 'icmp op load X, cst', try to see if we can compute the backedge
3129/// execution count.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003130const SCEV *
3131ScalarEvolution::ComputeLoadConstantCompareBackedgeTakenCount(
3132 LoadInst *LI,
3133 Constant *RHS,
3134 const Loop *L,
3135 ICmpInst::Predicate predicate) {
Dan Gohman0c850912009-06-06 14:37:11 +00003136 if (LI->isVolatile()) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003137
3138 // Check to see if the loaded pointer is a getelementptr of a global.
3139 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman0c850912009-06-06 14:37:11 +00003140 if (!GEP) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003141
3142 // Make sure that it is really a constant global we are gepping, with an
3143 // initializer, and make sure the first IDX is really 0.
3144 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3145 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3146 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3147 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman0c850912009-06-06 14:37:11 +00003148 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003149
3150 // Okay, we allow one non-constant index into the GEP instruction.
3151 Value *VarIdx = 0;
3152 std::vector<ConstantInt*> Indexes;
3153 unsigned VarIdxNum = 0;
3154 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3155 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3156 Indexes.push_back(CI);
3157 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman0c850912009-06-06 14:37:11 +00003158 if (VarIdx) return CouldNotCompute; // Multiple non-constant idx's.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003159 VarIdx = GEP->getOperand(i);
3160 VarIdxNum = i-2;
3161 Indexes.push_back(0);
3162 }
3163
3164 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3165 // Check to see if X is a loop variant variable value now.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003166 const SCEV* Idx = getSCEV(VarIdx);
Dan Gohmanaff14d62009-05-24 23:25:42 +00003167 Idx = getSCEVAtScope(Idx, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003168
3169 // We can only recognize very limited forms of loop index expressions, in
3170 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00003171 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003172 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3173 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3174 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman0c850912009-06-06 14:37:11 +00003175 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003176
3177 unsigned MaxSteps = MaxBruteForceIterations;
3178 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3179 ConstantInt *ItCst =
Dan Gohman8fd520a2009-06-15 22:12:54 +00003180 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003181 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003182
3183 // Form the GEP offset.
3184 Indexes[VarIdxNum] = Val;
3185
3186 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3187 if (Result == 0) break; // Cannot compute!
3188
3189 // Evaluate the condition for this iteration.
3190 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3191 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3192 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3193#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003194 errs() << "\n***\n*** Computed loop count " << *ItCst
3195 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3196 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003197#endif
3198 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003199 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003200 }
3201 }
Dan Gohman0c850912009-06-06 14:37:11 +00003202 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003203}
3204
3205
3206/// CanConstantFold - Return true if we can constant fold an instruction of the
3207/// specified type, assuming that all operands were constants.
3208static bool CanConstantFold(const Instruction *I) {
3209 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3210 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3211 return true;
3212
3213 if (const CallInst *CI = dyn_cast<CallInst>(I))
3214 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00003215 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003216 return false;
3217}
3218
3219/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3220/// in the loop that V is derived from. We allow arbitrary operations along the
3221/// way, but the operands of an operation must either be constants or a value
3222/// derived from a constant PHI. If this expression does not fit with these
3223/// constraints, return null.
3224static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3225 // If this is not an instruction, or if this is an instruction outside of the
3226 // loop, it can't be derived from a loop PHI.
3227 Instruction *I = dyn_cast<Instruction>(V);
3228 if (I == 0 || !L->contains(I->getParent())) return 0;
3229
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003230 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003231 if (L->getHeader() == I->getParent())
3232 return PN;
3233 else
3234 // We don't currently keep track of the control flow needed to evaluate
3235 // PHIs, so we cannot handle PHIs inside of loops.
3236 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003237 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003238
3239 // If we won't be able to constant fold this expression even if the operands
3240 // are constants, return early.
3241 if (!CanConstantFold(I)) return 0;
3242
3243 // Otherwise, we can evaluate this instruction if all of its operands are
3244 // constant or derived from a PHI node themselves.
3245 PHINode *PHI = 0;
3246 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3247 if (!(isa<Constant>(I->getOperand(Op)) ||
3248 isa<GlobalValue>(I->getOperand(Op)))) {
3249 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3250 if (P == 0) return 0; // Not evolving from PHI
3251 if (PHI == 0)
3252 PHI = P;
3253 else if (PHI != P)
3254 return 0; // Evolving from multiple different PHIs.
3255 }
3256
3257 // This is a expression evolving from a constant PHI!
3258 return PHI;
3259}
3260
3261/// EvaluateExpression - Given an expression that passes the
3262/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3263/// in the loop has the value PHIVal. If we can't fold this expression for some
3264/// reason, return null.
3265static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3266 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003267 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003268 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003269 Instruction *I = cast<Instruction>(V);
3270
3271 std::vector<Constant*> Operands;
3272 Operands.resize(I->getNumOperands());
3273
3274 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3275 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3276 if (Operands[i] == 0) return 0;
3277 }
3278
Chris Lattnerd6e56912007-12-10 22:53:04 +00003279 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3280 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3281 &Operands[0], Operands.size());
3282 else
3283 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3284 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003285}
3286
3287/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3288/// in the header of its containing loop, we know the loop executes a
3289/// constant number of times, and the PHI node is just a recurrence
3290/// involving constants, fold it.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003291Constant *
3292ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
3293 const APInt& BEs,
3294 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003295 std::map<PHINode*, Constant*>::iterator I =
3296 ConstantEvolutionLoopExitValue.find(PN);
3297 if (I != ConstantEvolutionLoopExitValue.end())
3298 return I->second;
3299
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003300 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003301 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3302
3303 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3304
3305 // Since the loop is canonicalized, the PHI node must have two entries. One
3306 // entry must be a constant (coming in from outside of the loop), and the
3307 // second must be derived from the same PHI.
3308 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3309 Constant *StartCST =
3310 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3311 if (StartCST == 0)
3312 return RetVal = 0; // Must be a constant.
3313
3314 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3315 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3316 if (PN2 != PN)
3317 return RetVal = 0; // Not derived from same PHI.
3318
3319 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003320 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003321 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3322
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003323 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003324 unsigned IterationNum = 0;
3325 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3326 if (IterationNum == NumIterations)
3327 return RetVal = PHIVal; // Got exit value!
3328
3329 // Compute the value of the PHI node for the next iteration.
3330 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3331 if (NextPHI == PHIVal)
3332 return RetVal = NextPHI; // Stopped evolving!
3333 if (NextPHI == 0)
3334 return 0; // Couldn't evaluate!
3335 PHIVal = NextPHI;
3336 }
3337}
3338
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003339/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003340/// constant number of times (the condition evolves only from constants),
3341/// try to evaluate a few iterations of the loop until we get the exit
3342/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman0c850912009-06-06 14:37:11 +00003343/// evaluate the trip count of the loop, return CouldNotCompute.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003344const SCEV *
3345ScalarEvolution::ComputeBackedgeTakenCountExhaustively(const Loop *L,
3346 Value *Cond,
3347 bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003348 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman0c850912009-06-06 14:37:11 +00003349 if (PN == 0) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003350
3351 // Since the loop is canonicalized, the PHI node must have two entries. One
3352 // entry must be a constant (coming in from outside of the loop), and the
3353 // second must be derived from the same PHI.
3354 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3355 Constant *StartCST =
3356 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman0c850912009-06-06 14:37:11 +00003357 if (StartCST == 0) return CouldNotCompute; // Must be a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003358
3359 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3360 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman0c850912009-06-06 14:37:11 +00003361 if (PN2 != PN) return CouldNotCompute; // Not derived from same PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003362
3363 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3364 // the loop symbolically to determine when the condition gets a value of
3365 // "ExitWhen".
3366 unsigned IterationNum = 0;
3367 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3368 for (Constant *PHIVal = StartCST;
3369 IterationNum != MaxIterations; ++IterationNum) {
3370 ConstantInt *CondVal =
3371 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3372
3373 // Couldn't symbolically evaluate.
Dan Gohman0c850912009-06-06 14:37:11 +00003374 if (!CondVal) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003375
3376 if (CondVal->getValue() == uint64_t(ExitWhen)) {
3377 ConstantEvolutionLoopExitValue[PN] = PHIVal;
3378 ++NumBruteForceTripCountsComputed;
Dan Gohman8fd520a2009-06-15 22:12:54 +00003379 return getConstant(Type::Int32Ty, IterationNum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003380 }
3381
3382 // Compute the value of the PHI node for the next iteration.
3383 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3384 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman0c850912009-06-06 14:37:11 +00003385 return CouldNotCompute; // Couldn't evaluate or not making progress...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003386 PHIVal = NextPHI;
3387 }
3388
3389 // Too many iterations were needed to evaluate.
Dan Gohman0c850912009-06-06 14:37:11 +00003390 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003391}
3392
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003393/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3394/// at the specified scope in the program. The L value specifies a loop
3395/// nest to evaluate the expression at, where null is the top-level or a
3396/// specified loop is immediately inside of the loop.
3397///
3398/// This method can be used to compute the exit value for a variable defined
3399/// in a loop by querying what the value will hold in the parent loop.
3400///
Dan Gohmanaff14d62009-05-24 23:25:42 +00003401/// In the case that a relevant loop exit value cannot be computed, the
3402/// original value V is returned.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003403const SCEV* ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003404 // FIXME: this should be turned into a virtual method on SCEV!
3405
3406 if (isa<SCEVConstant>(V)) return V;
3407
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003408 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003409 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003410 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003411 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003412 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003413 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3414 if (PHINode *PN = dyn_cast<PHINode>(I))
3415 if (PN->getParent() == LI->getHeader()) {
3416 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003417 // to see if the loop that contains it has a known backedge-taken
3418 // count. If so, we may be able to force computation of the exit
3419 // value.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003420 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003421 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003422 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003423 // Okay, we know how many times the containing loop executes. If
3424 // this is a constant evolving PHI node, get the final value at
3425 // the specified iteration number.
3426 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003427 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003428 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003429 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003430 }
3431 }
3432
3433 // Okay, this is an expression that we cannot symbolically evaluate
3434 // into a SCEV. Check to see if it's possible to symbolically evaluate
3435 // the arguments into constants, and if so, try to constant propagate the
3436 // result. This is particularly useful for computing loop exit values.
3437 if (CanConstantFold(I)) {
Dan Gohmanda0071e2009-05-08 20:47:27 +00003438 // Check to see if we've folded this instruction at this loop before.
3439 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3440 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3441 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3442 if (!Pair.second)
3443 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
3444
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003445 std::vector<Constant*> Operands;
3446 Operands.reserve(I->getNumOperands());
3447 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3448 Value *Op = I->getOperand(i);
3449 if (Constant *C = dyn_cast<Constant>(Op)) {
3450 Operands.push_back(C);
3451 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00003452 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00003453 // non-integer and non-pointer, don't even try to analyze them
3454 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00003455 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00003456 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003457
Owen Andersonecd0cd72009-06-22 21:39:50 +00003458 const SCEV* OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003459 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003460 Constant *C = SC->getValue();
3461 if (C->getType() != Op->getType())
3462 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3463 Op->getType(),
3464 false),
3465 C, Op->getType());
3466 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003467 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003468 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3469 if (C->getType() != Op->getType())
3470 C =
3471 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3472 Op->getType(),
3473 false),
3474 C, Op->getType());
3475 Operands.push_back(C);
3476 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003477 return V;
3478 } else {
3479 return V;
3480 }
3481 }
3482 }
Dan Gohman9bc642f2009-06-24 04:48:43 +00003483
Chris Lattnerd6e56912007-12-10 22:53:04 +00003484 Constant *C;
3485 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3486 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3487 &Operands[0], Operands.size());
3488 else
3489 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3490 &Operands[0], Operands.size());
Dan Gohmanda0071e2009-05-08 20:47:27 +00003491 Pair.first->second = C;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003492 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003493 }
3494 }
3495
3496 // This is some other type of SCEVUnknown, just return it.
3497 return V;
3498 }
3499
Dan Gohmanc76b5452009-05-04 22:02:23 +00003500 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003501 // Avoid performing the look-up in the common case where the specified
3502 // expression has no loop-variant portions.
3503 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003504 const SCEV* OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003505 if (OpAtScope != Comm->getOperand(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003506 // Okay, at least one of these operands is loop variant but might be
3507 // foldable. Build a new instance of the folded commutative expression.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003508 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
3509 Comm->op_begin()+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003510 NewOps.push_back(OpAtScope);
3511
3512 for (++i; i != e; ++i) {
3513 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003514 NewOps.push_back(OpAtScope);
3515 }
3516 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003517 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003518 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003519 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003520 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003521 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003522 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003523 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003524 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003525 }
3526 }
3527 // If we got here, all operands are loop invariant.
3528 return Comm;
3529 }
3530
Dan Gohmanc76b5452009-05-04 22:02:23 +00003531 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003532 const SCEV* LHS = getSCEVAtScope(Div->getLHS(), L);
3533 const SCEV* RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003534 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3535 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003536 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003537 }
3538
3539 // If this is a loop recurrence for a loop that does not contain L, then we
3540 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003541 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003542 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3543 // To evaluate this recurrence, we need to know how many times the AddRec
3544 // loop iterates. Compute this now.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003545 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman0c850912009-06-06 14:37:11 +00003546 if (BackedgeTakenCount == CouldNotCompute) return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003547
Eli Friedman7489ec92008-08-04 23:49:06 +00003548 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003549 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003550 }
Dan Gohmanaff14d62009-05-24 23:25:42 +00003551 return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003552 }
3553
Dan Gohmanc76b5452009-05-04 22:02:23 +00003554 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003555 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003556 if (Op == Cast->getOperand())
3557 return Cast; // must be loop invariant
3558 return getZeroExtendExpr(Op, Cast->getType());
3559 }
3560
Dan Gohmanc76b5452009-05-04 22:02:23 +00003561 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003562 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003563 if (Op == Cast->getOperand())
3564 return Cast; // must be loop invariant
3565 return getSignExtendExpr(Op, Cast->getType());
3566 }
3567
Dan Gohmanc76b5452009-05-04 22:02:23 +00003568 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003569 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003570 if (Op == Cast->getOperand())
3571 return Cast; // must be loop invariant
3572 return getTruncateExpr(Op, Cast->getType());
3573 }
3574
3575 assert(0 && "Unknown SCEV type!");
Daniel Dunbara95d96c2009-05-18 16:43:04 +00003576 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003577}
3578
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003579/// getSCEVAtScope - This is a convenience function which does
3580/// getSCEVAtScope(getSCEV(V), L).
Owen Andersonecd0cd72009-06-22 21:39:50 +00003581const SCEV* ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003582 return getSCEVAtScope(getSCEV(V), L);
3583}
3584
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003585/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3586/// following equation:
3587///
3588/// A * X = B (mod N)
3589///
3590/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3591/// A and B isn't important.
3592///
3593/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003594static const SCEV* SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003595 ScalarEvolution &SE) {
3596 uint32_t BW = A.getBitWidth();
3597 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3598 assert(A != 0 && "A must be non-zero.");
3599
3600 // 1. D = gcd(A, N)
3601 //
3602 // The gcd of A and N may have only one prime factor: 2. The number of
3603 // trailing zeros in A is its multiplicity
3604 uint32_t Mult2 = A.countTrailingZeros();
3605 // D = 2^Mult2
3606
3607 // 2. Check if B is divisible by D.
3608 //
3609 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3610 // is not less than multiplicity of this prime factor for D.
3611 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00003612 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003613
3614 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3615 // modulo (N / D).
3616 //
3617 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3618 // bit width during computations.
3619 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3620 APInt Mod(BW + 1, 0);
3621 Mod.set(BW - Mult2); // Mod = N / D
3622 APInt I = AD.multiplicativeInverse(Mod);
3623
3624 // 4. Compute the minimum unsigned root of the equation:
3625 // I * (B / D) mod (N / D)
3626 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3627
3628 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3629 // bits.
3630 return SE.getConstant(Result.trunc(BW));
3631}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003632
3633/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3634/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3635/// might be the same) or two SCEVCouldNotCompute objects.
3636///
Owen Andersonecd0cd72009-06-22 21:39:50 +00003637static std::pair<const SCEV*,const SCEV*>
Dan Gohman89f85052007-10-22 18:31:58 +00003638SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003639 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00003640 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3641 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3642 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003643
3644 // We currently can only solve this if the coefficients are constants.
3645 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003646 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003647 return std::make_pair(CNC, CNC);
3648 }
3649
3650 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3651 const APInt &L = LC->getValue()->getValue();
3652 const APInt &M = MC->getValue()->getValue();
3653 const APInt &N = NC->getValue()->getValue();
3654 APInt Two(BitWidth, 2);
3655 APInt Four(BitWidth, 4);
3656
Dan Gohman9bc642f2009-06-24 04:48:43 +00003657 {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003658 using namespace APIntOps;
3659 const APInt& C = L;
3660 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3661 // The B coefficient is M-N/2
3662 APInt B(M);
3663 B -= sdiv(N,Two);
3664
3665 // The A coefficient is N/2
3666 APInt A(N.sdiv(Two));
3667
3668 // Compute the B^2-4ac term.
3669 APInt SqrtTerm(B);
3670 SqrtTerm *= B;
3671 SqrtTerm -= Four * (A * C);
3672
3673 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3674 // integer value or else APInt::sqrt() will assert.
3675 APInt SqrtVal(SqrtTerm.sqrt());
3676
Dan Gohman9bc642f2009-06-24 04:48:43 +00003677 // Compute the two solutions for the quadratic formula.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003678 // The divisions must be performed as signed divisions.
3679 APInt NegB(-B);
3680 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00003681 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003682 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00003683 return std::make_pair(CNC, CNC);
3684 }
3685
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003686 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3687 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
3688
Dan Gohman9bc642f2009-06-24 04:48:43 +00003689 return std::make_pair(SE.getConstant(Solution1),
Dan Gohman89f85052007-10-22 18:31:58 +00003690 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003691 } // end APIntOps namespace
3692}
3693
3694/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman0c850912009-06-06 14:37:11 +00003695/// value to zero will execute. If not computable, return CouldNotCompute.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003696const SCEV* ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003697 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00003698 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003699 // If the value is already zero, the branch will execute zero times.
3700 if (C->getValue()->isZero()) return C;
Dan Gohman0c850912009-06-06 14:37:11 +00003701 return CouldNotCompute; // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003702 }
3703
Dan Gohmanbff6b582009-05-04 22:30:44 +00003704 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003705 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman0c850912009-06-06 14:37:11 +00003706 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003707
3708 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003709 // If this is an affine expression, the execution count of this branch is
3710 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003711 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003712 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003713 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003714 // equivalent to:
3715 //
3716 // Step*N = -Start (mod 2^BW)
3717 //
3718 // where BW is the common bit width of Start and Step.
3719
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003720 // Get the initial value for the loop.
Dan Gohman9bc642f2009-06-24 04:48:43 +00003721 const SCEV *Start = getSCEVAtScope(AddRec->getStart(),
3722 L->getParentLoop());
3723 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1),
3724 L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003725
Dan Gohmanc76b5452009-05-04 22:02:23 +00003726 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003727 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003728
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003729 // First, handle unitary steps.
3730 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003731 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003732 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3733 return Start; // N = Start (as unsigned)
3734
3735 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003736 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003737 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003738 -StartC->getValue()->getValue(),
3739 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003740 }
3741 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3742 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3743 // the quadratic equation to solve it.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003744 std::pair<const SCEV*,const SCEV*> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003745 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003746 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3747 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003748 if (R1) {
3749#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003750 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3751 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003752#endif
3753 // Pick the smallest positive root value.
3754 if (ConstantInt *CB =
Dan Gohman9bc642f2009-06-24 04:48:43 +00003755 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003756 R1->getValue(), R2->getValue()))) {
3757 if (CB->getZExtValue() == false)
3758 std::swap(R1, R2); // R1 is the minimum root now.
3759
3760 // We can only use this value if the chrec ends up with an exact zero
3761 // value at this index. When solving for "X*X != 5", for example, we
3762 // should not accept a root of 2.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003763 const SCEV* Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00003764 if (Val->isZero())
3765 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003766 }
3767 }
3768 }
3769
Dan Gohman0c850912009-06-06 14:37:11 +00003770 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003771}
3772
3773/// HowFarToNonZero - Return the number of times a backedge checking the
3774/// specified value for nonzero will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00003775/// CouldNotCompute
Owen Andersonecd0cd72009-06-22 21:39:50 +00003776const SCEV* ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003777 // Loops that look like: while (X == 0) are very strange indeed. We don't
3778 // handle them yet except for the trivial case. This could be expanded in the
3779 // future as needed.
3780
3781 // If the value is a constant, check to see if it is known to be non-zero
3782 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003783 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00003784 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003785 return getIntegerSCEV(0, C->getType());
Dan Gohman0c850912009-06-06 14:37:11 +00003786 return CouldNotCompute; // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003787 }
3788
3789 // We could implement others, but I really doubt anyone writes loops like
3790 // this, and if they did, they would already be constant folded.
Dan Gohman0c850912009-06-06 14:37:11 +00003791 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003792}
3793
Dan Gohmanab157b22009-05-18 15:36:09 +00003794/// getLoopPredecessor - If the given loop's header has exactly one unique
3795/// predecessor outside the loop, return it. Otherwise return null.
3796///
3797BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3798 BasicBlock *Header = L->getHeader();
3799 BasicBlock *Pred = 0;
3800 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3801 PI != E; ++PI)
3802 if (!L->contains(*PI)) {
3803 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3804 Pred = *PI;
3805 }
3806 return Pred;
3807}
3808
Dan Gohman1cddf972008-09-15 22:18:04 +00003809/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3810/// (which may not be an immediate predecessor) which has exactly one
3811/// successor from which BB is reachable, or null if no such block is
3812/// found.
3813///
3814BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003815ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00003816 // If the block has a unique predecessor, then there is no path from the
3817 // predecessor to the block that does not go through the direct edge
3818 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00003819 if (BasicBlock *Pred = BB->getSinglePredecessor())
3820 return Pred;
3821
3822 // A loop's header is defined to be a block that dominates the loop.
Dan Gohmanab157b22009-05-18 15:36:09 +00003823 // If the header has a unique predecessor outside the loop, it must be
3824 // a block that has exactly one successor that can reach the loop.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003825 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanab157b22009-05-18 15:36:09 +00003826 return getLoopPredecessor(L);
Dan Gohman1cddf972008-09-15 22:18:04 +00003827
3828 return 0;
3829}
3830
Dan Gohmanbc1e3472009-06-20 00:35:32 +00003831/// HasSameValue - SCEV structural equivalence is usually sufficient for
3832/// testing whether two expressions are equal, however for the purposes of
3833/// looking for a condition guarding a loop, it can be useful to be a little
3834/// more general, since a front-end may have replicated the controlling
3835/// expression.
3836///
Owen Andersonecd0cd72009-06-22 21:39:50 +00003837static bool HasSameValue(const SCEV* A, const SCEV* B) {
Dan Gohmanbc1e3472009-06-20 00:35:32 +00003838 // Quick check to see if they are the same SCEV.
3839 if (A == B) return true;
3840
3841 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
3842 // two different instructions with the same value. Check for this case.
3843 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
3844 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
3845 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
3846 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
3847 if (AI->isIdenticalTo(BI))
3848 return true;
3849
3850 // Otherwise assume they may have a different value.
3851 return false;
3852}
3853
Dan Gohmancacd2012009-02-12 22:19:27 +00003854/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman1116ea72009-04-30 20:48:53 +00003855/// a conditional between LHS and RHS. This is used to help avoid max
3856/// expressions in loop trip counts.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003857bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman1116ea72009-04-30 20:48:53 +00003858 ICmpInst::Predicate Pred,
Dan Gohmanbff6b582009-05-04 22:30:44 +00003859 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8b938182009-05-18 16:03:58 +00003860 // Interpret a null as meaning no loop, where there is obviously no guard
3861 // (interprocedural conditions notwithstanding).
3862 if (!L) return false;
3863
Dan Gohmanab157b22009-05-18 15:36:09 +00003864 BasicBlock *Predecessor = getLoopPredecessor(L);
3865 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003866
Dan Gohmanab157b22009-05-18 15:36:09 +00003867 // Starting at the loop predecessor, climb up the predecessor chain, as long
3868 // as there are predecessors that can be found that have unique successors
Dan Gohman1cddf972008-09-15 22:18:04 +00003869 // leading to the original header.
Dan Gohmanab157b22009-05-18 15:36:09 +00003870 for (; Predecessor;
3871 PredecessorDest = Predecessor,
3872 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00003873
3874 BranchInst *LoopEntryPredicate =
Dan Gohmanab157b22009-05-18 15:36:09 +00003875 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00003876 if (!LoopEntryPredicate ||
3877 LoopEntryPredicate->isUnconditional())
3878 continue;
3879
Dan Gohman423ed6c2009-06-24 01:18:18 +00003880 if (isNecessaryCond(LoopEntryPredicate->getCondition(), Pred, LHS, RHS,
3881 LoopEntryPredicate->getSuccessor(0) != PredecessorDest))
Dan Gohmanab678fb2008-08-12 20:17:31 +00003882 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003883 }
3884
Dan Gohmanab678fb2008-08-12 20:17:31 +00003885 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003886}
3887
Dan Gohman423ed6c2009-06-24 01:18:18 +00003888/// isNecessaryCond - Test whether the given CondValue value is a condition
3889/// which is at least as strict as the one described by Pred, LHS, and RHS.
3890bool ScalarEvolution::isNecessaryCond(Value *CondValue,
3891 ICmpInst::Predicate Pred,
3892 const SCEV *LHS, const SCEV *RHS,
3893 bool Inverse) {
3894 // Recursivly handle And and Or conditions.
3895 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CondValue)) {
3896 if (BO->getOpcode() == Instruction::And) {
3897 if (!Inverse)
3898 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
3899 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
3900 } else if (BO->getOpcode() == Instruction::Or) {
3901 if (Inverse)
3902 return isNecessaryCond(BO->getOperand(0), Pred, LHS, RHS, Inverse) ||
3903 isNecessaryCond(BO->getOperand(1), Pred, LHS, RHS, Inverse);
3904 }
3905 }
3906
3907 ICmpInst *ICI = dyn_cast<ICmpInst>(CondValue);
3908 if (!ICI) return false;
3909
3910 // Now that we found a conditional branch that dominates the loop, check to
3911 // see if it is the comparison we are looking for.
3912 Value *PreCondLHS = ICI->getOperand(0);
3913 Value *PreCondRHS = ICI->getOperand(1);
3914 ICmpInst::Predicate Cond;
3915 if (Inverse)
3916 Cond = ICI->getInversePredicate();
3917 else
3918 Cond = ICI->getPredicate();
3919
3920 if (Cond == Pred)
3921 ; // An exact match.
3922 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3923 ; // The actual condition is beyond sufficient.
3924 else
3925 // Check a few special cases.
3926 switch (Cond) {
3927 case ICmpInst::ICMP_UGT:
3928 if (Pred == ICmpInst::ICMP_ULT) {
3929 std::swap(PreCondLHS, PreCondRHS);
3930 Cond = ICmpInst::ICMP_ULT;
3931 break;
3932 }
3933 return false;
3934 case ICmpInst::ICMP_SGT:
3935 if (Pred == ICmpInst::ICMP_SLT) {
3936 std::swap(PreCondLHS, PreCondRHS);
3937 Cond = ICmpInst::ICMP_SLT;
3938 break;
3939 }
3940 return false;
3941 case ICmpInst::ICMP_NE:
3942 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3943 // so check for this case by checking if the NE is comparing against
3944 // a minimum or maximum constant.
3945 if (!ICmpInst::isTrueWhenEqual(Pred))
3946 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3947 const APInt &A = CI->getValue();
3948 switch (Pred) {
3949 case ICmpInst::ICMP_SLT:
3950 if (A.isMaxSignedValue()) break;
3951 return false;
3952 case ICmpInst::ICMP_SGT:
3953 if (A.isMinSignedValue()) break;
3954 return false;
3955 case ICmpInst::ICMP_ULT:
3956 if (A.isMaxValue()) break;
3957 return false;
3958 case ICmpInst::ICMP_UGT:
3959 if (A.isMinValue()) break;
3960 return false;
3961 default:
3962 return false;
3963 }
3964 Cond = ICmpInst::ICMP_NE;
3965 // NE is symmetric but the original comparison may not be. Swap
3966 // the operands if necessary so that they match below.
3967 if (isa<SCEVConstant>(LHS))
3968 std::swap(PreCondLHS, PreCondRHS);
3969 break;
3970 }
3971 return false;
3972 default:
3973 // We weren't able to reconcile the condition.
3974 return false;
3975 }
3976
3977 if (!PreCondLHS->getType()->isInteger()) return false;
3978
3979 const SCEV *PreCondLHSSCEV = getSCEV(PreCondLHS);
3980 const SCEV *PreCondRHSSCEV = getSCEV(PreCondRHS);
3981 return (HasSameValue(LHS, PreCondLHSSCEV) &&
3982 HasSameValue(RHS, PreCondRHSSCEV)) ||
3983 (HasSameValue(LHS, getNotSCEV(PreCondRHSSCEV)) &&
3984 HasSameValue(RHS, getNotSCEV(PreCondLHSSCEV)));
3985}
3986
Dan Gohmand2b62c42009-06-21 23:46:38 +00003987/// getBECount - Subtract the end and start values and divide by the step,
3988/// rounding up, to get the number of times the backedge is executed. Return
3989/// CouldNotCompute if an intermediate computation overflows.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003990const SCEV* ScalarEvolution::getBECount(const SCEV* Start,
3991 const SCEV* End,
3992 const SCEV* Step) {
Dan Gohmand2b62c42009-06-21 23:46:38 +00003993 const Type *Ty = Start->getType();
Owen Andersonecd0cd72009-06-22 21:39:50 +00003994 const SCEV* NegOne = getIntegerSCEV(-1, Ty);
3995 const SCEV* Diff = getMinusSCEV(End, Start);
3996 const SCEV* RoundUp = getAddExpr(Step, NegOne);
Dan Gohmand2b62c42009-06-21 23:46:38 +00003997
3998 // Add an adjustment to the difference between End and Start so that
3999 // the division will effectively round up.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004000 const SCEV* Add = getAddExpr(Diff, RoundUp);
Dan Gohmand2b62c42009-06-21 23:46:38 +00004001
4002 // Check Add for unsigned overflow.
4003 // TODO: More sophisticated things could be done here.
4004 const Type *WideTy = IntegerType::get(getTypeSizeInBits(Ty) + 1);
Owen Andersonecd0cd72009-06-22 21:39:50 +00004005 const SCEV* OperandExtendedAdd =
Dan Gohmand2b62c42009-06-21 23:46:38 +00004006 getAddExpr(getZeroExtendExpr(Diff, WideTy),
4007 getZeroExtendExpr(RoundUp, WideTy));
4008 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
4009 return CouldNotCompute;
4010
4011 return getUDivExpr(Add, Step);
4012}
4013
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004014/// HowManyLessThans - Return the number of times a backedge containing the
4015/// specified less-than comparison will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00004016/// CouldNotCompute.
Dan Gohman9bc642f2009-06-24 04:48:43 +00004017ScalarEvolution::BackedgeTakenInfo
4018ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
4019 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004020 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman0c850912009-06-06 14:37:11 +00004021 if (!RHS->isLoopInvariant(L)) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004022
Dan Gohmanbff6b582009-05-04 22:30:44 +00004023 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004024 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman0c850912009-06-06 14:37:11 +00004025 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004026
4027 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00004028 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004029 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Owen Andersonecd0cd72009-06-22 21:39:50 +00004030 const SCEV* Step = AddRec->getStepRecurrence(*this);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004031
4032 // TODO: handle non-constant strides.
4033 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4034 if (!CStep || CStep->isZero())
Dan Gohman0c850912009-06-06 14:37:11 +00004035 return CouldNotCompute;
Dan Gohmanf8bc8e82009-05-18 15:22:39 +00004036 if (CStep->isOne()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004037 // With unit stride, the iteration never steps past the limit value.
4038 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4039 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4040 // Test whether a positive iteration iteration can step past the limit
4041 // value and past the maximum value for its type in a single step.
4042 if (isSigned) {
4043 APInt Max = APInt::getSignedMaxValue(BitWidth);
4044 if ((Max - CStep->getValue()->getValue())
4045 .slt(CLimit->getValue()->getValue()))
Dan Gohman0c850912009-06-06 14:37:11 +00004046 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004047 } else {
4048 APInt Max = APInt::getMaxValue(BitWidth);
4049 if ((Max - CStep->getValue()->getValue())
4050 .ult(CLimit->getValue()->getValue()))
Dan Gohman0c850912009-06-06 14:37:11 +00004051 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004052 }
4053 } else
4054 // TODO: handle non-constant limit values below.
Dan Gohman0c850912009-06-06 14:37:11 +00004055 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004056 } else
4057 // TODO: handle negative strides below.
Dan Gohman0c850912009-06-06 14:37:11 +00004058 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004059
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004060 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4061 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4062 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00004063 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004064
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004065 // First, we get the value of the LHS in the first iteration: n
Owen Andersonecd0cd72009-06-22 21:39:50 +00004066 const SCEV* Start = AddRec->getOperand(0);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004067
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004068 // Determine the minimum constant start value.
Dan Gohman9bc642f2009-06-24 04:48:43 +00004069 const SCEV *MinStart = isa<SCEVConstant>(Start) ? Start :
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004070 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
4071 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004072
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004073 // If we know that the condition is true in order to enter the loop,
4074 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohmanc8a29272009-05-24 23:45:28 +00004075 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4076 // the division must round up.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004077 const SCEV* End = RHS;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004078 if (!isLoopGuardedByCond(L,
4079 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
4080 getMinusSCEV(Start, Step), RHS))
4081 End = isSigned ? getSMaxExpr(RHS, Start)
4082 : getUMaxExpr(RHS, Start);
4083
4084 // Determine the maximum constant end value.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004085 const SCEV* MaxEnd =
Dan Gohman92369c32009-06-20 00:32:22 +00004086 isa<SCEVConstant>(End) ? End :
4087 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth)
4088 .ashr(GetMinSignBits(End) - 1) :
4089 APInt::getMaxValue(BitWidth)
4090 .lshr(GetMinLeadingZeros(End)));
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004091
4092 // Finally, we subtract these two values and divide, rounding up, to get
4093 // the number of times the backedge is executed.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004094 const SCEV* BECount = getBECount(Start, End, Step);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004095
4096 // The maximum backedge count is similar, except using the minimum start
4097 // value and the maximum end value.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004098 const SCEV* MaxBECount = getBECount(MinStart, MaxEnd, Step);;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004099
4100 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004101 }
4102
Dan Gohman0c850912009-06-06 14:37:11 +00004103 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004104}
4105
4106/// getNumIterationsInRange - Return the number of iterations of this loop that
4107/// produce values in the specified constant range. Another way of looking at
4108/// this is that it returns the first iteration number where the value is not in
4109/// the condition, thus computing the exit count. If the iteration count can't
4110/// be computed, an instance of SCEVCouldNotCompute is returned.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004111const SCEV* SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman9bc642f2009-06-24 04:48:43 +00004112 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004113 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004114 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004115
4116 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00004117 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004118 if (!SC->getValue()->isZero()) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00004119 SmallVector<const SCEV*, 4> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004120 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Owen Andersonecd0cd72009-06-22 21:39:50 +00004121 const SCEV* Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00004122 if (const SCEVAddRecExpr *ShiftedAddRec =
4123 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004124 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00004125 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004126 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004127 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004128 }
4129
4130 // The only time we can solve this is when we have all constant indices.
4131 // Otherwise, we cannot determine the overflow conditions.
4132 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4133 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004134 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004135
4136
4137 // Okay at this point we know that all elements of the chrec are constants and
4138 // that the start element is zero.
4139
4140 // First check to see if the range contains zero. If not, the first
4141 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00004142 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00004143 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman8fd520a2009-06-15 22:12:54 +00004144 return SE.getIntegerSCEV(0, getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004145
4146 if (isAffine()) {
4147 // If this is an affine expression then we have this situation:
4148 // Solve {0,+,A} in Range === Ax in Range
4149
4150 // We know that zero is in the range. If A is positive then we know that
4151 // the upper value of the range must be the first possible exit value.
4152 // If A is negative then the lower of the range is the last possible loop
4153 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00004154 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004155 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4156 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
4157
4158 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00004159 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004160 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
4161
4162 // Evaluate at the exit value. If we really did fall out of the valid
4163 // range, then we computed our trip count, otherwise wrap around or other
4164 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00004165 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004166 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004167 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004168
4169 // Ensure that the previous value is in the range. This is a sanity check.
4170 assert(Range.contains(
Dan Gohman9bc642f2009-06-24 04:48:43 +00004171 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00004172 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004173 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00004174 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004175 } else if (isQuadratic()) {
4176 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4177 // quadratic equation to solve it. To do this, we must frame our problem in
4178 // terms of figuring out when zero is crossed, instead of when
4179 // Range.getUpper() is crossed.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004180 SmallVector<const SCEV*, 4> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004181 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Owen Andersonecd0cd72009-06-22 21:39:50 +00004182 const SCEV* NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004183
4184 // Next, solve the constructed addrec
Owen Andersonecd0cd72009-06-22 21:39:50 +00004185 std::pair<const SCEV*,const SCEV*> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00004186 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004187 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4188 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004189 if (R1) {
4190 // Pick the smallest positive root value.
4191 if (ConstantInt *CB =
Dan Gohman9bc642f2009-06-24 04:48:43 +00004192 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004193 R1->getValue(), R2->getValue()))) {
4194 if (CB->getZExtValue() == false)
4195 std::swap(R1, R2); // R1 is the minimum root now.
4196
4197 // Make sure the root is not off by one. The returned iteration should
4198 // not be in the range, but the previous one should be. When solving
4199 // for "X*X < 5", for example, we should not return a root of 2.
4200 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00004201 R1->getValue(),
4202 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004203 if (Range.contains(R1Val->getValue())) {
4204 // The next iteration must be out of the range...
4205 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
4206
Dan Gohman89f85052007-10-22 18:31:58 +00004207 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004208 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00004209 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00004210 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004211 }
4212
4213 // If R1 was not in the range, then it is a good return value. Make
4214 // sure that R1-1 WAS in the range though, just in case.
4215 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00004216 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004217 if (Range.contains(R1Val->getValue()))
4218 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00004219 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004220 }
4221 }
4222 }
4223
Dan Gohman0ad08b02009-04-18 17:58:19 +00004224 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004225}
4226
4227
4228
4229//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00004230// SCEVCallbackVH Class Implementation
4231//===----------------------------------------------------------------------===//
4232
Dan Gohman999d14e2009-05-19 19:22:47 +00004233void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004234 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4235 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4236 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004237 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4238 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004239 SE->Scalars.erase(getValPtr());
4240 // this now dangles!
4241}
4242
Dan Gohman999d14e2009-05-19 19:22:47 +00004243void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004244 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4245
4246 // Forget all the expressions associated with users of the old value,
4247 // so that future queries will recompute the expressions using the new
4248 // value.
4249 SmallVector<User *, 16> Worklist;
4250 Value *Old = getValPtr();
4251 bool DeleteOld = false;
4252 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4253 UI != UE; ++UI)
4254 Worklist.push_back(*UI);
4255 while (!Worklist.empty()) {
4256 User *U = Worklist.pop_back_val();
4257 // Deleting the Old value will cause this to dangle. Postpone
4258 // that until everything else is done.
4259 if (U == Old) {
4260 DeleteOld = true;
4261 continue;
4262 }
4263 if (PHINode *PN = dyn_cast<PHINode>(U))
4264 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004265 if (Instruction *I = dyn_cast<Instruction>(U))
4266 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004267 if (SE->Scalars.erase(U))
4268 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4269 UI != UE; ++UI)
4270 Worklist.push_back(*UI);
4271 }
4272 if (DeleteOld) {
4273 if (PHINode *PN = dyn_cast<PHINode>(Old))
4274 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004275 if (Instruction *I = dyn_cast<Instruction>(Old))
4276 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004277 SE->Scalars.erase(Old);
4278 // this now dangles!
4279 }
4280 // this may dangle!
4281}
4282
Dan Gohman999d14e2009-05-19 19:22:47 +00004283ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohmanbff6b582009-05-04 22:30:44 +00004284 : CallbackVH(V), SE(se) {}
4285
4286//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004287// ScalarEvolution Class Implementation
4288//===----------------------------------------------------------------------===//
4289
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004290ScalarEvolution::ScalarEvolution()
Owen Andersonb70139d2009-06-22 21:57:23 +00004291 : FunctionPass(&ID), CouldNotCompute(new SCEVCouldNotCompute()) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004292}
4293
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004294bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004295 this->F = &F;
4296 LI = &getAnalysis<LoopInfo>();
4297 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004298 return false;
4299}
4300
4301void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004302 Scalars.clear();
4303 BackedgeTakenCounts.clear();
4304 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanda0071e2009-05-08 20:47:27 +00004305 ValuesAtScopes.clear();
Dan Gohman9bc642f2009-06-24 04:48:43 +00004306
Owen Andersonc48fbfe2009-06-22 18:25:46 +00004307 for (std::map<ConstantInt*, SCEVConstant*>::iterator
4308 I = SCEVConstants.begin(), E = SCEVConstants.end(); I != E; ++I)
4309 delete I->second;
4310 for (std::map<std::pair<const SCEV*, const Type*>,
4311 SCEVTruncateExpr*>::iterator I = SCEVTruncates.begin(),
4312 E = SCEVTruncates.end(); I != E; ++I)
4313 delete I->second;
4314 for (std::map<std::pair<const SCEV*, const Type*>,
4315 SCEVZeroExtendExpr*>::iterator I = SCEVZeroExtends.begin(),
4316 E = SCEVZeroExtends.end(); I != E; ++I)
4317 delete I->second;
4318 for (std::map<std::pair<unsigned, std::vector<const SCEV*> >,
4319 SCEVCommutativeExpr*>::iterator I = SCEVCommExprs.begin(),
4320 E = SCEVCommExprs.end(); I != E; ++I)
4321 delete I->second;
4322 for (std::map<std::pair<const SCEV*, const SCEV*>, SCEVUDivExpr*>::iterator
4323 I = SCEVUDivs.begin(), E = SCEVUDivs.end(); I != E; ++I)
4324 delete I->second;
4325 for (std::map<std::pair<const SCEV*, const Type*>,
4326 SCEVSignExtendExpr*>::iterator I = SCEVSignExtends.begin(),
4327 E = SCEVSignExtends.end(); I != E; ++I)
4328 delete I->second;
4329 for (std::map<std::pair<const Loop *, std::vector<const SCEV*> >,
4330 SCEVAddRecExpr*>::iterator I = SCEVAddRecExprs.begin(),
4331 E = SCEVAddRecExprs.end(); I != E; ++I)
4332 delete I->second;
4333 for (std::map<Value*, SCEVUnknown*>::iterator I = SCEVUnknowns.begin(),
4334 E = SCEVUnknowns.end(); I != E; ++I)
4335 delete I->second;
Dan Gohman9bc642f2009-06-24 04:48:43 +00004336
Owen Andersonc48fbfe2009-06-22 18:25:46 +00004337 SCEVConstants.clear();
4338 SCEVTruncates.clear();
4339 SCEVZeroExtends.clear();
4340 SCEVCommExprs.clear();
4341 SCEVUDivs.clear();
4342 SCEVSignExtends.clear();
4343 SCEVAddRecExprs.clear();
4344 SCEVUnknowns.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004345}
4346
4347void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4348 AU.setPreservesAll();
4349 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00004350}
4351
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004352bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004353 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004354}
4355
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004356static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004357 const Loop *L) {
4358 // Print all inner loops first
4359 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4360 PrintLoopInfo(OS, SE, *I);
4361
Nick Lewyckye5da1912008-01-02 02:49:20 +00004362 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004363
Devang Patel02451fa2007-08-21 00:31:24 +00004364 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004365 L->getExitBlocks(ExitBlocks);
4366 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00004367 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004368
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004369 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4370 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004371 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004372 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004373 }
4374
Nick Lewyckye5da1912008-01-02 02:49:20 +00004375 OS << "\n";
Dan Gohmanb6b9e9e2009-06-24 00:33:16 +00004376 OS << "Loop " << L->getHeader()->getName() << ": ";
4377
4378 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
4379 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
4380 } else {
4381 OS << "Unpredictable max backedge-taken count. ";
4382 }
4383
4384 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004385}
4386
Dan Gohman13058cc2009-04-21 00:47:46 +00004387void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004388 // ScalarEvolution's implementaiton of the print method is to print
4389 // out SCEV values of all instructions that are interesting. Doing
4390 // this potentially causes it to create new SCEV objects though,
4391 // which technically conflicts with the const qualifier. This isn't
4392 // observable from outside the class though (the hasSCEV function
4393 // notwithstanding), so casting away the const isn't dangerous.
4394 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004395
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004396 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004397 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00004398 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004399 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00004400 OS << " --> ";
Owen Andersonecd0cd72009-06-22 21:39:50 +00004401 const SCEV* SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004402 SV->print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004403
Dan Gohman8db598a2009-06-19 17:49:54 +00004404 const Loop *L = LI->getLoopFor((*I).getParent());
4405
Owen Andersonecd0cd72009-06-22 21:39:50 +00004406 const SCEV* AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman8db598a2009-06-19 17:49:54 +00004407 if (AtUse != SV) {
4408 OS << " --> ";
4409 AtUse->print(OS);
4410 }
4411
4412 if (L) {
Dan Gohmane5b60842009-06-18 00:37:45 +00004413 OS << "\t\t" "Exits: ";
Owen Andersonecd0cd72009-06-22 21:39:50 +00004414 const SCEV* ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanaff14d62009-05-24 23:25:42 +00004415 if (!ExitValue->isLoopInvariant(L)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004416 OS << "<<Unknown>>";
4417 } else {
4418 OS << *ExitValue;
4419 }
4420 }
4421
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004422 OS << "\n";
4423 }
4424
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004425 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4426 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4427 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004428}
Dan Gohman13058cc2009-04-21 00:47:46 +00004429
4430void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4431 raw_os_ostream OS(o);
4432 print(OS, M);
4433}